You are on page 1of 3

Q1

public class Car {


private String vehicleNumber;
private String color;
private static int numberOfCars = 0;

public Car(String vehicleNumber, String color) {


this.vehicleNumber = vehicleNumber;
this.color = color;
}

public void display(String name) {


System.out.println("Owner's name: " + name);
System.out.println("Vehicle number: " + vehicleNumber);
System.out.println("Color: " + color);
}
}
Solution
Static variable : int numberOfCars :1
Instance Variable : 2
Local variable : String name : 3

Q2
Which of the following is/are correct?

Static members can only be accessed by static methods.


Non-static members can be accessed by static methods.
Static blocks get executed only once. <<<<--------True
Static variables and methods can be accessed without creating an object of the
class. <<<<-------True

Q3
class Person {
private String name;
private static int age;
static {
name = "john"; // line 1
}

Person() {
age = 20; // line 2
}

public int getAge() {


return age; // line 3
}
}

public class Account {


public static void main(String[] args) {
System.out.println(new Person().getAge());
}
}
Solution: "name" is a non static but in line 1 we are trying to access in static,
so it is a compilation error
Q4
class Computer {
private static int id;
private static int counter = 0;

public Computer() {
id = ++counter;
}

public int getId() {


return id;
}

// Rest of the methods


}

public class Tester {


public static void main(String[] args) {
Computer comp1 = new Computer();
Computer comp2 = new Computer();
Computer comp3 = new Computer();
System.out.println(comp1.getId() + " " + comp2.getId() + " "
+ comp3.getId());
}
}
Solution: "Id" is static so answer 3 3 3, if "Id" is not static then answer 1 2 3

Q5
class Printer {
static {
System.out.println("Static block in Printer class");
}

public static void display(String message) {


System.out.println(message);
}
}

public class Tester {


public static int sampleVariable = 1;

static {
System.out.println("Static block in Tester class");
}

public static void main(String[] args) {


sampleVariable++;
Printer p = null;
System.out.println("In main");
p.display("The value of sample variable is: " + sampleVariable);
}
}
Solution : C
first static block gets executed
second "In main" will get executed
Third it will go to display, but "p.display" is not correct way to call, it should
be "printer.display"

Q6
public class Tester {
public int var;

Tester(int var) {
System.out.println(this.var);
}

public static void main(String args[]) {


Tester tester = new Tester(20);
System.out.println(this.var);
}
}
Solution : compilation error, "this" keyword cannot be used in main method because
main method is static.

You might also like