Home »
Java programming language
Variable declaration, initialization in Java
By IncludeHelp Last updated : January 02, 2024
Just like C programming language, we can declare and initialize variables in Java too.
Variable Declaration
The simple approach is to declare a variable that just specifies the type of the variable and variable name (which should be a valid identifier).
Syntax
String name;
int age;
Variable Initialization
If the variable is declared, you can simply initialize it with the appropriate value by using the assignment operator (=).
Syntax
name = "Alin Alexander";
age = 27;
Variable Declaration with Initialization
You can also declare a variable with an initial value.
We would recommend using this style of variable declaration and initialization, as this kind of declaration also stores the default value of the variable.
Syntax
String name = "Alin Alexander";
int age = 27;
Example of Variable Declaration and Initialization
Consider this example, here we are declaring some of the variables with initial (default) values to them and then we will print the values.
public class Main {
public static void main(String[] args) {
int a = 10;
char b = 'X';
float c = 10.235f;
String str = "Hello";
System.out.println("a= " + a);
System.out.println("b= " + b);
System.out.println("c= " + c);
System.out.println("str= " + str);
}
}
Output
The output of the above example is:
a= 10
b= X
c= 10.235
str= Hello