Java Classes Questions

1. What are the different access specifiers in Java?

4 Access specifiers in Java are
1) public, - these class/methods/variables can be accessed by any class or method.

2)private - class, methods, or variables defined as private can be accessed within the class only.

3) protected - these can be accessed by the classes of the same package, or by the sub-class of this class in other packages also.

4) default - members are accessible by classes within the package only. Note that there is no "default" specifier. If no specifier is given, the class will have default access specifier.

2. What is the output of the following program?

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

Hello world

3. What is an object?




Object is an entity which has a state and behavior.
< br>Object is an instance of a class. Object has fields and methods.

Whenever the JVM reads the “new()” keyword, it will create an instance of that class.

e.g.



class A{
int n;
void print(){
System.out.println(n);
}
}

class Demo{
public static void main(String args[]){
A obj = new A();
}
}

Here we are creating an object called obj which has an integer data member n.

4. What is a constructor?


	
	

Constructor is a special method in a class which is used to initialize the object. It is implicitly invoked when an object is created.

Name of the constructor must be same as class name. And constructor must not have an explicit return type.

e.g.

		
class A{
A(){}//default constructor
A(int n){}//constructor
}
Here A class has two constructors. First one with no parameters is a default constructor.

5. Can a constructor be final? Is the constructor inherited?


			

No. The constructor can not be final.
It can't be inherited.

6. Write a class with a 2 parameter constructor and a default constructor.

public class Test {
  Test(int a,int b){
    System.out.println("I am a constructor with "+a+b);
 }
 Test( ){//default constructor
     System.out.println("I am default constructor ");
 }
 public static void main(String args[]) {
      Test c1 = new Test(10,20);
      Test c2 = new Test();
  }
}

The class has two constructors - one default and another with 2 parameters.

The main() function first calls parameterized constructor by instantiating the class with 2 integers. Then it calls default constructor by instantiating the class with 0 values.

The output of the program is
I am a constructor with 1020
I am default constructor

7. What is the output of the following program?

   class Test   
    {  
        int i;   
    
        public static void main (String args[])   
        {  
            Test test = new Test();   
            System.out.println(test.i);  
        }  
    }  

0.0

Instance variable are initialized to 0 automatically. So the output is 0.

8. What is the output of the following program?

public class Test {	 
        int i;   
        Test(int n){
        	System.out.println("Hello world");
        }
    
        public static void main (String args[])   
        {  
            Test test = new Test();   
            System.out.println(test.i);  
        }   

}

Compiler error

The class has only a parameterized constructor. It has no default constructor.

The class instantiation with default constructor gives an error.

9. What is a class?

A class is a blue print of an object.

A class is a user defined data type similar to structures. A class has data members and methods. Data members define the state of the object and methods define behavior of the object.

e.g.
class Test
{
int num;
void printNum(){
.....
}
}

Here class Test has an instance variable called num. It also has a method printNum()

10. What is the keyword "final" used for?


	

final keyword can be used in different contexts.

A final variable is the one which can not be modified. Its value is set either using an initializer or using an assignment statement. Once assigned, its value can not be changed.

e.g.

final int m=10;
Now m can not be changed. Changing m results in syntax error.

A final object can not change its reference. its fields can change. But it can not refer to another object.
final A obj = new A();
obj.m=10;//ok
obj = new A();//error
A final method can not be overridden. The derived classes can not re-define a final method.
e.g.
class A{
final void print(){}
}
class B extends A{
final void print(){//error
}
}

A final class can not be inherited - it can not be subclassed.
final class A{}
class B extends A{}//error

11. What is static keyword?

A static variable of a class is common to all objects of the class unlike an instance variable.
e.g.

class A{
static int m;
}

Now m is shared between all objects of the class A.

A static method of a class can be invoked without using object of a class. And a static method can access only static variables of a class and it can call only static methods of that class.

e.g.
class A{
static int m;
int n;
static void printHello(){
System.out.println("Hello world");
System.out.println("m is "+m);
System.out.println("n is "+n);//error
}
}
class Test{
public static void main(String args[]){
A.printHello();//no error
}
}

As printHello() is a static method, we can call this method without creating any object of A class.

And this method is not able to access the instance variable n.

12. Can a class be defined as a static class?


		

A top level class can not be static.

But an inner class - a nested class can be static in Java.

e.g.

  class A{
static class B{}
}

Here B is the static inner class of class A. Which means B can be created without an outer class object.

13. What is static block in Java?


	
	

Java static block or static initializer block is the group of statements that gets executed when the class is loaded by Java class loader. So a static block is executed even before main method. Static block is used to initialize static variables of the class.

A class can have multiple static blocks which are executed in the same order they are defined in the class.

e.g.

   class A{
static int m;
int n;
static{
m = 1;
}
A(int num){
n = num;
}
}
Here the block static { m = 1;} is the static initializer block.

Unlike the constructor, this block gets executed only once.

14. What is constructor overloading in Java?

Defining multiple constructors is called constructor overloading.

e.g.

