Java Notes
Java Notes
Variables
A variable is a container that stores a value.
This value can be changed during the execution of the program.
Example: int number = 8; (Here, int is a data type, the number is the variable
name, and 8 is the value it contains/stores).
Rules for declaring a variable name
We can choose a name while declaring a Java variable if the following rules are
followed:
Must not begin with a digit. (E.g., 1arry is an invalid variable)
Name is case sensitive. (Harry and harry are different)
Should not be a keyword (like Void).
White space is not allowed. (int Code With Harry is invalid)
Can contain alphabets, $character, _character, and digits if the other
conditions are met.
class Main {
2. byte type
The byte data type can have values from -128 to 127 (8-bit signed two's
complement integer).
If it's certain that the value of a variable will be within -128 to 127, then it
is used instead of int to save memory.
Default value: 0
class Main {
range = 124;
3. short type
The short data type in Java can have values from -32768 to 32767 (16-
bit signed two's complement integer).
If it's certain that the value of a variable will be within -32768 and 32767,
then it is used instead of other integer data types (int, long)
class Main {
short temperature;
temperature = -200;
4. int type
The int data type can have values from -231 to 231-1 (32-bit signed two's
complement integer).
If you are using Java 8 or later, you can use an unsigned 32-bit integer.
This will have a minimum value of 0 and a maximum value of 232-1.
Default value: 0
class M ain {
5. long type
The long data type can have values from -263 to 263-1 (64-bit signed two's
complement integer).
If you are using Java 8 or later, you can use an unsigned 64-bit integer
with a minimum value of 0 and a maximum value of 264-1.
Default value: 0
class L o n g E x am p le {
}
Notice, the use of L at the end of -42332200000. This represents that it's an
integer of the long type.
6. double type
class M ain {
}
}
7. float type
class M ain {
Notice that we have used -42.3f instead of -42.3 in the above program. It's
because -42.3 is a double literal.
To tell the compiler to treat -42.3 as float rather than double , you need to
use f or F .
8. char type
It's a 16-bit Unicode character.
The minimum value of the char data type is '\u0000' (0) and the
maximum value of the is '\uffff' .
class M ain {
System.out.println(letter); // prints Q
class Main {
public static void main(String[] args) {
}
}
Here, we have assigned 9 as a character (specified by single quotes) to
the letter1 variable. However, the letter2 variable is assigned 65 as an integer
number (no single quotes).