Java – Multiple Choice Questions and Answers – Exception Handling

HOME



public class QAAutomation {
    
     public static void main(String[] args) {
        try {
            System.out.println("Inside try");
            throw new RuntimeException("Error");
        } finally {
            System.out.println("Inside finally");
        }
    }
}

 public class QAAutomation {
    
    static void method() throws Exception {
        throw new Exception("Error occurred");
    }

    public static void main(String[] args) {
        method();
    }
}


 class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new CustomException("Custom error occurred");
        } catch (CustomException e) {
            System.out.println(e.getMessage());
        }
    }
}

public class Test {
    
    public static void main(String args[]) {
        try {
            int a, b;
            b = 0;
            a = 5 / b;
            System.out.print("A");
        } catch (ArithmeticException e) {
            System.out.print("B");
        } finally {
            System.out.print("C");
        }
    }
}

public class Test {
    public static void main(String args[])
    {
        try
        {
            int i, sum;
            sum = 10;
            for (i = -1; i < 3 ;++i)
                sum = (sum / i);
        }
        catch(ArithmeticException e)
        {
            System.out.print("0");
        }
        System.out.print(sum);
    }
}



public class Test{
    public static void main(String[] args) {
        try {
            System.exit(0);
        } finally {
            System.out.println("Finally executed");
        }
    }
}



  public class Test {
         public static void main(String[] args) {
             String str = null;
             try {
                 System.out.println(str.length());
             } catch (NullPointerException e) {
                 System.out.println("Caught a NullPointerException");
             }
         }
     }

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class Test {
    public static void readFile() throws IOException {
        File file = new File("example.txt");
        FileReader reader = new FileReader(file);
        reader.close();
    }

    public static void main(String[] args) {
        try {
            readFile();
        } catch (IOException e) {
            System.out.println("IOException handled");
        }
    }
}


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

        try {
            int[] numbers = {1, 2, 3};
            System.out.println(numbers[3]);
            int division = 10 / 0;
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index is out of bounds");
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } finally {
            System.out.println("Finally block executed");
        }
        System.out.println("Rest of the program");
    }
}

public class Test {
    public static void main(String args[])
    {
        try
        {
            System.out.print("Hello" + " " + 1 / 0);
        }
        catch(ArithmeticException e)
        {
            System.out.print("World");
        }
    }
}




public class Test {

    public static void main(String[] args) {
        try {
            throw new Exception("First Exception");
        } catch (Exception e) {
            try {
                throw new Exception("Second Exception");
            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new Error("Fatal error");
        } catch (Exception e) {
            System.out.println("Exception");
        } catch (Error e) {
            System.out.println("Error");
        }
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            int[] array = new int[5];
            System.out.println(array[5]);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException");
        } finally {
            System.out.println("Finally block executed.");
        }
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new NullPointerException();
        } catch (RuntimeException e) {
            System.out.println("RuntimeException");
        } catch (Exception e) {
            System.out.println("Exception");
        }
    }
}


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"));    
    }
}


Class and Object in Java

HOME

Let us consider the Phone as the object. The state of the Phone is coloured grey, and black, and types like IPhone, Samsung, and behaviour is calling, sending messages, and internet browsing.

public class Student {
          String Name;
}

How to create an Object?

To create an object, specify a class name like Student, an object name like stud, and use a new keyword. 

Student stud = new Student();

Let us create a class and an object of its class and print the value of the variable name.

public class Student {

    String Name = "Tom";
    public static void main(String[] args)

    {
        Student stud = new Student();
        System.out.println("Name of Student :"+stud.Name);
    }
}

Multiple Objects of a Class

We can create multiple objects of a class. In the below example, we have created 2 objects of class Student.

public class Student {

    String Name = "Tom";
    public static void main(String[] args)
    {
        Student stud1 = new Student();
        Student stud2 = new Student();
        System.out.println("Name of Student :"+stud1.Name);
        System.out.println("Name of Student :"+stud2.Name);
    }
}

Multiple Classes

We can create a class and then create an object of that class in another class. Like, here, we have created a class called Student.java and another class is Student_Demo.java where we will create the object of class Student. This is a better approach than the previous one.

public class Student {
          String Name = "Tom";         
}


public class Student_Test{
    public static void main(String[] args)
    {
        Student stud = new Student();
        System.out.println("Name of Student :"+stud.Name);
    }
}

There are multiple ways to initialize the classes and objects.

1) Initialize through reference

Here, initializing an object means storing data in the object. Let’s see a simple example where we are going to initialize the object through a reference variable.

public class Student {
          String Name ;
          int Age;
}

public class Student_Test {
    public static void main(String[] args)
    {
        Student stud = new Student();
        stud.Name ="Tom";
        stud.Age=35;
        System.out.println("Name of Student :"+stud.Name);
        System.out.println("Age of Student :"+stud.Age);
    }
}

2) Initializing through method

We are creating the two objects of the Student class and initializing the value to these objects by invoking the InsertData() method. Here, we are displaying the state (data) of the objects by invoking the DisplayData() method.