public class Test
{
Test(int n){
...
}
Test(){
...
}
public static void main(String arg[]){
Test t1 = new Test(10);
Test t2 = new Test();
....
}
}
Here Test class has two constructors Test(int n), Test().
t1 calls first constructor as it is initialized with one integer argument. t2 calls second constructor - zero parameter constructor also called default constructor.

15. Write a class A which has a constructor with one int parameter. Write class B which is a subclass of A with a default constructor.


class A
{
   public A(int num)
   {
      n = num;
      System.out.println("A constructor");
   }
   int n;
}
class B extends A
{
    public B()
   {
     super(0);
     System.out.println("B constructor");
   }
}
public class Test
{
   public static void main(String a[])
  {
    B obj = new B();
    A obj2 = new A(10);
  }
}

If we omit the line super(0) in B class constructor, we get a syntax error. Because implicitly a subclass constructor must call the super class constructor. In this case, it tries to implicityly call default constructor of super class A. As A class does not have a default constructor, there will be error.

By adding the line super(0), we are calling base class constructor - A(int num) with 0 as parameter.

The super() call if present, must be the first statement in derived class constructor.

16. Write a program to read names and times taken by n runners and find the fastest runner.

import java.util.Scanner;
class Runner{
     String name;
     int runTime;
     Runner(String n, int t){
         name = n;
         runTime = t;
     }
     int getTime(){
         return runTime;
     }
     String getName(){
         return name;
     }
}
class Demo{
     public static void main(String args[]){
            int n;
            System.out.println("Number of runners ");
            Scanner scanner = new Scanner(System.in);
            n = scanner.nextInt();
            Runner arr[] = new Runner[n];
            for(int i=0;i<n;i++)
            {
                System.out.println("Name and time taken");
                String name = scanner.next();
                int time = scanner.nextInt();
                arr[i] = new Runner(name,time);
            }
            int fastest = 0;
            for(int i=1;i<n;i++){
                 int time = arr[i].getTime();
                 if(time<arr[fastest].getTime()) 
                        fastest = i;
            }
            System.out.println("the fastest runner is "+arr[fastest].getName());      }
}

We are using a class Runner with 2 fields- name and time taken. Next we create an array of Runner objects.

Find the smallest element in the array. And then find the corresponding Name.

We could even use a comparator or comparable interfaces.

17. Explain static methods with an example.

A static method can be accessed without creating an object of the class. But a static method can not access instance variables, it can only access static variable and only call other static methods.

class AB{
int m;
static int sm;
static void printNum(int n){
System.out.println("n is "+n);
// System.out.println("m is"+m);//error
System.out.println("sm is "+sm);//no error
}
}

class Demo{
public static void main(String args[]){
int a = 10;
AB.printNum(a);
}
}

As the method printNum is a static method, we are calling it directly without creating any object of AB class.

Also note that main method of the program will be static, because the JVM will be able to call it directly,

18. What is the output of the program?

class Const
{
    private Const(){
        System.out.println("Constructor");
   }
   private Const(int n)
  {
     System.out.println("Constructor and n is"+n);
  }
  public static void main(String args[]){
      Const obj = new Const(10);
  }
}

The output is Constructor and n is 10.

Though the constructor is private, it is accessible from methods of the same class. So there will not be any errors

19. What is finalize method?

finalize method is a deprected method used to clean up resoures used by an object before the object is garbage collected.

You can define finalize method in a class. But as we are not certain when the object will be garbage collected, this method is deprecated since Java 9.

class A{
void finalize(){
//* close files*/
/* release other resources*/
}
}

20. What is overloading of functions? Explain with the help of an example.

Overloading is the process where two functions will have same name but different number of parameters or different types of parameters.

During compilation, the compiler will select the correct method based on the parameters passed to method.

e.g.
int sumNumbers(int n1,int n2)
{
return n1+n2;
}
float sumNumbers(int n1,float n2,int n3)
{
return n1+n2+n3;
}

Now if we call the method as

int s = sumNumbers(10,20)
first method will be called.

And if we call it as
int s2 = sumNumbers(10,1.4,88)
second method will be called.

21. Can a constructor of a class be private? Write an example.

Constructor can be private. If a class has a private constructor, then it can only be called by the same class, not by other classes.
 
class Const
{
    private Const(){
        System.out.println("Constructor");
   }
   private Const(int n)
  {
     System.out.println("Constructor and n is"+n);
  }
}
class Test{

  public static void main(String args[]){
      Const obj = new Const(10);
  }
}

When we compile the above program, we get an error while creating obj in main() funciton.

$javac Const.java
Const.java:14: error: Const(int) has private access in Const
      Const obj = new Const(10);
                  ^
1 error

Const obj = new Const(10) calls the one parameter constructor of the Cost class. But main() function is in a separate class and it does not have access to constructor of Const class. So we get an error. 

We can have a static method in such a class which will create an object and return that object. 

22. What are the differences between default and protected access specifiers.

If no access specifier is used, the default access is used - which is package private. That is - the fields are accessible from within the same package.

class A
{
int m;//default access
}

Protected access specifier makes the fields accessible only from the same class and its derived classes.

class A{
protected int m;
}
class B extends B{
void printM(){
System.out.println(m+"");//no error
}
}
class Demo{
public static void main(String args[]){
A obj = new A();
A.m=10;//error
}
}

