The following two lines Java code defines two integers, num1 and num2:
int num1; int num2;
num1 and num2 are two int variables.
The int keyword indicates that the name that follows represents an integer value, for example, 10, 15, 70, 1000, etc.
Because you have declared num1 and num2 variables of int data type, we cannot store a real number, such as 10.1.
The following piece of code stores 5 in num1 and 7 in num2:
num1 = 5; num2 = 7;
Java supports two kinds of data types:
A variable of the primitive data type holds a value whereas a variable of the reference data type holds the reference to an object in memory.
String is a class defined in the Java library and we can use it to manipulate sequence of characters.
You declare a reference variable str of String type as
String str;
There is a reference constant null
, which can be assigned to any reference variable.
If null is assigned to a reference variable, it means that the reference variable is not referring to any object in memory.
The null reference literal can be assigned to str.
str = null;
A String object is created using the new
operator.
Strings are used so often that there is a shortcut to create a string object.
All string literals, a sequence of characters enclosed in double quotes, are treated as String objects.
We can use string literals like so:
// Assigns "Hello" to str1 String str1 = "Hello"; // Assigns the reference of a String object with text "Hello" to str1 String str1 = new String ("Hello");