Types of Variables
Division 1 :
Based on the type of value represented by a variable all variables are divided into 2 types. They are:
- Primitive variables
- Reference variables
Primitive variables can be used to represent primitive values. Example: int x=10;
Reference variables can be used to reference to objects.
Student s=new Student();
Diagram:
Division 2 :
Based on the behaviour and position of declaration all variables are divided into the following 3 types.
- Instance variables
- Static variables
- Local variables
1. Instance variables:
- If the value of a variable is varied from object to object such type of variables are called instance variables.
- For every object a separate copy of instance variables will be created.
- Instance variables will be created at the time of object creation and destroyed atthe time of object destruction hence the scope of instance variables is exactlysame as scope of objects.
- Instance variables will be stored on the heap as the part of object.
- Instance variables should be declared with in the class directly but outside of any method or block or constructor.
- Instance variables can be accessed directly from Instance area. But cannot be accessed directly from static area.
- But by using object reference we can access instance variables from static area.
class Test { int i=10; public static void main(String[] args) { //System.out.println(i); //C.E:non-static variable i cannot be referenced from a static context(invalid) Test t=new Test(); System.out.println(t.i);//10(valid) t.methodOne(); } public void methodOne() { System.out.println(i);//10(valid) } }
class Test { boolean b; public static void main(String[] args) { Test t=new Test(); System.out.println(t.b);//false } }
2. Static variables:
- If the value of a variable is not varied from object to object such type of variables is not recommended to declare as instance variables. We have to declare such type of variables at class level by using static modifier.
- In the case of instance variables for every object a separate copy will be created but in the case of static variables for entire class only one copy will be created and shared by every object of that class.
- Static variables will be crated at the time of class loading and destroyed at the time of class unloading hence the scope of the static variable is exactly same as the scope of the .class file.
- Static variables will be stored in method area. Static variables should be declared with in the class directly but outside of any method or block or constructor.
- Static variables can be accessed from both instance and static areas directly.
- We can access static variables either by class name or by object reference but usage of class name is recommended.
- But within the same class it is not required to use class name we can accessdirectly.
- Start JVM.
- Create and start Main Thread by JVM.
- Locate(find) Test.class by main Thread.
- Load Test.class by main Thread. // static variable creation
- Execution of main() method.
- Unload Test.class // static variable destruction
- Terminate main Thread.
- Shutdown JVM
class Test { static int i=10; public static void main(String[] args) { Test t=new Test(); System.out.println(t.i);//10 System.out.println(Test.i);//10 System.out.println(i);//10 } }
class Test { static String s; public static void main(String[] args) { System.out.println(s);//null } }
class Test { int x=10; static int y=20; public static void main(String[] args) { Test t1=new Test(); t1.x=888; t1.y=999; Test t2=new Test(); System.out.println(t2.x+"----"+t2.y);//10----999 } }
3. Local variables:
- The local variables will be stored on the stack.
- For the local variables JVM won't provide any default values compulsory we should perform initialization explicitly before using that variable.
class Test { public static void main(String[] args) { int x; if(args.length>0) { x=10; } else { x=20; } System.out.println(x); } }
Output:java Test x10java Test x y10java Test20
- It is never recommended to perform initialization for the local variables inside logical blocks because there is no guarantee of executing that block always at runtime.
- It is highly recommended to perform initialization for the local variables at the time of declaration at least with default values.
class Test { public static void main(String[] args) { public int x=10; //(invalid) private int x=10; //(invalid) protected int x=10; //(invalid) static int x=10; //(invalid) volatile int x=10; //(invalid) transient int x=10; //(invalid) final int x=10;//(valid) } }
- For the static and instance variables it is not required to perform initialization explicitly JVM will provide default values. But for the local variables JVM won't provide any default values compulsory we should perform initialization explicitly before using that variable.
- For every object a separate copy of instance variable will be created whereas for entire class a single copy of static variable will be created. For every Thread a separate copy of local variable will be created.
- Instance and static variables can be accessed by multiple Threads simultaneously and hence these are not Thread safe but local variables can be accessed by only one Thread at a time and hence local variables are Thread safe.
- If we are not declaring any modifier explicitly then it means default modifier but this rule is applicable only for static and instance variables but not local variables.
UnInitialized Arrays
class Test { int[] a; public static void main(String[] args) { Test t1=new Test(); System.out.println(t1.a);//null System.out.println(t1.a[0]);//R.E:NullPointerException } }
1. Instance level:
int[] a; System.out.println(obj.a);//null System.out.println(obj.a[0]);//R.E:NullPointerException
int[] a; System.out.println(obj.a);//null System.out.println(obj.a[0]);//R.E:NullPointerException
2. Static level:
static int[] a; System.out.println(a);//null System.out.println(a[0]);//R.E:NullPointerException
static int[] a=new int[3]; System.out.println(a);//[I@3e25a5 System.out.println(a[0]);//0
3. Local level:
int[] a; System.out.println(a); //C.E: variable a might not have been initialized System.out.println(a[0]);
Example 2:int[] a=new int[3]; System.out.println(a);//[I@3e25a5 System.out.println(a[0]);//0
- Once we created an array every element is always initialized with default values irrespective of whether it is static or instance or local array.
- Every variable in java should be either instance or static or local. Every variable in java should be either primitive or reference
Var- arg methods (variable no of argument methods) (1.5)
- Until 1.4v we can't declared a method with variable no. Of arguments.
- If there is a change in no of arguments compulsory we have to define a newmethod.
- This approach increases length of the code and reduces readability.
- But from 1.5 version onwards we can declare a method with variable no. Of arguments such type of methods are called var-arg methods.
class Test {public static void methodOne(int... x) {System.out.println("var-arg method");}public static void main(String[] args) {methodOne(); methodOne(10); methodOne(10,20,30);}}
class Test {public static void sum(int... x) {int total=0;for(int i=0;i<x.length;i++) {total=total+x[i];}System.out.println("The sum :"+total);}public static void main(String[] args) {sum();sum(10);sum(10,20);sum(10,20,30,40);}}
class Test {public static void sum(int... x) {int total=0;for(int x1 : x){total=total+x1;}System.out.println("The sum :"+total);}public static void main(String[] args) {sum();sum(10);sum(10,20);sum(10,20,30,40);}}
Case 1:
- methodOne(int... x) (valid)
- methodOne(int ...x) (valid)
- methodOne(int...x) (valid)
- methodOne(int x...) (invalid)
- methodOne(int. ..x) (invalid)
- methodOne(int .x..) (invalid)
Case 2:
Case 3:
Case 4:
class Test { public static void methodOne(int i) { System.out.println("general method"); } public static void methodOne(int... i) { System.out.println("var-arg method"); } public static void main(String[] args) { methodOne();//var-arg method methodOne(10,20);//var-arg method methodOne(10);//general method } }
class Test { public static void methodOne(int... i) { System.out.println("var-arg method"); } public static void main(String[] args) { methodOne(new int[]{10,20,30});//var-arg method } }
Case 7:
class Test { public void methodOne(int[] i){} public void methodOne(int... i){} }
class Test { public static void main(String... args) { method } }
- methodOne(int... x) we can call this method by passing a group of int values and x will become 1D array. (i.e., int[] x)
- methodOne(int[]... x) we can call this method by passing a group of 1D int[] and x will become 2D array. ( i.e., int[][] x)
class Test { public static void methodOne(int[]... x) { for(int[] a:x){ System.out.println(a[0]); } } public static void main(String[] args){ int[] l={10,20,30}; int[] m={40,50}; methodOne(l,m); } }
10
40
Main Method
- Whether the class contains main() method or not,and whether it is properly declared or not,
- these checking's are not responsibilities of the compiler, at runtime JVM is responsible for this.
- If JVM unable to find the required main() method then we will get runtime exception saying NoSuchMethodError: main.
If we are performing any changes to the above syntax then the code won't run and will get Runtime exception saying NoSuchMethodError.
Even though above syntax is very strict but the following changes are acceptable to main() method.
- The order of modifiers is not important that is instead of public static we can take static public.
- We can declare string[] in any acceptable form
- String[] args
- String []args
- String args[]
- Instead of args we can use any valid java identifier.
We can replace string[] with var-arg parameter.
Example: main(String... args)- main() method can be declared with the following modifiers.final, synchronized, strictfp.
- class Test {
- static final syncronized strictfp public void main(String... ask){ 8. System.out.println("valid main method");
- }
- }
- output :
- valid main method
- Public static void main(String args){} (invalid)
- public synchronized final strictfp void main(String[] args){} (invalid)
- public static void Main(String... args){} (invalid)
- public static int main(String[] args){} //int return type we can't take //(invalid)
- public static synchronized final strictfp void main(String... args){}(valid)
- public static void main(String... args){}(valid)
- public void main(String[] args){}(invalid)
class Test { public static void main(String[] args) { System.out.println("String[] array main method"); // overloaded methods } public static void main(int[] args) { System.out.println("int[] array main method"); } }
Example 2:
class Parent { public static void main(String[] args) { System.out.println("parent main"); } } class Child extends Parent { public static void main(String[] args) { System.out.println("Child main"); } }
- Untill 1.6v if our class doesn't contain main() method then at runtime we will get Runtime Exception saying NosuchMethodError:main
- But from 1.7 version onwards instead of NoSuchMethodError we will get more meaning full description .
class Test { }
- From 1.7 version onwards to start program execution compulsory main method should be required, hence even though the class contains static block if main method notavailable then won't be executed.
class Test {static {System.out.println("static block"); }}}
class Test {static {System.out.println("static block");System.exit(0);}}
class Test {static {System.out.println("static block"); }public static void main(String[] args) {System.out.println("main method");}}
Command line arguments:
The arguments which are passing from command prompt are called command line arguments.
The main objective of command line arguments are we can customize the behavior of the main() method.
class Test {public static void main(String[] args) {for(int i=0;i<=args.length;i++) {System.out.println(args[i]);}}}
Output:
public static void main(String[] args) {String[] argh={"X","Y","Z"}; args=argh;for(String s : args) {System.out.println(s);}}
class Test {public static void main(String[] args) {System.out.println(args[0]+args[1]);}}
class Test {public static void main(String[] args) {System.out.println(args[0]);}}
Java coding standards
- Whenever we are writing java code , It is highly recommended to follow coding standards , which improves the readability and understandability of the code.
- Whenever we are writing any component(i.e., class or method or variable) thename of the component should reflect the purpose or functionality.
Example:
Coding standards for classes:
- Usually class names are nouns.
- Should starts with uppercase letter and if it contains multiple words every inner
- word should starts with upper case letter.
Example:
Coding standards for interfaces:
- Usually interface names are adjectives.
- Should starts with upper case letter and if it contains multiple words every inner word should starts with upper case letter.
Example:
- Serializable
- Runnable
- Cloneable
these are adjectives
Coding standards for methods:
- Usually method names are either verbs or verb-noun combination.
- Should starts with lowercase character and if it contains multiple words everyinner word should starts with upper case letter.(camel case convention)
- Usually variable names are nouns.
- Should starts with lowercase alphabet symbol and if it contains multiple wordsevery inner word should starts with upper case character.(camel case convention)
- Usually constants are nouns.
- Should contain only uppercase characters and if it contains multiple words then these words are separated with underscore symbol.
- Usually we can declare constants by using public static final modifiers.
- Method name should be prefixed with set.
- It should be public.
- Return type should be void.
- Compulsory it should take some argument.
- The method name should be prefixed with get.
- It should be public.
- Return type should not be void.
- It is always no argument method.
- For the boolean properties the getter method can be prefixed with either get or is. But recommended to use is.
- public void addMyActionListener(MyActionListener l) (valid)
- public void registerMyActionListener(MyActionListener l) (invalid)
- public void addMyActionListener(ActionListener l) (invalid)
- public void removeMyActionListener(MyActionListener l) (valid)
- publc void unregisterMyActionListener(MyActionListener l) (invalid)
- public void removeMyActionListener(ActionListener l) (invalid)
- public void deleteMyActionListener(MyActionListener l) (invalid)
- Class level binary data includung static variables will be stored in method area.
- Objects and corresponding instance variables will be stored in Heap area.
For every method the JVM will create a Runtime stack all method calls
performed by that Thread and corresponding local variables will be stored in that stack.- Every entry in stack is called Stack Frame or Action Record.
- The instruction which has to execute next will be stored in the corresponding PC Registers.