Java Variables

Java Variables
Java Variables

Variable allocates reserved memory area.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of
a variable declaration is shown here:
type identifier [ = value][, identifier [= value] …] ;
The type is one of Java’s atomic types, or the name of a class or interface.

Example:
char ch=’A’;//chis variable
int num=10;//num is variable

Types of Variable

  • Local Variable is declared inside the method.
  • Instance Variable is declared inside the class but outside the method.
  • Static variable is declared as with static keyword.

Example:

class MyVariables{  
   int num1=50;//instance variable  
   static int2 m=100;//static variable  
   void method(){  
      int num3=90;//local variable  
   }  
}

Java static method

If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a class.
A static method can access static data member and can change the value of it.
Ex:-

 
class Calculate{  
  static int cube(int x){  
  return x*x*x;  
  }  
  
  public static void main(String args[]){  
  int result=Calculate.cube(5);  
  System.out.println(result);  
  }  
}
java java tutorials learn java study java
Recent Posts