ShowTutorials.com

Refreshing your ideas and broadening your visions


Variables

Variables are names given to the data. They are used for storing data.
A Variable must have some Data type.

For example:
byte num = 2;
Here, num is variable name, and byte is data type. And the value 2 is assigned to variable num.

java variable example

So, where ever the variable num is used in the program, its value will be 2, unless we change it.
To use an variable, it must be declared first.
Whenever, we declare a variable in our program, memory will be allocated for that variable where the data will be stored.

byte num;
This is just declaration of the variable, no value is assigned to it, so it will have default value, which is 0

byte num = 2;
This is declaration, as well as assigning the value 2. This is the initialization of the variable as we are assigning value as well.

System.out.println(“The number is: ” + num);
Using the variable to print on the screen.
Output will be
The number is: 2

What data type to be selected?

Depending on our need, the proper data type should be selected.
For whole numbers, we can choose byte / short / int / long after considering the range of these data types.
For fractional numbers, we can choose float / double. We can go for double for more precision.
For characters/letters, we can go for char
For storing true/false, we can choose boolean

public class CheckVariables {
    public static void main(String[] args) {
        byte b = 2;
        short sh = 10;
        int i = 200;
        long lo = 500;

        float pi = 3.14f;
        double dob = 14.44566;
        
        char ch = 'A';
        boolean flag = true;

        System.out.println("b: " + b);
        b = 100; // Changing the value of b
        System.out.println("Now b value: " + b);

        
        System.out.println("sh: " + sh);
        System.out.println("i: " + i);
        System.out.println("lo: " + lo);
        System.out.println("pi: " + pi);
        System.out.println("dob: " + dob);        
        System.out.println("ch: " + ch);
        System.out.println("flag: " + flag);
    }
}

Output:
java variables example
There are also other non-primitive data types available which we can use. We will check those in later chapters.


Latest Topics: