Friday, July 22, 2022

Language_Fundamentals : Types_Of_Variables | UnInitialized_Arrays | Var_arg_ Methods | Main_Method | Command_Line_Arguments | Coding_Standards

Types of Variables

Division 1 : 

Based on the type of value represented by a variable all variables are divided into 2 types. They are:

  1. Primitive variables
  2. Reference variables

1. Primitive variables:
Primitive variables can be used to represent primitive values. Example: int x=10;

2. Reference variables:
Reference variables can be used to reference to objects.

Example
Student s=new Student();

Diagram: 





Division 2 : 

Based on the behaviour and position of declaration all variables are divided into the following 3 types.

  1. Instance variables
  2. Static variables
  3. 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.


Example:

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) } }

For the instance variables it is not required to perform initialization JVM will always provide default values.

Example:

class Test { boolean b; public static void main(String[] args) { Test t=new Test(); System.out.println(t.b);//false } }
Instance variables also known as object-level variables or attributes.

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.


java TEST
  1. Start JVM.
  2. Create and start Main Thread by JVM.
  3. Locate(find) Test.class by main Thread.
  4. Load Test.class by main Thread. // static variable creation
  5. Execution of main() method.
  6. Unload Test.class // static variable destruction
  7. Terminate main Thread.
  8. Shutdown JVM

Example:

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 } }
For the static variables it is not required to perform initialization explicitly, JVM will always provide default values

Example:

class Test { static String s; public static void main(String[] args) { System.out.println(s);//null } }
Example:

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 } }

Diagram:


 

Static variables also known as class level variables or fields.

3. Local variables:


Sometimes to meet temporary requirements of the programmer we can declare variables inside a method or block or constructors such type of variables are called local variables or automatic variables or temporary variables or stack variables.

Local variables will be stored inside stack.

The local variables will be created as part of the block execution in which it is declared and destroyed once that block execution completes. Hence the scope of the local variables is exactly same as scope of the block in which we declared.

Example 1:

class Test { public static void main(String[] args) { int i=0; for(int j=0;j<3;j++) { i=i+j; } }
Example 2: 

class Test { public static void main(String[] args) { try { int i=Integer.parseInt("ten"); } catch(NullPointerException e) { }
  • 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.
Example 3:

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 x
10

java Test x y
10

java Test
20

  • 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.

Example 4:

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) } }
Conclusions:

  • 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 
Example :

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:

Example 1:

int[] a; System.out.println(obj.a);//null System.out.println(obj.a[0]);//R.E:NullPointerException
Example 2:

int[] a; System.out.println(obj.a);//null System.out.println(obj.a[0]);//R.E:NullPointerException

2. Static level:

Example 1:

static int[] a; System.out.println(a);//null System.out.println(a[0]);//R.E:NullPointerException
Example 2:

static int[] a=new int[3]; System.out.println(a);//[I@3e25a5 System.out.println(a[0]);//0

3. Local level:

Example 1:

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


Hence the following are the various possible combinations for variables.

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.


We can declare a var-arg method as follows.



Example 1: 





We can call or invoke this method by passing any no. Of int values including zero number also.

Example:
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);
      } 
}
Output:
    var-arg method
    var-arg method
    var-arg method

Internally var-arg parameter implemented by using single dimensional array hence within the var-arg method we can differentiate arguments by using index.

Example : 
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);
  }
}
Output:
    The sum: 0
    The sum: 10
    The sum: 30
    The sum: 100

Example : 
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);
    }
}
Output:
    The sum: 0
    The sum: 10
    The sum: 30
    The sum: 100

Case 1:

Which of the following var-arg method declarations are valid?
  1. methodOne(int... x) (valid)
  2. methodOne(int ...x) (valid)
  3. methodOne(int...x) (valid)
  4. methodOne(int x...) (invalid)
  5. methodOne(int. ..x) (invalid)
  6. methodOne(int .x..) (invalid)

Case 2:

We can mix var-arg parameter with general parameters also.
Example:
    methodOne(int a,int... b) //valid methodOne(Strings,int...x) //valid
    

Case 3:

if we mix var-arg parameter with general parameter then var-arg parameter should be the last parameter.
Example:
    methodOne(int a,int... b) //valid methodOne(int... a,int b) //(invalid)

Case 4:

With in the var-arg method we can take only one var-arg parameter. i.e., if we are trying to more than one var-arg parameter we will get CE.

Example:
    methodOne(int... a,int... b) //(invalid)

Case :5
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 } }
In general var-arg method will get least priority that is if no other method matched then only var-arg method will get the chance this is exactly same as default case inside a switch.

Case 6:
For the var-arg methods we can provide the corresponding type array as argument.
Example:
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){} }
Output:
    Compile time error.
    Cannot declare both methodOne(int...) and methodOne(int[]) in Test

Single Dimensional Array Vs Var-Arg Method:
Case 1:
Wherever single dimensional array present we can replace with var-arg parameter.
Example:
class Test { public static void main(String... args) { method } }
Case 2:
Wherever var-arg parameter present we can't replace with single dimensional array.
Note :

  1. 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)
  1. 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)


Above reasons this case 2 is invalid.
Example: 
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); } }
Output: 
    10
    40

Analysis:



















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.


Example:
    class Test
    {}

Output:
    javac Test.java
    java Test R.E: 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.

  1. The order of modifiers is not important that is instead of public static we can take static public.
  2. We can declare string[] in any acceptable form
    1. String[] args
    2. String []args
    3. String args[]
  3. Instead of args we can use any valid java identifier.
  4. We can replace string[] with var-arg parameter.

    Example: main(String... args)
  5. main() method can be declared with the following modifiers.final, synchronized, strictfp.
  6. class Test {
  7. static final syncronized strictfp public void main(String... ask){ 8. System.out.println("valid main method");
  8. }
  9. }
  10. output :
  11. valid main method 
