JAVA – Multiple Choice Questions and Answers

HOME

Java – Multiple Choice Questions and Answers – Method, Overloading, Overriding

HOME



class box 
    {
        int width;
        int height;
        int length;
        int volume;
        void volume(int height, int length, int width) 
        {
             volume = width*height*length;
        } 
    }    
    class Prameterized_method
    {
        public static void main(String args[])
        {
            box obj = new box();
            obj.height = 1;
            obj.length = 5;
            obj.width = 5;
            obj.volume(3,2,1);
            System.out.println(obj.volume);        
        } 
     }

 class equality 
    {
        int x;
        int y;
        boolean isequal()
        {
            return(x == y);  
        } 
    }    
    class Output 
    {
        public static void main(String args[])
        {
            equality obj = new equality();
            obj.x = 5;
            obj.y = 5;
            System.out.println(obj.isequal());
        } 
    }


 class overload 
    {
        int x;
 	int y;
        void add(int a) 
        {
            x =  a + 1;
        }
        void add(int a, int b)
        {
            x =  a + 2;
        }        
    }    
    class Overload_methods 
    {
        public static void main(String args[])
        {
            overload obj = new overload();   
            int a = 0;
            obj.add(6);
            System.out.println(obj.x);     
        }
   }

class overload 
    {
        int x;
 	    int y;
        
       void add(int a)
        {
            x =  a + 1;
        }
        void add(int a , int b)
        {
            x =  a + 2;
        }        
    }    
    class Overload_methods 
    {
        public static void main(String args[])
        {
            overload obj = new overload();   
            int a = 0;
            obj.add(6, 7);
            System.out.println(obj.x);     
        }
    }

class overload 
   {
        int x;
 	    double y;
        void add(int a , int b) 
        {
            x = a + b;
        }
        void add(double c , double d)
        {
            y = c + d;
        }
        overload() 
        {
            this.x = 0;
            this.y = 0;
        }        
    }    
    class Overload_methods 
    {
        public static void main(String args[])
        {
            overload obj = new overload();   
            int a = 2;
            double b = 3.2;
            obj.add(a, a);
            obj.add(b, b);
            System.out.println(obj.x + " " + obj.y);     
        }
   }



class area 
    {
        int width;
        int length;
        int volume;
        area() 
        {
           width=5;
           length=6;
        }
        void volume() 
        {
             volume = width*length*height;
        } 
    }    
    class cons_method 
    {
        public static void main(String args[])
        {
            area obj = new area();
            obj.volume();
            System.out.println(obj.volume);        
        } 
    }



 class test 
    {
        int a;
        int b;
        test(int i, int j) 
        {
            a = i;
            b = j;
        }
        void meth(test o) 
        {
            o.a *= 2;
            o.b /= 2;
        }          
    }    
    class Output 
    {
        public static void main(String args[])
        {
            test obj = new test(10 , 20);
            obj.meth(obj);
            System.out.println(obj.a + " " + obj.b);        
        } 
    }

class Output {
    public static int sum(int... x) {
        int total = 0; 
        for (int num : x) { 
            total += num;
        }
        return total;
    }

    public static void main(String args[]) {
        System.out.println(sum(10));             
        System.out.println(sum(10, 20));         
        System.out.println(sum(10, 20, 30));     
        System.out.println(sum(10, 20, 30, 40)); 
    }
}

a) only sum(10)
b) only sum(10,20)
c) only sum(10) & sum(10,20)
d) all of the mentioned


class Test
{
 public void m1 (int i,float f)
 {
  System.out.println(" int float method");
 }
 
 public void m1(float f,int i)
  {
  System.out.println("float int method");
  }
 
  public static void main(String[]args)
  {
    Test test =new Test();
       test.m1(20,20);
   }
}

class Test {
    void show(int a) {
        System.out.println("int method: " + a);
    }

    void show(double a) {
        System.out.println("double method: " + a);
    }

    public static void main(String[] args) {
        Test obj = new Test();
        obj.show(10);      // Line 1
        obj.show(10.5);    // Line 2
        obj.show('A');     // Line 3
    }
}




class Derived  
{ 
    public void getDetails() 
    { 
        System.out.printf("Derived class "); 
    } 
} 
  
public class Test extends Derived 
{ 
    public void getDetails() 
    { 
        System.out.printf("Test class "); 
        super.getDetails(); 
    } 
    public static void main(String[] args) 
    { 
        Derived obj = new Test(); 
        obj.getDetails(); 
    } 
}

