JavaIntellectualTricks

Java Coding Standards

Whenever we are writing java code, it is highly recommended to follow coding standards.
Whenever we are writing any component, it's name should reflect the purpose of that component (functionality). The main advantage of this approach is readability and maintainability of the code will be improved.
Example:
//Not Recommended
class A {
 public int m1(int x, int y) {
  return x + y;
 }
}
//Recommended
package com.learning.java public class Calculator { public static int sum(int firstNumber, int secondNumber) { return firstNumber + secondNumber; } }
Coding standard for class:
Usually class names are nouns, should starts with upper case character and if contains multiple words every inner word should starts with upper case character.
Example:
String
StringBuilder
Account
Student

Coding standard for interfaces:
Usually interface names are adjectives, should starts with upper case character and if contains multiple words every inner word should starts with upper case character.
Example:
Runnable
Serializable
Comparable

Coding standard for methods:
Usually method names are either verbs or verb-noun combinations, should starts with lower case character and if contains multiple words every inner word should starts with upper case character.(camel case convention)
Example:
print()
run()
start()
setName()
getSalary()

Coding standard for variable:
Usually variable names are nouns, should starts with lower case character and if contains multiple words every inner word should starts with upper case character.(camel case convention)
Example:
name
age
MobileNumber
Coding standard for constant:
Usually constant names are nouns, should contain only upper case characters and if it contains multiple words, then these words are separated with underscore(_) symbol.
Example:
MAX_VALUE
PI
MAX_PRIORITY
MIN_PRIORITY

Note: Usually we can declare constants with public static and final modifiers.

Coding standard for JavaBean:
A Java Bean is a simple java class which contains some private variables along with public setter and getter methods for those variables.
Example:
public class Student{
private String name;
public void setName(String name){
this.name=name;
}
public String getName(){
return name;
}
}
class name ends with Bean is not official convention. i.e  “StudentBean” naming convention is not recommended.

Syntax for setter method:

  • It should be public method.
  • Return type should be void.
  • Method name should be prefixed with set
  • method should contain some arguments

Syntax for getter method:

  • It should be public method.
  • Return type should not be void.
  • Method name should be prefixed with get
  • method should not contain any argument

Note: for boolean property getter method name can be prefixed with either “get” or “is”, but recommended to use “is”
Example:
private boolean empty;
public boolean isEmpty(){
return empty;
}
public boolean getEmpty(){
return empty;
}

Coding standard for Listeners:
case 1:
To register a listener:
method name should be prefixed with “add”
method should be public
Example:
public void addMyActionListener(myActionListener  l) //valid
public void registerMyActionListener(myActionListener l) //Invalid
public void addMyActionListener(ActionListener l) //Invalid

case 2:
To de-register a listener:
method name should be prefixed with “romove”
method should be public
Example:
public void removeMyActionListener(myActionListener  l) //valid
public void unRegisterMyActionListener(myActionListener l) //Invalid
public void addMyActionListener(ActionListener l) //Invalid
public void deleteMyActionListener(myActionListener l) //Invalid

Command Line Arguments


  • The arguments which are passing from command prompt are called command line arguments.
  • With these command line arguments JVM will create an array and by passing that array as argument JVM will call main().

Example:
>java Test A B C
A=args[0];
B=args[1];
C=args[2];

The main objective of command line arguments is we can customize behavior of the main().

Q. Why java main( ) takes always String as parameter?

Case 1:
class Test {
 public static void main(String[] args) {
  for (int i = 0; i <= args.length; i++) {
   System.out.println(args[i]);
  }
 }
}
>java Test A B // o/p: A B  ArrayIndexOutsOfBoundsException
>java Test A B C // o/p: A B C  ArrayIndexOutsOfBoundsException
If we replace <= with < ,then we won't get any run time exception.

Case 2:
class Test {
 public static void main (String[] args){ 
  String[] argh={“X”,”Y”,”Z”}; 
  args=argh; 
  for(String s: args){ 
   System.out.println(s); 
  } 
 }
}
o/p:
>java Test A B // o/p: X Y Z
>java Test A B C // o/p: X Y Z    

Case 3:
With in main() command line arguments are available in String form.
class Test {
 public static void main(String[] args) {
  System.out.println(args[0] + args[1]);
 }
}
> javaTest 10 20 //o/p: 1020

Case 4:
Usually space itself is the separator between command line arguments. If our command line arguments itself contains the space then we have to enclose that command line arguments with in double quotes.
class Test {
 public static void main(String[] args) {
  System.out.println(args[0]);
 }
}
> java Test “Note Book” //o/p:  Note Book

Exploring main( ) method

Whether class contains main( ) method or not and whether main() is declared according to requirement or not , these things won't be checked by compiler. At run time JVM is responsible to check these things. If JVM unable to find main(), then we will get run time exception saying ”NoSuchMethodError: main”

class Test{
}
>javac Test.java // No error
>java Test // NoSuchMethodError: main

At run time JVM always searches for the main() with the following prototype.
public static void main(String[] args)
Here:
public refers – to call by JVM from anywhere
static refers – without existing object also JVM has to call this method for one time.
void refers – main() won't return anything to JVM
main refers – this is the name which is configured inside JVM
String[] args refers – command line arguments

The above syntax is very strict and we perform any change then we will get run time exception saying NoSuchMethodError: main

Even though the above syntax is very strict, the following changes are acceptable.

  • Instead of public static , we can take static public i.e the order of modifier is not important.             We can declare String array in any acceptable form

main(String[] args)
main(String  []args)
main(String  args[])

  • We can take any valid java identifier instead  of args.
main(String[]  purna)

  • We can replace String array with var-arg parameter

main(String...  args)

  • We can declare main() with the following modifiers

final, synchronized, strictfp
class Test{
static final synchronized strictfp public void main(String...  purna){
System.out.println(“valid main method”);
}
}

Q1. Which of the following main() declarations are valid?
1. public static void main(String args) // (Invalid)
2. public static void Main(String[] args) // (Invalid)
3. public  void main(String[] args) // (Invalid)
4. public static int  main(String[] args) // (Invalid)
5. final synchronized strictfp public void main(String[]  args) // (Invalid)
6. final synchronized strictfp public  static void main(String[]  args) // (valid)
7. public static void main(String...  args) // (valid)

Q2.In which of the above cases we will get compile time error ?
We won't get compile time error anywhere. But except last two cases in remaining we will get runtime exception saying  NoSuchMethodError: main

Case 1: 
Overloading of the main method is possible ,but JVM will always call String[] arguments main() only.
The other overloaded method, we have to call explicitly like normal method call.
class Test{
public static void main(String[] args){
System.out.println(“String []”);
}
public static void main(int[] args){ //overloaded methods
System.out.println(“int []”);
}
}
o/p: String [ ]

Case 2:
inheritance concept applicable for main(), hence while executing child class if child does not contain main(), then parent class main () will be executed.

//p.java
class P{
public static void main(String[] args){
System.out.println(“Parent main”);
}
}
class C extends P{
}
>javac P.java
>java P  // o/p: Parent main
>java C // o/p: Parent main

Case 3: 
It seems overriding concept applicable for main(), but it is not method overriding, but it is method hiding.
//p.java
class P{
public static void main(String[] args){
System.out.println(“Parent main”);
}
}
class C extends P{
public static void main(String[] args){ // It is method hiding but not method overriding
System.out.println(“Child main”);
}
}
>javac P.java
>java P  // o/p: Parent main
>java C // o/p: Child main

Note:
For main() inheritance and overloading concepts are applicable, but overriding concept is not applicable. Instead of overriding,  method hiding is applicable.

1.7 version enhancements w.r.t main():

Until 1.6 version, if the class doesn't contain main(), then we ll get run time exception saying  NoSuchMethodError: main. But from 1.7 version onwards instead of   “NoSuchMethodError: main” we will get more elaborated information.
Example:
class Test{
}
1.6 version:
>javac Test.java
>java Test //R.E: NoSuchMethodError: main
1.7 version:
>javac Test.java
>java Test   //R.E. Main method not found in class Test, please define the main method as:
public static void main(String[] args)

From 1.7 on wards main() is mandatory to start program execution,hence even though class contains static block it won't be executed if the class does not main().
Example 1:
class Test{
static {
System.out.println(“static block”);
}
}
1.6 version:
>javac Test.java
>java Test // static block & R.E: NoSuchMethodError: main
1.7 version:
>javac Test.java
>java Test //R.E. Main method not found in class Test, please define the main method as:
public static void main(String[] args)
Example 2:
class Test{
static {
System.out.println(“static block”);
System.exit(0);
}
}
1.6 version:
>javac Test.java
>java Test // static block
1.7 version:
>javac Test.java
>java Test //R.E. Main method not found in class Test, please define the main method as:
public static void main(String[] args)

Example 3:
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 // static block
    // main method
1.7 version:
>javac Test.java
>java Test // static block
    // main method

1.6 flowchart:
1. Identification of static members
2. execute static blocks and static variable assignments
3. check for main()

  • If it is available execute main()
  • If it is not available R.E: NoSuchMethodError: main
1.7 flowchart:
1. check for main()

  • If it is available identifies static members then execute static blocks and static variable assignments
  • If it is not available Error: R.E. Main method not found in class Test, please define the main method as: public static void main(String[] args) then program terminates.
Q. Without writing main() is it possible to print some statements to the console?
Ans: Yes by using static block, but this rule is applicable until 1.6 versions, but from 1.7 version onwards it is impossible to print some statements to the console with out writing main().



var- arg methods

Variable Number of Argument methods:

Until 1.4 version , we cannot declare a method with variable number of arguments. If there is a change in number of arguments, compulsory we should go for new method, which increases length of the code and reduces readability. To overcome this problem SUN people introduced var-args methods in 1.5 version. According to this we can declare a method which can take variable number of arguments, such type of methods are called var- arg methods.
Syntax: methodName(int... x);


  • We can call this method by passing any number of int values including 0 number. i.e.  sum(int... x) then we can call this sum method by sum(); sum(10); sum(10,20); sum(10,20,30); sum(10,20,30,40);

class Test{
public static void sum(int... x){
System.out.println(“var-arg method”);
}
public static void main(String args []){
sum();
sum(10);
sum(10,20);
sum(10,20,30);
sum(10,20,30,40);
}
}
>javac Test.java
>java Test
o/p:      var-arg method
    var-arg method
    var-arg method
    var-arg method
    var-arg method

  • Internally var-arg parameter is converted in to one dimensional array. Hence with in the var-arg method we can differentiate values by using index.

class Test{
public static void sum(int... x){
int total=0;
for(int x1: x){
total=total+x1;
}
System.out.println(“Sum is: ”+ total);
}
public static void main(String args []){
sum();
sum(10);
sum(10,20);
sum(10,20,30);
sum(10,20,30,40);
}
}
o/p:   Sum is : 0
Sum is : 10
Sum is : 30
Sum is:  60
Sum is:  100

Q. Which of the following are the valid var-arg declarations?
1. m1(int...  x)  (valid)
2. m1(int   ...x) (valid)
3. m1(int...x)    (valid)
4. m1(int  x...) (Invalid)
5. m1(int.  ..x) (Invalid)
6. m1(int  .x..) (Invalid)

  • we can use var-arg parameter with normal parameter i.e

m1(int x, int... y)
m1(String s,double... d)
If we mix normal parameter with var-arg parameter, then var-arg parameter should be last parameter. i.e.
m1(double... d,String s) (Invalid)
m1(char ch,d,String... s) (valid)

  • Inside var-arg method we can take only one var-arg parameter and we can't take more than one var-arg parameter. i.e.

m1(int...  x ,double... d) (Invalid)

  • Inside a class we can't declare var-arg method and corresponding 1-D array method simultaneously, otherwise we ' ll get compile time error.

class Test{
public static void m1(int...  x){
System.out.println(“int...”);
}
public static void m1(int[]  x){
System.out.println(“int[]”);
}
}
C.E.: cannot declare both m1(int []) and m1(int...) in Test

  • In general, var-arg method will get least priority i.e if no other method matched then only var-arg method will get the chance to execute

.It is exactly same as default case inside switch.
class Test{
public static void m1(int...  x){
System.out.println(“var-arg method”);
}
public static void m1(int  x){
System.out.println(“Normal Method”);
}
public static void main(String args []){
m1(); //  var-arg method
m1(10); // Normal Method
m1(10,20); // var-arg method
}
}

Equivalence between var-arg parameter and one dimensional array:

case 1: Where ever one dimensional array is present, we can replace with var-arg parameter.
m1(int[]  x) = = m1(int...  x) (valid)
Example: main(String[] args) = = main(String...  args)

case 2:  Where ever var-arg parameter ispresent, we can't replace with  one dimensional array.
m1(int...  x) = = m1(int[]  x) (invalid)

Note: 
1. m1(int...  x) = =  int[]  x
we can call this method by passing a group of int values and x will become one dimensional array.
2. m1(int[]...  x) = = int[][]  x

  • We can call this method by passing a group of dimensional int arrays and x will become 2 D int array