m here is protected variable and accessible by class B. But not by Demo class.

23. Does Java have destructors for class? Why?

Java does not have destructors.

As Java has automatic garbage collection, we can not predict when exactly an object will be destroyed.

But there is an equivalent method to destructor called finalize which is called before an object is garbage collected. This method is deprecated. It is advisable that classes write a close method to clean up and explicitly call such a method.

24. With an example, explain inner class in Java

A class which is defined inside another class is called Inner class. This inner class can access all the members of the outer class. Inner class object must be created as a part of outer class.

e.g.

class LinkedList{
class Node{
int num;
Node next;
}
Node head;
void append();
}

Here the class Node is an inner class of LinkedList class.

25. Write a class named Rectangle with width and height and with these methods: A no-arg constructor that creates a default rectangle. A constructor that creates a rectangle with the specified width and height. A method named getArea() that returns the area of this rectangle. A method named getPerimeter() that returns the perimeter.

public class Rectangle{
    int len,wid;
    Rectangle(int l,int w){
        len = l;
        wid = w;
    }
    Rectangle(){
        len=wid=1;
    }
    int getPerimeter(){
        return 2*(len+wid);
    }
    int getArea(){
        return len*wid;
    }
    public static void main(String args[]){
        Rectangle r1 = new Rectangle(10,20);
        System.out.println("Area is "+r1.getArea());
        System.out.println("Perimeter is "+r1.getPerimeter());
    }
}

26. What are wrapper classes and auto-boxing?

Wrapper classes are 8 classes corresponding to 8 primitive data types which are object forms of these types.

e.g. an int variable can be converted to an Integer object and a float can be converted to Float object.

Some classes like collections can be formed only with objects as members. In such cases you can wrap primitive types in these wrapper classes.

The automatic conversion of primitive types to their wrapper class objects is called autoboxing.

e.g.
Integer obj = 3;//autoboxing

Unboxing is the opposite process - converting wrapper objects to primitive types.

Integer i1 = 12;
int m1 = i1;//unboxing

27. Can you define a class within another class in Java? Can you define a method within another method?

We can define a class within another class. These inner classes can be static or non-static. We can even define a class within a method - these are called local classes.

But we can define a method within a method. But we can define a lambda within a method which is almost like a method.

28. What are the errors if any, in the program given.

boolean isPalindrome(String s) {
    int i = 0, j = s.length() - 1;
    while (i != j && s.charAt(i) == s.charAt(j)) {
           i++;
           j--;
     }
     return (i == j);
}

This code does not work for strings with even number of characters. If there are even characters i will never be equal to j and at some point our index goes beyond the length of string and program will crash.

The correct condition should be

while (i < j && s.charAt(i) == s.charAt(j))

29. Can you call one constructor from constructor of the same class?

Yes, it is possible to call one constructor from another constructor of the same class using keyword "this" with required parameters.

But if this() call is used, it must be first statement of the constructor.

e.g.
class A{
int num;
A(){
num = 0;
System.out.println("default constructor");
}
A(int m){
this();
num = m;
System.out.println("parameterized constructor");
}
}
class Demo{
public static void main(String args[]){
A obj = new A(10);
}
}

Now if we make a change and move the call to constructor to end of second construtor, the program does not compile.

A(int m){
num = m;
System.out.println("parameterized constructor");
this();//gives error
}

30. A class has one string field - name. Write a code to sort the objects of this class based on last names. class Student { String name; }

 class Name implements Comparable<Name> {
   String name;
   Name(String name){
 	 this.name = name;
  }
    public	int compareTo(Name s){
       String arr[] = s.name.split(" ");
       String myArr[] = name.split(" ");
       if(arr.length<2 || myArr.length<2)
 	  return 0;
       return myArr[1].compareTo(arr[1]);
 		
    }
 
 }
 class Demo{
      public static void main(String args[]){
            Name obj1 = new Name("Usha Ratnakar");
            Name obj2 = new Name("Asha Stuvwy");
            if(obj1.compareTo(obj2)>0){
                System.out.println("obj1 is larger");
             }else
                 System.out.println("obj2 is larger");
         }
 }

31. How do you access overridden method of a superclass? Can you similarly access overridden method of a super-super class?


	

An overridden super class method can be called by using the keyword super followed by dot operator and the method name,

e.g.
super.print(10);

Similarly you can use super.super.method() to invoke super super class method.

class B1
{
public void print(int num)
{
System.out.println("Printing the number "+num);
}
}
class D1 extends B1
{
public void print(int num)
{
super.print(num);

System.out.println("Printing the square of the number "+(num*num));
}
}

Here D1 print() method is calling super class print() method by using super.print(num)

32. What are class/instance and local variables?


Local variables − Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed.

Instance variables − Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.

Class variables − Class variables are variables declared within a class, outside any method, with the static keyword.

33. When is the constructor of a class invoked in Java?

A constructor is invoked whenever an object is being created using new operator.

If there are multiple constructor, the constructor being called depends on the arguments we send to new statement.

A obj = new A(10);

new A(10) calls one int parameter constructor of A class.