Variable Types in java
Variable is nothing but a name or keyword which occupies space in the memory. Variables are classified in 3 types.
- Local Variable
- Instance (or non-static) variable
- Static or Class variables
- Parameters or arguments
Local Variables:
- Local variables can be declared in the method,Constructor or block.
- It has scope till the end of execution of method,Constructor or block i.e. it will be destroyed once exit the method,Constructor or block.
- It is mandatory to initialize them, otherwise it throws error at compile time.
- Access modifier can not be used with them.
1 2 3 4 5 6 |
public class Demo1 { public static void main(String[] args) { int age = 0; // Initializing local variable age age = age +2; } } |
- These variables are declared inside the class, but outside the method,Constructor or block.
- These are available to all method,Constructor or block.
- Access modifier can be used with them.
- If not initialized, then default values will be assigned to them like false for boolean, 0 for integer,null for object reference. Execute the below program for understanding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class Demo1 { String name; //instance variables boolean val; //instance variables int age; //instance variables public static void main(String[] args) { Demo1 d = new Demo1(); d.checkVariables(); } public void checkVariables(){ System.out.println(name +"--"+ val +"--"+ age); } } |
- Static keyword is used to define the static variables.
- These are declared at the class level.
- It can not be declared as local i.e. not inside a method, constructor or a block.
- It can be accessed with the class name i.e. classname.staticvariable.
1 2 3 4 5 6 |
public class Demo1 { static String name; // static variable public static void main(String[] args) { Demo1.name = "Shekhar"; } } |
Ask Question
If you have any question, you can go to menu ‘Features -> Q&A forum-> Ask Question’. Select the desired category and post your question.