You are here: Home / Topics / Understanding Variables in Java

Understanding Variables in Java

Filed under: Java Tutorial on 2024-03-01 20:50:25

In Java, the variables can be declared to store data in the program for a specific time. In a programming language, few variations are there to
declare a variable. The following program will explain to declare and then initialize an int variable.

public static void main(String[] args) {
int data1;
data1=1;
System.out.println (data1);
}

 

Output:      1
 

Multiple variable initializations within a statement When we come to initializations of multiple variables, Java supports multiple
initializations of variables within a single statement. We can also write the declaration and initialization of multiple variables together within a single statement. We need to use a comma-separated list for initializing multiple variables.


public static void main(String[] args) {
int data1 = 11, data2 = 12;
System.out.println(data2);
}

Output:     2


Initialization of variable through arithmetic operation After the successful completion of the arithmetic operation, the final
outcome would be assigned to the variable. The assignment operator (=) is used to complete the assignment of the result and the sequence of
assignments is from right to left. If the mathematics operation is use brackets within the operation, the operation inside the bracket performs
first.


public static void main(String[] args) {
int data1 = 1, data2 = (2 * 2) - 1;
System.out.println (data2);
}

Output:   3

Assigning one primitive variable to another A variable value can assign by using another variable. This is called as copy the value of a variable to another variable.


Demonstration

  1. Assign a integer value to an int
  2. Assign the variable value to a different variable.


It is explained in the following example.
public static void main(String[] args) {
       int data1 = 1;
       int data2 = data1;
      System.out.println (data2);
}
Output: 

1

Note: Assignment operation can be written in a single statement also.

Naming Convention

  1. The variable names are case-sensitive “value” and “Value” both are different.
  2. Space is not permitted in variable names.
About Author:
J
Java Developer     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.