Lesson 4- Data Types and Variables
You should be able to copy and paste these code blocks below into your IDE to see output and manipulate if you so desire. If you see a ******* this will indicate that you need to create a new program using the class name that you see in the code block. It's also important to note that Java is case-sensitive.
For example, if you see
public class Integers {
some code here;
}
Then you should create a new Java project with the file name Integers. If not, the code block will not work. The main class name must be the same as the project name.
What Are Data Types?
Let's write a program that we can use to calculate sums of two numbers.*****
public class Arithmetic {
public static void main(String[] rags) {
System.out.println(1+1);
}
}
Notice in the print statement, we have asked the compiler to print 1+1. This should output, 2. We can do this for multiple calculations.
public class Arithmetic {
public static void main(String[] rags) {
System.out.println(1+1);
System.out.println(1+2);
System.out.println(2+1);
System.out.println(3+2);
}
}
This will output:
2
3
3
5
We can perform many calculations, though so many numbers and calculations such as this can be difficult to keep track of. We can use data types to manage these variables.
A data type is a system of data that Java uses to store information that can be referenced at a later time. There are several different data types that we will visit in this set of notes. Let's begin with a few basic data types, known as variables.
Variables
A variable is a data type that stores data for later retrieval. The first data type that we are going to look at is an integer variable, or int
. An int
variable holds whole numbers. It cannot store data in the form of fractions or decimals.
To declare an int
variable, you type int
followed by the variable name. All variables must have a name, or they can't be used and you'll receive a syntax error. Let's assign one variable as x and one as y.*****
public class Variables {
public static void main(String[] args) {
int x;
int y;
System.out.println(1+1);
System.out.println(1+2);
System.out.println(2+1);
System.out.println(3+2);
}
}
Now that we've set up these two variables, we can run our code.
Notice that nothing changes with the run of our program. However, in the background, Java sets aside memory space for the two variables.
Let's initialize our variables with information. We initialize a variable using an equal sign = followed by the data that you want stored in that variable.
public class Variables {
public static void main(String[] args) {
int x;
int y;
x = 45;
y = 37;
}
}
Here, we initialize x setting it equal to 45, while y is set equal to 37. Now, nothing here really takes place. We've given our variable some sort of data to hold. Though, they've yet to be referenced. Now that we have assigned data to the variable, we simply have to call the variable by name to access the information that is stored there.
public class Variables {
public static void main(String[] args) {
int x;
int y;
x = 45;
y = 37;
System.out.println(x);
System.out.println(y);
}
}
Now, note that once we have declared and initialized a variable, we cannot declare the same variable type with a name that has already been initialized. What do I mean by declare and initialize? Declaring a variable means assigning a data type to be referenced. We declared the int
variable x and initialized it by assigning the value 45.
public class Variables {
public static void main(String[] args) {
int x;
int y;
x = 45;
y = 37;
int x;
System.out.println(x);
System.out.println(y);
}
}
This code block would prompt a logic error because the variable was already declared with the variable name x. Two solutions can solve this. Either change the name of the variable, perhaps to z, or delete the variable altogether.
Now, a situation may arise where we'd like to initialize the variable to hold one value at this moment but then change to another value the next. Declaring the variable a second time won't work in this case. Let's try another way.
public class Variables {
public static void main(String[] args) {
int x;
int y;
x = 45;
y = 37;
System.out.println(x);
System.out.println(y);
x = 12;
System.out.println(x);
}
}
In this case, the first instance of x prints out as 45. The second instance is 12.
Now, remember that I mentioned that an int
variable can only be assigned the value of a whole number. What about a decimal? Or a collection of words? Let's look at a few other variable data types that we can use to achieve these desires.
Floating Point
A floating point, which we declare as float
, gives us the ability to reference data more mathematically, such as decimals or fractions.*****
public class FloatingPointNumbers {
public static void main(String[] args) {
int x = 5;
float y = 5.5f;
}
}
Here, when declaring a float
, we must end the variable value with f
. This is to differentiate a float
from a double
variable, which we will go over a bit later.
Let's analyze this new data type using some arithmetic.
public class FloaingPointNumbers{
public static void main(String[] args)
int x = 5/4;
floaty y = 5/4f;
System.out.println(x);
System.out.println(y);
}
}
Our output is as follows:
1
1.25
Mathematically, Java calculates int
variables by rounding to the nearest whole number. Since 5 divided by 4 is 1.25, Java automatically rounds this down to stay consistent with storing data in our int
variable. However, Java will give us a more accurate calculation with our float
variable.
Double
Double
variable types are similar to float
. The only major difference is that they can provide more decimal places. The downside: more data means more memory. Though, the memory usage is not very significant.
Here is a demonstration of using a double
variable.*****
public class Double{
public static void main(String[] args)
double x = 1.2;
double y = 2.4354;
System.out.println(x/y);
}
Output:
0.4927322000492732
The Math Class Library
This is a good time to look at the Math class library. Most IDE's come with the Math class built in.
In order to use the Math class, we must important the library into our program. Let's also set up a few variables for manipulation.*****
import java.lang.Math;
public class MathClassPractice {
public static void main(String[] args){
double x = 1.78;
double y = -4.5;
System.out.println(Math.abs(x+y));
}
}
Here, the Math.abs( )
method will return the absolute value of whatever we're asking. Here, we're returning the absolute value of the sum of x and y.
Output:
2.7199999999999998
There are more useful methods of the Math class library. See those Math Class Library.
Char Variables
Sometimes, we want to be able to manipulate words and texts as well. In order to do this, Java defines the char
data type, the primitive type. Characters are the smallest entity of text that you can work with on a computer. Starting off, we can think of single letters.*****
public class Characters {
public static void main(String[] args) {
char x = 'x';
System.out.println(x);
}
}
Output:
x
In the case of a char
, it is necessary that the value be initialized using single quotations ' ' otherwise an error will be returned by the compiler.
Let's create something more complex.
public class Characters {
public static void main(String[] args) {
char h = 'h';
char e = 'e';
char l = 'l';
char l = 'l';
char o = 'o';
char exclPoint = '!';
System.out.print(h);
System.out.print(e);
System.out.print(l);
System.out.print(l);
System.out.print(o);
System.out.print(exclPoint);
}
}
Output:
hello!
This is incredibly tedious. Let's take a look at how to make this process easier.
String Variables
The last variable that we are going to look at is a string
variable.*****
public class JavaStrings {
public static void main(String[] args){
char a = 'a';
String word = "word";
}
}
String is not a primitive data type like we have been using with int
, float
, double
, and char
. String
is what we call a class, and creating a variable, in our case the variable word
, creates an instance of the String
class. Unlike primitive data types, instances of classes can contain various methods and functions declared by the parent class of which they are an instance.
For example, the concatenation operator.
public class JavaStrings {
public static void main(String[] args){
String string1 = "a word";
String string2 = "contains letters";
String string3 = string1 + string2;
System.out.println(string3);
}
}
Output:
a wordcontains letters
Concatenation simply refers to the merging of two or more strings to create one concatenated string. However, this won't take into account grammar as we know it. It simply concatenates at the string
's first indices. That's why there isn't a space between string1
and string2
. We can fix this:
public class JavaStrings {
public static void main(String[] args){
String string1 = "a word";
String string2 = "contains letters";
String string3 = string1 + " " + string2;
System.out.println(string3);
}
}
Another example is the toUpperCase( )
function. This capitalizes the string
value fully. We can do this in one of two ways:
-
Directly to the
string3
value as it is initialized -
To the
string3
value as it is called by the print function.public class JavaStrings {
public static void main(String[] args){
String string1 = "a word";
String string2 = "contains letters";
String string3 = string1 + " " + string2;
System.out.println(string3);}
}
Output:
a word contains letters
The replace( )
function is one more method from the string
class that we are going to look at.
public class JavaStrings {
public string void main(String[] args){
String s1 = "first";
String s2 = "second";
String s3 = s1 + s2 + "third";
System.out.println(s3.replace('d','o'));
}
}
Output:
firstseconothiro
Notice that the characters 'd' are replaced with 'o'. If we had, instead tried to use 'D', then nothing would happen because there are no capital D characters in our strings. Remember, Java is a case-sensitive language. Your code must be very specific.
On the note of specificity, you may have noticed that there is a specific way that I've been naming variables. It is convention to use Camel Case. For example, the popular brands iPhone, YouTube, and AirDrop use camel case. In Java, variables should begin lowercase, then subsequent words become uppercase. For example, firstNumber, lastName, or userInput.
Next Lesson: Lesson 5a - Simple Calculations
Table of Contents: Table of Contents