class Test{
public static void main(String args []){
int[] a={10,20,30};
int[] b={40,50,60};
m1(a,b);
}
public static void m1(int[]...  x){
for(int[]  x1: x){
System.out.println(x1[0]); // 10, 40
}
}
}

Variables

Types of variable:
Based on type of value represented by a variable, all variables are divide in to 2 types.
1.Primitive variables
Primitive variables can be used to represent primitive values.
Example:
int x=10; // here x is called as primitive variables
2.Reference variables
Reference variables can be used to refer objects
Example:
Student s=new Student(); // here s is called as reference variable

Based on position of declaration and behavior all variables are divide in to 3 types.
1. instance variables
2. static variables
3. local variables

Instance variables:
  • If the value of a variable is varied from object to object, such types of variable are called as instance variables.
  • For every object, a separate copy of instance variable is created.
  • Instance variables should be declared with in the class directly, but outside of any method or constructor or block.
  • Instance variables are created when an object is created and destroyed at the time of object destruction, hence the scope instance variable is exactly same as object.
  • Instance variables will be stored in the heap memory as a part of object.
  • We can't access instance variables directly from static area, but we can access by using object reference.But we can access instance variables directly from instance area.
Example:
class Test{
int x=100;
public static void main(String [] args){
System.out.prinln(x); // C.E Non-static variable x cannot be referenced from a static context
Test t= new Test();
System.out.prinln(t.x);  //100
}
public void m1(){
System.out.prinln(x);  //100
}
}
For instance variables JVM is always providing default initial value and we are not required to perform initialization explicitly.
Example:
class Test{
int i;
boolean b;
double d;
String s;

public static void main(String [] args){
Test t= new Test();
System.out.prinln(t.i);  //0
System.out.prinln(t.b); //false
System.out.prinln(t.d); //0.0
System.out.prinln(t.s); //null
}
}
Instance variables are also known as object level variables or attributes.

Static variables:
  • If the value of the variable not varied from object to object, then it is not recommended to declare variable as instance variable. We have to declare such type variables as 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, a single copy will be created at class level and shared by every object of the class.
  • Instance variables should be declared with in the class directly, but outside of any method or constructer or block.
  • Instance variables are created at the time of class loading and destructed at time of class unloading, hence the scope of the static variables is exactly same as the scope of the .class file.

If we are trying to run a simple java program the following steps are carring on:-
> java Test

1. start the JVM.
2. create and start main thread.
3. Locate the Test.class file
4. Load the Test.class file
5. Execute main() method
6. Unload  Test.class file
7. Terminate main thread
8. Shutdown the JVM

static variables will be stored in method area.
We can access static variable either by object reference or by class name, but recommended to use class name.
With in the same class it is not required to use class name and we can use directly.
class Test{
int x=100;
public static void main(String [] args){
System.out.prinln(x); // C.E Non-static variable x cannot be referenced from a static context
Test t= new Test();
System.out.prinln(t.x);  //100
}
public void m1(){
System.out.prinln(x);  //100
}
}

For instance variables JVM is always providing default initial value and we are not required to perform initialization explicitly.
Example:
class Test{
int x=10;
public static void main(String [] args){
Test t= new Test();
System.out.prinln(t.x);  //10
System.out.prinln(Test.x); //10
System.out.prinln(x); //10
}
}
We can access static variables directly from both instance and static areas.
class Test{
int x=100;
public static void main(String [] args){
System.out.prinln(x); // C.E Non-static variable x cannot be referenced from a static context
Test t= new Test();
System.out.prinln(t.x);  //100
}
public void m1(){
System.out.prinln(x);  //100
}
}

For instance variables JVM is always providing default initial value and we are not required to perform initialization explicitly.
Example:
class Test{
int i=10;
public static void main(String [] args){
System.out.prinln(i);  //10
}
public void m1(){
System.out.prinln(i);  //10
}
}
For static variables JVM will provide default values and we are not required to perform initialization explicitly.
Example:
class Test{
static int i;
static boolean b;
static double d;
static String s;

public static void main(String [] args){
System.out.prinln(Test .i);  //0
System.out.prinln(Test .b); //false
System.out.prinln(Test .d); //0.0
System.out.prinln(Test .s); //null
System.out.prinln(i);  //0
System.out.prinln(b); //false
System.out.prinln(d); //0.0
System.out.prinln(s); //null
}
}
static variables are also known as class level variables or fields.
Example:
class Test{
static int x=10;
int x=20;
public static void main(String [] args){
Test t1=new Test();
t1.x=111;
t1.y=222;
Test t2=new Test();
System.out.prinln(t2.x+”--”+t2.y);  //111--20
}
}

