Following are examples of variable declaration and initialization in Java.
Example:
int x, y, z; // Declares three ints, x, y, and z. int x = 10, y = 25; // Example of initialization byte Y = 24; // initializes a byte type variable Y. double pi = 3.14159; // declares and assigns a value of PI. char x = 'x'; // the char variable a iis initialized with value 'x'
Three type of variable:
- Local variables
- Instance variables
- Class/Static variables
Local Variables
- Access modifiers cannot be used for local variables.
- Local variables are declared in methods, constructors, or blocks.
- Local variables are visible only within the declared method, constructor, or block.
Example:
public class Test { public void pupAge() { int age = 0; age = age + 9; System.out.println("Puss age is : " + age); } public static void main(String args[]) { Test test = new Test(); test.pupAge(); } }
output
Puss age is: 9
Following example uses age without initializing it, so it would give an error at the time of compilation.
public class Test { public void pupAge() { int age; age = age + 9; System.out.println("Puss age is : " + age); } public static void main(String args[]) { Test test = new Test(); test.pupAge(); } }
Output
/Test.java:4: error: variable age might not have been initialized age = age + 9; ^ 1 error
Instance Variables
- Access modifiers can be given for instance variables.
- Instance variables can be accessed directly by calling the variable name inside the class.
- Values can be assigned during the declaration or within the constructor.
import java.io.*; public class Student { // this instance variable is visible for any child class. public String name; // salary variable is visible in Student class only. private double salary; // The name variable is assigned in the constructor. public Student (String empName) { name = empName; } // The salary variable is assigned a value. public void setSalary(double empSal) { salary = empSal; } // This method prints the Student details. public void printEmp() { System.out.println("name : " + name ); System.out.println("salary :" + salary); } public static void main(String args[]) { Student empOne = new Student("Nicki Minaj"); empOne.setSalary(50000); empOne.printEmp(); } }
output
name : Nicki Minaj salary :50000.0
Class/Static Variables
- Static variables are stored in the static memory
- tatic variables are created when the program starts and destroyed when the program stops.
- Static variables can be accessed by calling with the class name ClassName.VariableName.
import java.io.*; public class Employee { // salary variable is a private static variable private static double salary; // developer is a constant public static final String developer = "job "; public static void main(String args[]) { salary = 83000; System.out.println(developer + "average salary:" + salary); } }
output
job average salary:83000.0