import java.io.IOException;

class Derived {
    public void getDetails() throws IOException { // Line 4
        System.out.println("Derived class");
    }
}

public class Test extends Derived {
    public void getDetails() throws Exception { // Line 10
        System.out.println("Test class");
    }

    public static void main(String[] args) throws IOException { // Line 14
        Derived obj = new Test();
        obj.getDetails();
    }
}

class Derived 
{
    protected final void getDetails()
    {
        System.out.println("Derived class");
    }
}

public class Test extends Derived
{
    protected final void getDetails()
    {
        System.out.println("Test class");
    }
    public static void main(String[] args)
    {
        Derived obj = new Derived();
        obj.getDetails();
    }
}

public class Test
{
    public int getData(String temp) throws IOException
    {
        return 0;
    }
    public int getData(String temp) throws Exception
    {
        return 1;
    }
    public static void main(String[] args)
    {
        Test obj = new Test();
        System.out.println(obj.getData("Happy"));    
    }
}


Polymorphism in Java

HOME

In this tutorial, I’ll explain about Polymorphism in Java. It is one of the four concepts of OOPs. It is a concept where we can perform a single action in multiple ways. Poly means many and morphs means form. Polymorphism allows us to define one interface and have multiple implementations. An example of polymorphism is that there are different forms of communication like calls, SMS, picture messages, etc.

There are 2 types of polymorphism:-

  1. Method Overloading in Java – This is an example of compile time (or static polymorphism)
  2. Method Overriding in Java – This is an example of runtime time (or dynamic polymorphism)

Complie Time Polymorphism

It is also known as static polymorphism. Method Overloading is an example of static polymorphism. It is a feature that allows a class to have more than one method having the same name if their argument lists are different. Error if any occur, resolved during compile time.

Below is an example of static polymorphism.

public class Calculation {

	void sum(int a, int b) {
		System.out.println("Sum of 2 numbers :" + (a + b));
	}

	void sum(int x, int y, int z) {
		System.out.println("Sum of 3 numbers :" + (x + y + z));
	}

}
public class PolymorphismTest {

	public static void main(String[] args) {

		Calculation cal = new Calculation();
		cal.sum(10, 5);
		cal.sum(2, 6, 4);

	}
}

The output of the above program is

Dynamic Polymorphism

It is also known as Dynamic Method Dispatch. In this, the call to the overridden method happens at the runtime. This type of polymorphism is achieved by Method Overriding. Declaring a method in sub class that is already present in the parent class is known as method overriding. 

Below is an example of dynamic polymorphism

Parent Class

public class Bank {

	 //Overridden method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of parent class");
		System.out.println("Interest Rate of Bank :" + 0);

	}
}

Child 1 Class

public class BOI extends Bank {

    // Overriding method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of child 1 class");
		System.out.println("Interest Rate of BOI Bank :" + 4.1);

	}

}

Child 2 Class

public class BoFA extends Bank {

    // Overriding method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of child 2 class");
		System.out.println("Interest Rate of BofA Bank :" + 3.2);

	}

}

Child 3 Class

public class SBI extends Bank {

	// Overriding method
	public void getRateOfInterest() {

		System.out.println("getRateOfInterest() method of child 3 class");
		System.out.println("Interest Rate of SBI Bank :" + 5.3);

	}
}

Test Class

public class StaticPolTest {

	public static void main(String[] args) {

		Bank bank1 = new Bank();
		bank1.getRateOfInterest();

		BOI bank2 = new BOI();
		bank2.getRateOfInterest();

		BofA bank3 = new BofA();
		bank3.getRateOfInterest();

		SBI bank4 = new SBI();
		bank4.getRateOfInterest();
	}

}

The output of the above program is

Points to note for Method Overriding:-

  1. The argument list of the overriding method (method of subclass) must match the overridden method (the method of parent class). The data types of the arguments and their sequence should exactly match.
  2. The access Modifier of the overriding method (method of a subclass) cannot be more restrictive than the overridden method of the parent class. 

Suppose, I have changed the access modifier of SBI class from public to protected and then run the StaticPolTest program. In that case, I’ll get a compile-time error.

