Daily Archives: December 30, 2017

default keyword in Java

  1. default can be used in switch statement.
  2. default can be used in annotation, specifying the default value. For example:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Todo {
    String author() default "Yash";
}

@Todo(author = "Yashwant")
public void incompleteMethod1() {
    //Some business logic is written
    //But it’s not complete yet
}

Local/Instance/Class variable

Local variable, variable defined inside method, constructor or block.
Instance variable, a variable inside class. It can be instantiated.
Class variable, inside class, but outside method. Must be static. Only one copy per class.

public class MyTest {

    static String str = "abcd";  // classs variable, only one copy

    private String a = "123";   // instance variable, can be copied by instantiation

    public int calculate() {
        int a = 1;  // local variable
        return a;
    }

}