Link Search Menu Expand Document

Types

Table of Contents

  1. Primitives & Wrapper Classes
  2. Numbers
  3. booleans
  4. Using Objects

Primitives & Wrapper Classes

Every primitive type has an Object that is called a wrapper class that essentially represents the same value, but as an object, for example:

  • Integer for int
  • Double for double
  • Boolean for boolean
  • Character for char

While these do represent the same values and can for all intents and purposes be used the same, you should always use the primitive type over the wrapper class whenever possible. There are some cases where you need to use the wrapper class (making an ArrayList or other data structure to contain a primitive type), but you should always prefer using the primitive type when possible.

Numbers

ints and doubles both represent numbers and technically, anything that can be represented by an int can also be represented by a double. However, just because it can doesn't mean it should. You should always use the type that best represents the value you are storing; a percentage might make sense as a double, but a count should always be a whole number and should therefore be an int. Make sure to consider what your variables are representing before making them all doubles when they shouldn't be.

booleans

Similarly, there are a few different ways you can represent a true/false (or yes/no) value. You could represent it with an int as a 1 or a 0, or even with a String as "yes" or "no" or "true" or "false", however, there's a better type to represent that. You're representing one of two values, and that is exactly what a boolean should be used for. booleans represent a true or false value, and should always be used when you're saving some variable that represents one of two states.

Using Objects

It's generally good to try to minimize the number of objects your program creates. For example, rather than creating a Scanner that takes in user input in every method where your program needs to take in user input, it would be better to create one Scanner that takes in user input in main and pass that Scanner as a parameter to all of the methods that need it. The same goes for Random objects, Graphics objects, and any other objects that do the same thing throughout your program. See the following two programs for examples:

Bad
public static void main(String[] args) {
    Scanner console = new Scanner(System.in);
    ...
    method1();
}

public static void method1() {
    Scanner console = new Scanner(System.in);
    ...
}
Good
public static void main(String[] args) {
    Scanner console = new Scanner(System.in);
    ...
    method1(console);
}

public static void method1(Scanner console) {
    ...
}