Speed up development with full-stack environments for every branch.

Learn More

Declare variables [Java]

318 Runs 3893 Views 456 Copies


mirang 126

published 4 years ago

Following types of variables can be declared in java
1. Static variables : These variables are class level variables. 
Their life begins when the class is first
loaded in memory and ends when the class is unloaded.
2. Instance variables : These variables are declared at class level. 
Their life begins when the 
object/instance of the class is created and ends when the object is distroyed
3. Method local variables : These are local to the method in which they are declared
4. Block variables : These are declared within any block and can be accessed ONLY within the block

public class HelloWorld {

  //Static variable in Java, the value of staticVariable will be 1 for all instance of HelloWorld class
  static int staticVariable = 1;
//Instance variable as at object level, so each object will have different copies of instanceVariable
  public int instanceVariable = 1;

  public static void main(String[] args) {
    //method level local variable, scope is only the 'main' method
    int methodLevelLocalVariable = 3;
    //This will retrieve line separator dependent on OS.
    String newLine = System.getProperty("line.separator");
    System.out.println("Static variable value : " + staticVariable + newLine);
    //You cannot access instance variable from static method, 
    //as it does not work with instance variables
    //System.out.println("Instance variable value : " + instanceVariable);
    System.out.println("Method level variable value : " + methodLevelLocalVariable + newLine);
      //block level variable, they are only visible within {} blocks above
      int blockLevelVariable = 3;
      System.out.println("Block level variable value : " + blockLevelVariable);

Please login/signup to get access to the terminal.

Your session has timed out.

Dismiss (the page may not function properly).