Local variables:
  • The variables which are inside the constructor, block or method are called local variables.
  • Sometimes to meet temporary requirements of the programmer, we can declare a variable inside a method, block or constructor . Such type of variables are also called as local/automatic/stack/temporary variable.
  • Local variables will be stored inside stack memory.
  • Local variables will be created while executing the block in which we declared it .
  • Once block execution completes, automatically local variables will be destroyed. Hence the scope of local variable is the block in which we declared  it.

Example 1:
class Test{
public static void main(String [] args){
int i=0;
for(int j=0;j<3;j++){
i=i+j;
}
System.out.prinln(i+” ”+j);  // C.E cannot find symbol, symbol: variable j, location: class Test
}
}
Example 2:
class Test{
public static void main(String [] args){
try{
int j=Integer.parseInt(“ten”);
}
catch(NumberFormatException  nfe){
j=10;  // C.E cannot find symbol, symbol: variable j, location: class Test
}
 System.out.prinln(j);  // C.E cannot find symbol, symbol: variable j, location: class Test
}
}

For local variables JVM won't provide default values, compulsorily we should perform initialization explicitly before using that variable i.e if we are not using then, it is not required to perform initialization.

Example 1:
class Test{
public static void main(String [] args){
int i;
System.out.prinln(“Hello”); // Hello
}
}
Example 2:
class Test{
public static void main(String [] args){
int i;
System.out.prinln(i); // C.E : variable i might not have been initialized
}
}
Example 3:
class Test{
public static void main(String [] args){
int i;
if(args.length>0){
x=10;
}
System.out.prinln(i); // C.E : variable i might not have been initialized
}
}
Example 4:
class Test{
public static void main(String [] args){
int i;
if(args.length>0){
x=10;
}
else{
x=20;
}
System.out.prinln(i);  // No Error //Java Test  A B then o/p=10, //Java Test  then o/p=20
}
}
Note :
1. It is not recommended to perform initialization for local variables inside logical blocks because there is no guarantee for the execution of these blocks always at run time.
2. It is highly recommended to perform  initialization for local variables  at the time of declaration at least with default values.
3. The only applicable modifier for local variables is final. Bymistake if we are trying apply any other modifier then we 'll get compile time error.

Example:
class Test{
public static void main(String [] args){
public int x=10; // C.E Illegal start of expression
private int x=10; // C.E Illegal start of expression
protected int x=10; // C.E Illegal start of expression
static int x=10; // C.E Illegal start of expression
transient int x=10; // C.E Illegal start of expression
volatile int x=10; // C.E Illegal start of expression
final int x=10; // No error
}
}
Note:
If we are not declaring with any modifier then by default it is default. But this rule is applicable only for instance and static variables but not for local variables.

Conclusions:
1. For instance and static variables JVM is providing deafult values and we are not required to perform initialization explicitly. But for local variaable JVM won't provide deafult values and we are  required to perform initialization explicitly before using that variable.
2. Instance and static can be accessed by multiple threads simultaneously and hence these are not thread safe. But in the case of local variables for every thread a separate copy will be created and hence local variables are thread safe.
3. Every variable in java should be either instance or static or local. Every variable in java should be either primitive or reference. So the various possible combinations of variable in java are instance-primitive, instance-reference, static-primitive, static-reference, local-primitive and local-reference.

UnInitialized arrays:
class Test{
int[] x;
public static void main(String [] args){
Test t=new Test();
System.out.println(t.x); //null
System.out.println(t.x[0]); //NullPointerException
}
}

Instance level:
int[] x;
System.out.println(obj.x); //null
System.out.println(obj.x[0]); //NullPointerException

int[] x=new int[3];
System.out.println(obj .x); // [I e3563@5
System.out.println(obj .x[0]); //NullPointerException

Static level:
static int[] x;
System.out.println(obj.x); //null
System.out.println(obj.x[0]); //NullPointerException


static int[] x=new int[3];
System.out.println(obj .x); // [I e3563@5
System.out.println(obj .x[0]); //NullPointerException

Local level:
int[] x;
System.out.println(obj.x); // variable x might not have been initialized
System.out.println(obj.x[0]); // variable x might not have been initialized

int[] x=new int[3];
System.out.println(obj .x); // [I e3563@5
System.out.println(obj .x[0]); //0