Monday 26 March 2018

Does finally always execute in Java?

Yes, finally will be called.
The only times finally won't be called are:
  1. If you invoke System.exit();
  2. If the JVM crashes first;
  3. If there is an infinite loop (or some other non-interruptable, non-terminating statement) in the try block;
  4. If the OS forcibly terminates the JVM process.
  5. If the host system dies; e.g. power failure, hardware error, etc.

Is Java “pass-by-reference” or “pass-by-value”?

Java is always pass-by-value. Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the reference to it. This is confusing to beginners.

Example;

public static void main( String[] args ) {
    Dog aDog = new Dog("Max");
    // we pass the object to foo
    foo(aDog);
    // aDog variable is still pointing to the "Max" dog when foo(...) returns
    aDog.getName().equals("Max"); // true, java passes by value
    aDog.getName().equals("Fifi"); // false 
}

public static void foo(Dog d) {
    d.getName().equals("Max"); // true
    // change d inside of foo() to point to a new Dog instance "Fifi"
    d = new Dog("Fifi");
    d.getName().equals("Fifi"); // true
}
In this example aDog.getName() will still return "Max". The value aDog within main is not changed in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo.

Can main() method overloaded ??

Yes, main() can be overloaded. Let’s see the following examples for better clarity :

ExampleMain.java

class ExampleMain
{
public static void main(String[] args)
{
System.out.println("Hiii");
}

public static void main(int x)
{
System.out.println("Hello");
}

}

Output
Hiii