Which of the following main() method declarations are valid ? 
  1.  Public static void main(String args){} (invalid)
  2.  public synchronized final strictfp void main(String[] args){} (invalid)
  3.  public static void Main(String... args){} (invalid)
  4.  public static int main(String[] args){} //int return type we can't take //(invalid)
  5.  public static synchronized final strictfp void main(String... args){}(valid)
  6.  public static void main(String... args){}(valid)
  7.  public void main(String[] args){}(invalid)
In which of the above cases we will get compile time error ? 
No case, in all the cases we will get runtime exception.

Case 1:
Overloading of the main() method is possible but JVM always calls string[] argument main() method only.
      
Example:
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"); } }

Output:
String[] array main method

The other overloaded method we have to call explicitly then only it will be executed.

Case 2:
Inheritance concept is applicable for static methods including main() method
hence while executing child class if the child class doesn't contain main() method then the parent class main() method will be executed.

Example 1:

class Parent { public static void main(String[] args) { System.out.println("parent main"); } } class Child extends Parent {}

 Analysis:



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"); } }
Analysis :


It seems to be overriding concept is applicable for static methods but it is not overriding it is method hiding.

Version Enhansements with respect to main() :

Case 1 :

  • 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 { }
1.6 version :
    javac Test.java
    java Test    
    RE: NoSuchMethodError:main

1.7 version :
    javac Test.java
    java Test
    Error: main method not found in class Test, please define the main method as
    public static void main(String[] args)

Case 2 :
  • 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"); }
}}
1.6 version :
    javac Test.java
    java Test
output :
static block
RE: NoSuchMethodError:main

1.7 version :
    javac Test.java
    java Test
output :
Error: main method not found in class Test, please define the main method as
public static void main(String[] args)

Case 3 :

class Test {
 static {
    System.out.println("static block");
      System.exit(0);
 }}
1.6 version :
    javac Test.java
    java Test
output :
    static block
 
1.7 version :
    javac Test.java
    java Test
    Error: main method not found in class Test, please define the main method as
    public static void main(String[] args)

Case 4 :

class Test {
 static {
  System.out.println("static block"); }
  public static void main(String[] args) {
     System.out.println("main method");
  } 
}
1.6 version :
    javac Test.java
    java Test
output :
    static block
    main method

1.7 version :
    javac Test.java
    java Test
output :
    static block
    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. 

Example 1:

class Test {
       public static void main(String[] args) {
          for(int i=0;i<=args.length;i++) {
              System.out.println(args[i]);
          } 
       }
}

Output:

java Test x y z ArrayIndexOutOfBoundsException: 3
       Replace i<=args.length with i<args.length then it will run successfully.

Example 2:

public static void main(String[] args) {
       String[] argh={"X","Y","Z"}; args=argh;
         for(String s : args) {
              System.out.println(s);
        }
}

Output:
    java Test A B C    
        X
        Y
        Z
    java Test A B
        X
        Y
        Z
    java Test 
        X
        Y
        Z

Within the main() method command line arguments are available in the form of String hence "+" operator acts as string concatenation but not arithmetic addition.

Example 3:

class Test {
  public static void main(String[] args) {
       System.out.println(args[0]+args[1]);
   } 
}
Output:
E:\SCJP>javac Test.java E:\SCJP>java Test 10 20 1020
Space is the separator between 2 command line arguments and if our command line argument itself contains space then we should enclose with in double quotes.

Example 4:

class Test {
       public static void main(String[] args) {
              System.out.println(args[0]);
       } 
}
Output:
E:\SCJP>javac Test.java 
E:\SCJP>java Test "Sai Charan" 
Sai Charan

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:

  1. Serializable 
  2. Runnable 
  3. 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)

Coding standards for variables:
  • 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)
Example:
    length
    name
    salary
    age
    mobileNumber

Coding standards for constants:
  • 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.
Example:
MAX_VALUE
MIN_VALUE             nouns 
NORM_PRIORITY

Java bean coding standards
A java bean is a simple java class with private properties and public getter and setter methods
Example:



1. Syntax for setter method:
  1. Method name should be prefixed with set.
  2. It should be public.
  3. Return type should be void.
  4. Compulsory it should take some argument.
2. Syntax for getter method:
  1. The method name should be prefixed with get.
  2. It should be public.
  3. Return type should not be void.
  4. It is always no argument method.
        
Note :
  • For the boolean properties the getter method can be prefixed with either get or is. But recommended to use is.
Example:


Coding standards for listeners:
To register a listener:
Method name should be prefixed with add.
  1. public void addMyActionListener(MyActionListener l) (valid)
  2. public void registerMyActionListener(MyActionListener l) (invalid)
  3. public void addMyActionListener(ActionListener l) (invalid)
To unregister a listener:
The method name should be prefixed with remove.
  1. public void removeMyActionListener(MyActionListener l) (valid)
  2. publc void unregisterMyActionListener(MyActionListener l) (invalid)
  3. public void removeMyActionListener(ActionListener l) (invalid)
  4. public void deleteMyActionListener(MyActionListener l) (invalid)

Various Memory areas present inside JVM

  1. Class level binary data includung static variables will be stored in method area.
  2. Objects and corresponding instance variables will be stored in Heap area.
  3. 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.
  4. Every entry in stack is called Stack Frame or Action Record.
  5. The instruction which has to execute next will be stored in the corresponding PC Registers. 

You may also like

Kubernetes Microservices
Python AI/ML
Spring Framework Spring Boot
Core Java Java Coding Question
Maven AWS