Chapter 4
Data Types and Variables
Computers store data in memory. To access the data, you need to find where it is stored. For this, we use variables. In programming, a variable joins a name (identifier) to a memory address. For variables holding numerical, character, boolean (meaning true/false) or string data, the actual value stored is called a literal. A variable can only hold one value at a time, but you can change what that value is.
You may remember variables from math class, where the identifiers were typically single letters. In programming, you can (and should) use full words that make clear what the variable represents (so, for example, salary is a better identifier than s if you are storing a salary amount).
Data Types
What types of data can you store? Sometimes, you will want to store a number, sometimes a single letter or other character, sometimes a word, and other times more complicated data types. In some programming languages, a particular variable can hold any type of value, and can even change type. For example, a single variable might hold the integer 8 at first, then later hold the character w. This is not true in Java.
Java is a strongly typed language, meaning each variable is of a specific type, and cannot change type. You can change the value of the data stored in a variable but not the type of data.
The most basic types of data in Java are called primitive types.
Primitive types include:
- int (integers, such as 5, -3 and 0)
- double (floating-point decimals, such as 6.23 and -8.0)
- boolean (either true or false)
- char (a single character, such as w, y, 6, or $)
...as well as byte, short, long, and float; however, you will work only with the list above in this course.
Note that strings are not a primitive type. Rather, they are associated with a class called String (like the System class we discussed earlier). Don't worry about that yet; classes and reference types are explained later. Do know, however, that the S in String is uppercase when used in programs.
Declaring variables
Before using a variable, you have to declare it. Think of declaring as saying, “Hey! I’m going to use a variable. It’s going to be of this type and have this name...”
State the type and the name, as follows:
int age;
Note the semicolon (;) at the end of this line. In Java (and many other languages), all statements (essentially, lines of code that perform some action) are ended with a semicolon.
You might be wondering why public static void main(String[] args) has no semicolon. It’s because this is a method header (or declaration), signalling the start of a block of code. Essentially, lines of code that start a block of statements use { } instead of a semicolon. These include method headers as well as if, while and for blocks that you will learn about soon.
Like method identifiers, variable names usually begin lowercase. As with other identifiers, use camel case for names with multiple words.
double timeOfDay;
boolean isLegalAge;
You can declare multiple variables of the same type on one line, as in:
double width, height, length; //declares three double variables
Although Strings are not primitive data types, they can be declared using the same syntax, as in:
String bookTitle;
Assignment
Assignment is the act of storing a value (or literal) in a variable. The = sign does not mean “equals” (like it does in mathematics); It means “put the value on the right into the variable on the left” as in:
//set age to 7
age = 7;
//set name to Sally
name = "Sally";
Note that in Java, assignment is done right to left. Also note that assignment does not have to happen directly upon declaration.
You can declare and assign at the same time, as in:
//declare a variable called height to hold a double, and store 65.2 into it
double height = 65.2;
//declare a variable called height to hold a String, and store "Jill" into it
String name = "Jill";
You can even declare multiple variables of the same type on the same line, assigning values to some (or all), as in:
//declare three char variables and assign z to one of them
char first, middle = 'z', last;
Note that the first time you store a value into a variable, this is called initializing the variable (because you’re setting the initial value of the variable).
When assigning a char literal, the value must be enclosed in single quotes. When assigning a String literal, it is enclosed in double quotes. In some languages (such as JavaScript), you can use single and double quotes interchangeably-- this is not the case in Java.
char initial = 'c';
String message = "Welcome home!"; //note the double versus single quotes
Be careful when copying and pasting single or double quote symbols into your code. Most text editors use “smart quotes” (which curl to the left and right). These will not work correctly in code. If you run into this problem, simply retype any quote characters from text that you’ve pasted.
One last note about variable declaration. You only declare a variable once. Once you’ve declared it, you do not continue to state its type in later use.
int age;
...
age = 7; //not int age = 7, because age has already been declared
Constants
Some variables hold values that should not be changed after initial assignment. For example, you might have an application that uses the sales tax rate for your state. This should be set once (when it is first declared) and not change elsewhere. Such variables are called constants and are declared using the final keyword. By convention, names of constants are all UPPERCASE, with underscores used to separate multiple words.
final double TAX_RATE = 0.07;
final int NUMBER_OF_ROOMS = 20;
final double PI = 3.14159;
If you try to change the value of a variable declared final after initial assignment, you will get an error.
Operations
Most math operations do what you would expect in Java, with these exceptions:
- When dividing integers, the result is itself is always an integer. Any decimal part is discarded (not rounded). For example, 7/2 is 3 (not 3.5) and 209/10 is 20 (not 20.9).
- + is used both for the addition of numbers and concatenation of strings. Concatenating means essentially sticking two strings together (e.g., "bob" + "white" produces "bobwhite"). Note that multiple + symbols are read left to right, so if numbers are connected by + before string concatenation, they will actually be added; otherwise they will be concatenated. For example, 3 + 4 + "shirt" is "7shirt", but "shirt" + 3 + 4 is "shirt34" (because the 3 is concatenated to shirt first)
- The % symbol does not indicate percent; it is modulo (usually shortened to mod) and means the remainder from division. For example, 7 % 2 is 1 (there is 1 left over after dividing 7 by 2) and 209 % 10 is 9.
- There is no exponent (or power) symbol in Java. You will learn soon how to use the Math class in Java to evaluate exponents.
As in mathematics, there is an order of precedence (remember PEMDAS?), meaning some operations always happen before others. The order is (each level left to right):
+, - (as in positive/negative, not addition and subtraction)
*, /, % (* is multiplication, / is division, and % is modulo)
+, - ,+ (arithmetic addition/subtraction and string concatenation)
= (variable assignment)
If you want to be sure that one operation happens before another, you can enclose it in parentheses. You can enclose one set of parentheses within another for further grouping.
For example
would be evaluated in this order:int daysInMonth = 30;
String message = "There are" + (2 * (daysInMonth - 5)) + " days left";
- daysInMonth - 5 (result is 25)
- 2 * 25 (result is 50)
- "There are" + 50 (result is "There are 50")
- "There are 50" + " days left" (The final result is "There are 50 days left")
Type Conversion (Casting)
Casting is the process of converting a value from one type to another. Remember that Java is strongly typed, so if a value from one type of variable is to be stored in another type of variable, its type needs to first be converted (or cast).
If an int value is to be stored into a double variable, it needs to be converted to a double. Java will do this automatically. This is called an implicit conversion (because you don’t have to state it in your code). Why is this OK? Since the int type has less precision than the double type, it can be “widened” into a double without changing its value.
Consider:
int x = 7;
double y = x; //y will now have a value of 7.0.
If a double and an int are used in the same math operation, the int will first be cast implicitly to a double and the result of the operation will be a double.
int a = 10;
double b = 4.0;
System.out.println(a/b); // will evaluate 10.0/4.0 and print the result, 2.5
Note that if both the values above were stored as ints, no casting would occur and the result would also be an int. This is a common error for beginning Java programmers, as shown in this example.
int a = 10;
int b = 4;
System.out.println(a/b); // will evaluate 10/4 and print 2, not 2.5
If you want to store a double into an int, you must explicitly cast it, by writing the type to convert to in parentheses, as in:
double y= 3.8;
int x = (int) y; //convert y’s value into an int. 3.8 is narrowed to 3.
Note that since you are now “narrowing” (i.e. going from more to less precision) the value of x will be 3 and the 0.8 will be discarded. An explicit cast is necessary here because you are (potentially) actually changing the value.