Static_Scope_Garbage_collection Flashcards

1
Q

What is the difference between Class and Object?

A
  • Class is like a Blueprint and Object is like an actual House.
  • The Blueprint/House analogy for the Class/Object relationship is probably the simplest way to understand the difference between a Class and an Object. Blueprint tells you a lot about a House, but you can’t live in a Blueprint. It provides detailed instructions about what a house is supposed to look like.
  • A House is created from a Blueprint.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Can a class have a variable like every object has instance variables?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are static variables in Java?

A
  • Static variables are variables associated with the Class itself instead of Objects.
  • Class variables are also called static variables.
  • They are called static variables because the static keyword is used to identify them.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Provide an example of the static variable creation in Java.

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How are static variables accessed in Java? Provide an example.

A
public class Car {
    //Initialization block
    {
        color = "Red";
    }
String color = "Green";
String type;
int serialNumber;
//Static Variable declaration
static int carCount; } ~~~

// Inside Main

        // Static variable access
        // Note: Used name of the class to access as it is a static variable
        Car.carCount = 1; // Correct way of accessing static variable
        // Below is not a preferred(although its legal) way of 
        // accessing a static variable, as it is not tied to an object.
        c.carCount = 2;

~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

When is a Static variable initialized?

A

Note: As in the below notes we said carCount will always be 1. To make this increment, there has to be more work done in constructors to achieve the goal of keeping track of the count of the Cars.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Taking the example of static variable carCount in Car class. Write code in the class to achieve the goal of keeping the count of the cars for each new object created and also maintain a serial number for each Car.

A
// User defined default constructor
    Car() {
        carCount++;
        serialNumber = carCount;
        //color = "Blue";
    }
// User defined constructor
Car(String c, String t){
    color = c;
    type = t;
    carCount++; 
    serialNumber = carCount;
} ~~~
    // In Main
        Car c1, c2, c3;
        c1 = new Car("Red", "Sedan");
        c2 = new Car("Green", "Coupe");
        c3 = new Car("Blue", "SUV");
 System.out.println("Car1 SerialNumber: " + c1.serialNumber); System.out.println("Car2 SerialNumber: " + c2.serialNumber); System.out.println("Car3 SerialNumber: " + c3.serialNumber);
        System.out.println("Static variable print: " + Car.carCount);

```

Note: Also, check the attached picture to see how the JVM memory is used for this implementation. It clearly shows that carCount being static is not tied to Objects, but to the Class Car.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are Static methods in Java?

A
  • The static keyword can also be applied to a method. A static method, like a static variable, is associated with the class, not the objects(instances)
  • Refer attached picture for example:
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Can static methods access instance variables?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the point of having static methods if we cannot access instance variables or methods from it?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

When are static methods or variables or initialization blocks loaded?

A

As soon as Class is loaded into JVM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is a static initialization block?

A
public class Car {
    //Initialization block
    {
        color = "Red";
    }
//static initialization block
static {
    //color = "Yellow"; // Illegal as non-static variable
    //printDescription(); // Illegal as non-static method
    setCarCount(3);
} ~~~

String color;
String type;
int serialNumber;
    //Static Variable declaration
    static int carCount;
    // Constructors
    // User defined default constructor
    // Compiler will not create a default constructor in this case
    Car() {
        carCount++; // Static variable increment
        serialNumber = carCount;
        color = "Blue";
    }
    // User defined constructor
    Car(String c, String t){
        color = c;
        type = t;
        carCount++;
        serialNumber = carCount;
    }
    void printDescription()
    {
        System.out.println("This is a " + color + " " + type);
    }
    // Static Methods
    static void setCarCount(int c)
    {
        carCount = c;
    }
    static void resetCarCount()
    {
        carCount = 0;
    }
}

~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How is “this” is used?

A

Consider the below example. When customize is called with 2 arguments with the same variable names color and type which will be declared when the function customize is called. The compiler looks up in the local block first to resolve if the color is already present. Then, it encounters another variable color with the same name in the assignment, which also resolves to be a local variable. This assigns the value to the local variable, but that was not our intention. The class instances are not changed.

void customize(String color, String type)
    {
        color = color; // Both resolve to same local variable color
        type = type + " " + type; // same here as color, variable type also
        System.out.println(getDescription());
    }

For resolving such variable name issues, “this” is used. Which will differentiate between local and instance variables. Re-writing the above code with this:

void customize(String color, String type)
    {
        this.color = color;
        this.type = type + " " + type;
        System.out.println(getDescription());
    }

In the picture below, let’s see how stack and heap references will be when an object myCar is created in main. We assume the initial values of color=red and type=celica. And, myCar object called customize with “blue” and “convertible”.

Note: “this” will also prevent local lookup and consider the variable is already an instance variable of the object and goes directly to the heap.

Another use of “this” in chaining constuctors. In below code there is a block of code repeated in both the constructors.

Car() {
        carCount++; // Static variable increment
        serialNumber = carCount;
        color = "Blue";
    }
// User defined constructor
Car(String color, String type){
    this.color = color;
    this.type = type;
    carCount++;
    serialNumber = carCount;
} ~~~ ```

To resolve the repetition, code can be written as below using “this”. No need of calling with the constructor name. Simply call with this().

Car() {
        carCount++; // Static variable increment
        serialNumber = carCount;
        color = "Blue";
    }
// User defined constructor
Car(String color, String type){
    this(); // this exactly resolves the constructor call
    this.color = color;
    this.type = type;
} ~~~ ```

Above code can also be rewritten as below:

Car() {
        this("green", "coupe");
        color = "Blue";
    }
// User defined constructor
Car(String color, String type){
    this.color = color;
    this.type = type;
    carCount++;
    serialNumber = carCount;
} ~~~ ```
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is wrong in the below code?

Car() {
        carCount++; // Static variable increment
        serialNumber = carCount;
        color = "Blue";
    }

    // User defined constructor
    Car(String color, String type){
​ this.color = color;
        this.type = type;
        this(); 
    }
A

In chaining constructors, “this” constructor call should always be the first line.

Below is the corrected code.

Car() {
        carCount++; // Static variable increment
        serialNumber = carCount;
        color = "Blue";
    }

    // User defined constructor
    Car(String color, String type){
        this(); // always the first line
        this.color = color;
        this.type = type;
    }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the scope in Java?

A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Different levels of scope.

A

Note: It is also important to know that every method call gets its own frame on the stack. All the stacks share the same heap. And, when the method execution is completed the frame is popped out of the stack.

17
Q

How do we do garbage collection in Java?

A
18
Q

Is there an explicit way for us to do garbage collection in Java?

A
  • Sometimes, we can give suggestion to JVM to do garbage collection using below call:
system.gc();

But it is not guaranteed, JVM will do GC only if required.

  • Another way of doing GC is setting the object to null:
  • Example:
    ~~~
    Car myCar = new Car(); myCar = NULL;
    ~~~
19
Q

Provide an example of a scenario where Java memory leak can occur.

A
public class CourseExamples {
    static Car myCar;

    static void doSomething(Car car){
        myCar = car;
        System.out.println("The color of the car is: " + car.color);
    }
}

Here the local object ‘car’ will become out of scope after doSomething() method execution is completed, but car object is being referenced by static object ‘myCar’ and it is going to be referenced until the program is running and causes a memory leak as car is already out of scope but still being referenced. To resolve above issue below is the corrected code:

public class CourseExamples {
    static Car myCar;

    static void doSomething(Car car){
        myCar = car;
        System.out.println("The color of the car is: " + myCar.color);
        myCar = null; // de-references the object to prevent memory leak
    }
}