Variables and Types
1. Variables: Name It!
In the last exercise, we learn to print different statements with
While it’s great to print out a number or a sentence, we haven’t given them a meaning.
In Java, we introduce the idea of a variable for data. A variable is like a box that stores a piece of data with a name.
For example, there can be a variable called
myName that stored
"Patrick", another variable called
loveMusic that stored
true, and another variable called
age that stored
3. Just like the image below:
2. What the Type!
So how do we create these boxes or variables in Java to store data?
Before learning that we need to learn the concept of type in Java. Each variable has its own type that restrict it to store a specific kind of data.
For example, the variable called
age that store the number
3 should contain contain integers, not sentences or symbols.
In Java, for a variable to store whole numbers, it is type
int. And, we declare a
int variable called
age with data
3 with the line of code:
int age = 3;
In general, to declare a variable we write them in the format:
[data type] [variable name] = [data];.
The following are the important data types that have been built-in in Java:
inttype: an integer (i.e.
chartype: a character such as a symbol or single alphabet letter (i.e.
Stringtype: a sequence of
booleantype: a type that is either the value
doubletype: type that store fractional numbers (i.e.
Let’s revisit the three variables we talked about and identify their data types.
To declare these variables in Java, we type the following:
String name = "Patrick"; int age = 10; boolean loveMusic = true;
3. What the Type – Help Patrick!
Patrick 🐥 isn’t a master of data types! He often mixed them up when declaring variables. Let’s help him fix his mistake:
By storing data in variables, you can use that data later or change it by assigning it to a different data of the same type. For example:
int age = 10; System.out.println(age); // prints out 10 age = 11; // assign data 11 to the variable age System.out.println(age); // prints out 11
4. What the Type – Track Numbers!
Now consider the following code. What do you think the output is? Track the values of each variable by yourself then test it out below!
double x = 2.3; double y = 10.0; int z = 4; x = y; y = x; z = 0; z = z; System.out.println("x: " + x + " y: " + y + " z: " + z );