public class Student {
	String Name;
	int Age;

	void InsertData(String n, int a) {
		Name = n;
		Age = a;
	}

	void DisplayData() {
		System.out.println("Name of Student :" + Name);
		System.out.println("Age of Student :" + Age);
	}
}


public class Student_Test {
    
    public static void main(String[] args) {
        Student stud = new Student();
        stud.InsertData("Tom", 34);
        stud.DisplayData();
    }
}

We can create multiple objects

public class Student {
          String Name ;
          int Age;

          void InsertData(String n, int a)
          {
                   Name =n;
                   Age = a;
          }

          void DisplayData()
          {
                   System.out.println("Name of Student :"+Name);
                   System.out.println("Age of Student :"+Age);
          }
    }  


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

            Student stud1 = new Student();
            Student stud2 = new Student();
            stud1.InsertData("Matt",43);
            stud1.DisplayData();
            stud2.InsertData("Terry",36);
            stud2.DisplayData();
    }
 }

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);
    }
}

Constructors in Java

 
 

A constructor initializes an object when it creates. It has the same name as its class and is syntactically similar to a method. However, constructors have no explicit return type.

Every time an object is created using the new() keyword, at least one constructor is called.

ConstructorDemo demo = new ConstructorDemo();

It calls a default constructor if there is no constructor available in the class. In such case, Java compiler provides a default constructor by default. Let me explain constructor with the help of a simple program. Here I have created a class ConstructorDemo, created its constructor and then create the object demo which will in turn will call the constructor too.

//Create a Class ConstructorDemo 
public class ConstructorDemo   
{ 
   int x;
 //Create a Constructor for class ConstructorDemo 
   ConstructorDemo()
   {
                   x=24;
   }
         public static void main(String[] args) {
            
                //Create an object of class Constructor and will call the constructor
                 ConstructorDemo demo = new ConstructorDemo();
                  System.out.println("Value of x: "+demo.x);
      }
} 

Output
Value of x:24

Things to remember for a Constructor:-

  • Constructor name must be the same as its class name
  • A Constructor must have no explicit return type
  • A Java constructor cannot be abstract, static, final, and synchronized

There are two types of constructors in Java: no-arg constructor, and parameterized constructor.

No Argument Constructor – Here, constructor does not have any argument.

public class DefaultConstructorStudent {
    String Name;
     DefaultConstructorStudent()
    {
            System.out.println("Display details of Student");
       }
      public static voidmain(String[] args) {
           DefaultConstructorStudent stud = newDefaultConstructorStudent();
     }
}

Output
Display details of Student

Parameterized Constructor – A constructor that has a specific number of parameters called a parameterized constructor.

In this example, I have a parameterized constructor with two parameters Name and RollNo. While creating the objects stud1 and stud2, I have passed two arguments so that this constructor gets invoked after creation of stud1 and stud2.

public class ParameterizedStudent {
    String Name;
    int RollNo;
ParameterizedStudent(String New_Name,int New_RollNo)

     {
          Name = New_Name;
          RollNo = New_RollNo;
     }
 
   void DisplayInformation()
   {
        System.out.println("Name: "+Name+", "+"Roll_No: "+RollNo);
   }
        public staticvoid main(String[] args) {
 
            ParameterizedStudent stud1 = newParameterizedStudent("TOM",001);
            ParameterizedStudent stud2 = newParameterizedStudent("MIKE",002);
            stud1.DisplayInformation();
            stud2.DisplayInformation();              
       }
}
 
Output 
Name: TOM, Roll_No: 1
Name: MIKE, Roll_No: 2

Constructor Overloading – This is same as method overloading. Here will have more than one constructor with different parameter lists. Constructors overloaded if they have either different number or parameters, different data type of parameters or different sequence of parameters.

public class ConstructorOverloading {
      String Name;  
      int RollNo;
      int Age;

      //Constructor 1 
      ConstructorOverloading(String New_Name, int New_RollNo, int New_Age)
      {
          Name  = New_Name;
          RollNo = New_RollNo;
          Age = New_Age;
      }

      //Constructor 2
       ConstructorOverloading(int R, int A)
       { 
           RollNo = R;
           Age = A;              
       }

      //Constructor 3 
       ConstructorOverloading(String SName, int SRollNo)
       {
           Name = SName;
           RollNo =SRollNo;
       }
       voidDisplayInformation()
       {
            System.out.println("Name: "+Name+", "+"Roll_No: "+RollNo+","+"Age: "+Age);
       }

      public static void main(String[] args) {
        ConstructorOverloading stud1 = newConstructorOverloading("TOM",001, 20);
        ConstructorOverloading stud2 = newConstructorOverloading(002,21);
        ConstructorOverloading stud3 = newConstructorOverloading("MIKE",003);
        stud1.DisplayInformation();
        stud2.DisplayInformation();
        stud3.DisplayInformation();
     }
}

Output
Name: TOM, Roll_No: 1,Age: 20
Name: null, Roll_No: 2,Age: 21
Name: MIKE, Roll_No: 3,Age: 0

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).