THROWS VS THROW
1. Throws clause in used to declare an exception and throw keyword is used to throw an exception explicitly.
2. If we see syntax wise, throw is followed by an instance variable and throws is followed by exception class names.
3. The keyword throw is used inside method body to invoke an exception and throws clause is used in method declaration (signature).
Throw:
static{
try {
throw new Exception("Something went wrong!!");
} catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}
}
Throws:
public void sample() throws ArithmeticException{
//Statements
.....
//if (Condition : There is an error)
ArithmeticException exp = new ArithmeticException();
throw exp;
...
}
Cloning
By default, java cloning is ‘field by field copy’ i.e. as the Object class does not have idea about the structure of class on which clone() method will be invoked. So, JVM when called for cloning, do following things:
1) If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.
2) If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.
In java, if a class needs to support cloning it has to do following things:
A) You must implement Cloneable
B) You must override clone() method from Object class.
EXAMPLE
Employee cloned = (Employee) original.clone();
System.out.println(cloned.getEmpoyeeId());
Finally
Finally block will execute even if you put return statement in try block or catch block but finally block won’t run if you call System.exit form try or catch.
Static
non-static variable cannot be referenced from a static context. Static variable belongs to Java class while non-static variable belongs to object. Static variable will keep same value for every object while value of non static variable varies from object to object.
Static fields are initialized at the time of class loading in Java, opposite to instance variable which is initialised when you create instance of a particular class.Static method can not be overridden in Java as they belong to class and not to object. If you try to override a static method with a non-static method in sub class you will get compilation error.
How to access non static variable inside static method or block
public class StaticTest {
private int count=0;
public static void main(String args[]) throws IOException {
StaticTest test = new StaticTest(); //accessing static variable by creating an instance of class
test.count++;
}
}
Yes, we can overload static method in Java.