By Value or By Reference
- Primitive variables are passed by value in a method and their values don’t change in calling method.
- Changes in the reference variables which are done in the called method, are also seen by the calling method.
Loading, Linking and Initialization
- Loading
- Loads the binary representation of class.
- Linking
- Verification
- Preparation
- Resolution
- Initialization
- Defaulting of member variables.
- Difference between object initialization and static initialization.
public class MyClass {
static {
System.out.println
("Static initialization block");
}
public static int myField = 42;
public static void main(String[] args) {
System.out.println("Main method");
}
}
In this example:
- Class loading occurs when the program is run.
Linking includes - verification, preparation (allocating memory for myField), and resolution.
- Initialization includes executing the static
initialization block and initializing myField.
When you run the program, you’ll see the following output:
Static initialization block
Main method
Comparing Objects
- Compares the reference pointed by two objects is same or not.
- Not very meaningful, until you implement equals() and hashCode() methods of Object class.
The Garbage Collector
- JVM runs the garbage collector program to free the unused memory.
- So unlike C++, in java you don’t have to explicitly free memory references.