getRateOfInterest() method of parent class
Interest Rate of Bank :0
getRateOfInterest() method of child 1 class
Interest Rate of BOI Bank :4.1
getRateOfInterest() method of child 2 class
Interest Rate of BofA Bank :3.2
Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Cannot reduce the visibility of the inherited method from Bank

	at JavaDemo.Polymorphism.SBI.getRateOfInterest(SBI.java:6)
	at JavaDemo.Polymorphism.StaticPolTest.main(StaticPolTest.java:17)

Method Overloading in Java

HOME

public class MethodOverloading_Demo {

    public void Calculation(int a, float b) {
        System.out.println("Sum of 2 numbers :" + (a + b));
    }

    //Different type of parameters
    public void Calculation(float x, float y) {
        System.out.println("Sum of 2 numbers :" + (x + y));
    }

    //Different number of parameters
    public void Calculation(int i, int j, int k) {
        System.out.println("Sum of 3 numbers :" + (i + j + k));
    }

    //Different sequence of parameters
    public void Calculation(float p, int r) {
        System.out.println("Sum of 3 numbers :" + (p + r));
    }

    public static void main(String[] args) {

        MethodOverloading_Demo add = new MethodOverloading_Demo();

        //Call overloaded methods
        add.Calculation(5, 12f);
        add.Calculation(13f, 12.0f);
        add.Calculation(22, 33, 50);
        add.Calculation(11f, 10);
    }

}

What is Type Promotion?

When a data type of smaller type, promote to bigger type, it called type promotion.  Suppose a method has double data type and object provides float, then the program works fine. Float will be promote to double.

Let us explain this with an example. In the below example, object has provided float data type, but method has double data type, so there is type promotion.

public class Addition {

    public void Calculation(int a, int b)  {
        System.out.println("Sum of 2 numbers :"+(a+b));
    }

    public void Calculation(int x, double y)   {
        System.out.println("Sum of 2 numbers :"+(x+y));
    }

    public static void main(String[] args) {
        Addition add = new Addition();
        //Type Promotion method
        add.Calculation(5,12);
        add.Calculation(13,12f);
    }
}

Methods in Java

HOME

modifier returnType nameOfMethod (Parameter List) {
   // method body  }

Here,

  • modifier − It defines the access type of the method like public, protected, default, private
  • returnType − Method may return a value or not. Void does not return any value.
  • nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.
  • Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.
  • method body − The method body defines what the method does with the statements.
public static int methodName(int a, int b) {
      // body
   }

public class Method_Example {

    public static void main(String[] args) {

        //Standard Library Method
        System.out.println("Square root of 9 is : " + Math.sqrt(9));

        //User defined Method
        MyMethod();
    }

    public static void MyMethod()
    {
        System.out.println("My User defined Method");
    }
}

Java Methods with Arguments and Return Value

A Java method can have zero or more parameters, and they may return a value.

public class Min_Method {

    public static void main(String[] args) {
        int a = 10;
        int b = 5;
        int c = minMethod(a,b);
                System.out.println("Minimum value is :" + c);
    }

    //Define function min_function
    public static int minMethod(int x, int y)
    {
        int min;
        if (x>y)
            min =y;
        else
            min = x;
        //return value
        return min;
    }
}

Void Keyword

The void keyword allows us to create methods that do not return a value. When a method’s return type is void, it means that the method performs some operation or task but does not produce any result that needs to be returned to the caller.

public class Min_Method {

    public static void main(String[] args) {

        int a = 10;
        int b = 5;

        //Call function
        minMethod(a,b);
    }

    //Define function min_function
    public static void minMethod(int x, int y)
    {
        int min;
        if(x>y)
            min =y;
        else
            min = x;
        System.out.println("Minimum value is :" + min);
    }
}

Method Overloading

When a class has two or more methods by the same name but different parameters, it known as method overloading. To know more about method overloading, click here.

public class Overloading_Example {
    
        public static void main(String[] args) {

            int a= 10;
            int b = 24;
            double c = 12.0;
            double d = 13.0;
            min_function(a, b);
            min_function(c,d);
        }

        public static void min_function(int x, int y)
        {
            int min;
            if(x>y)
                min = y;
            else
                min = x;

            System.out.println("Minimum value for integer is :"+ min);
        }

        public static void min_function(double m, double n)
        {
            double min;
            if(m>n)
                min=n;
            else
                min=m;
            System.out.println("Minimum value for integer is :"+ min);
        }
    }

What is main method in Java?

The main()method is the entry point into the application. The signature of the method is always: public static void main(String[] args).