250+ TOP MCQs on Introduction To Methods and Answers

Java MCQs on Methods of Java Programming Language.

1. What is the return type of a method that does not return any value?
a) int
b) float
c) void
d) double

Answer: c
Clarification: Return type of a method must be made void if it is not returning any value.

2. What is the process of defining more than one method in a class differentiated by method signature?
a) Function overriding
b) Function overloading
c) Function doubling
d) None of the mentioned

Answer: b
Clarification: Function overloading is a process of defining more than one method in a class with same name differentiated by function signature i:e return type or parameters type and number. Example – int volume(int length, int width) & int volume(int length , int width , int height) can be used to calculate volume.

3. Which of the following is a method having same name as that of it’s class?
a) finalize
b) delete
c) class
d) constructor

Answer: d
Clarification: A constructor is a method that initializes an object immediately upon creation. It has the same name as that of class in which it resides.

4. Which method can be defined only once in a program?
a) main method
b) finalize method
c) static method
d) private method

Answer: a
Clarification: main() method can be defined only once in a program. Program execution begins from the main() method by java runtime system.

5. Which of this statement is incorrect?
a) All object of a class are allotted memory for the all the variables defined in the class
b) If a function is defined public it can be accessed by object of other class by inheritation
c) main() method must be made public
d) All object of a class are allotted memory for the methods defined in the class

Answer: d
Clarification: All object of class share a single copy of methods defined in a class, Methods are allotted memory only once. All the objects of the class have access to methods of that class are allotted memory only for the variables not for the methods.

6. What will be the output of the following Java program?

  1.     class box 
  2.     {
  3.         int width;
  4.         int height;
  5.         int length;
  6.         int volume;
  7.         void volume(int height, int length, int width) 
  8.         {
  9.              volume = width*height*length;
  10.         } 
  11.     }    
  12.     class Prameterized_method
  13.     {
  14.         public static void main(String args[])
  15.         {
  16.             box obj = new box();
  17.             obj.height = 1;
  18.             obj.length = 5;
  19.             obj.width = 5;
  20.             obj.volume(3,2,1);
  21.             System.out.println(obj.volume);        
  22.         } 
  23.      }

a) 0
b) 1
c) 6
d) 25

Answer: c
Clarification: None.
output:

$ Prameterized_method.java
$ Prameterized_method
6

7. What will be the output of the following Java program?

  1.     class equality 
  2.     {
  3.         int x;
  4.         int y;
  5.         boolean isequal()
  6.         {
  7.             return(x == y);  
  8.         } 
  9.     }    
  10.     class Output 
  11.     {
  12.         public static void main(String args[])
  13.         {
  14.             equality obj = new equality();
  15.             obj.x = 5;
  16.             obj.y = 5;
  17.             System.out.println(obj.isequal());
  18.         } 
  19.     }

a) false
b) true
c) 0
d) 1

Answer: b
Clarification: None.
output:

$ javac Output.java
$ java Output 
true

8. What will be the output of the following Java program?

  1.     class box 
  2.     {
  3.         int width;
  4.         int height;
  5.         int length;
  6.         int volume;
  7.         void volume() 
  8.         {
  9.              volume = width*height*length;
  10.         } 
  11.     }    
  12.     class Output 
  13.     { 
  14.         public static void main(String args[])
  15.         {
  16.             box obj = new box();
  17.             obj.height = 1;
  18.             obj.length = 5;
  19.             obj.width = 5;
  20.             obj.volume();
  21.             System.out.println(obj.volume);        
  22.         } 
  23.     }

a) 0
b) 1
c) 25
d) 26

Answer: c
Clarification: None.
output:

$ javac Output.java
$ java Output
25

9. In the following Java code, which call to sum() method is appropriate?

  1. class Output 
  2. {
  3.  
  4.         public static int sum(int ...x)
  5.         {
  6.              return; 
  7.         }
  8.         static void main(String args[]) 
  9.         {    
  10.              sum(10);
  11.              sum(10,20);
  12.              sum(10,20,30);
  13.              sum(10,20,30,40);
  14.         } 
  15. }

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

Answer: d
Clarification: sum is a variable argument method and hence it can take any number as an argument.

10. What will be the output of the following Java program?

  1.     class area 
  2.     {
  3.         int width;
  4.         int length;
  5.         int volume;
  6.         area() 
  7.         {
  8.            width=5;
  9.            length=6;
  10.         }
  11.         void volume() 
  12.         {
  13.              volume = width*length*height;
  14.         } 
  15.     }    
  16.     class cons_method 
  17.     {
  18.         public static void main(String args[])
  19.         {
  20.             area obj = new area();
  21.             obj.volume();
  22.             System.out.println(obj.volume);        
  23.         } 
  24.     }

a) 0
b) 1
c) 30
d) error

Answer: d
Clarification: Variable height is not defined.
output:

$ javac cons_method.java
$ java cons_method
error: cannot find symbol height

250+ TOP MCQs on Inheritance – 1 and Answers

Java MCQs on Inheritance of Java Programming Language.

1. Which of this keyword must be used to inherit a class?
a) super
b) this
c) extent
d) extends

Answer: d
Clarification: None.

2. A class member declared protected becomes a member of subclass of which type?
a) public member
b) private member
c) protected member
d) static member

Answer: b
Clarification: A class member declared protected becomes a private member of subclass.

3. Which of these is correct way of inheriting class A by class B?
a) class B + class A {}
b) class B inherits class A {}
c) class B extends A {}
d) class B extends class A {}

Answer: c
Clarification: None.

4. Which two classes use the Shape class correctly?

A. public class Circle implements Shape 
   {
    private int radius;
   }
B. public abstract class Circle extends Shape 
   {
    private int radius;
   }
C. public class Circle extends Shape 
   {
   private int radius;
   public void draw();
   }
D. public abstract class Circle implements Shape 
   {
    private int radius;
    public void draw();
   }
E. public class Circle extends Shape 
   {
    private int radius;
    public void draw()
    {
     /* code here */
    }
   }
F. public abstract class Circle implements Shape 
   {
     private int radius;
     public void draw() 
     { 
      /* code here */ 
     }
   }

a) B,E
b) A,C
c) C,E
d) T,H

Answer: a
Clarification: If one is extending any class, then they should use extends keyword not implements.

5. What will be the output of the following Java program?

  1.     class A 
  2.     {
  3.         int i;
  4.         void display() 
  5.         {
  6.             System.out.println(i);
  7.         }
  8.     }    
  9.     class B extends A 
  10.     {
  11.         int j;
  12.         void display() 
  13.         {
  14.             System.out.println(j);
  15.         }
  16.     }    
  17.     class inheritance_demo 
  18.     {
  19.         public static void main(String args[])
  20.         {
  21.             B obj = new B();
  22.             obj.i=1;
  23.             obj.j=2;   
  24.             obj.display();     
  25.         }
  26.    }

a) 0
b) 1
c) 2
d) Compilation Error

Answer: c
Clarification: Class A & class B both contain display() method, class B inherits class A, when display() method is called by object of class B, display() method of class B is executed rather than that of Class A.
output:

$ javac inheritance_demo.java 
$ java inheritance_demo 
2

6. What will be the output of the following Java program?

  1.     class A 
  2.     {
  3.         int i;
  4.     }    
  5.     class B extends A 
  6.     {
  7.         int j;
  8.         void display() 
  9.         {
  10.             super.i = j + 1;
  11.             System.out.println(j + " " + i);
  12.         }
  13.     }    
  14.     class inheritance 
  15.     {
  16.         public static void main(String args[])
  17.         {
  18.             B obj = new B();
  19.             obj.i=1;
  20.             obj.j=2;   
  21.             obj.display();     
  22.         }
  23.    }

a) 2 2
b) 3 3
c) 2 3
d) 3 2

Answer: c
Clarification: None
output:

$ javac inheritance.java
$ java inheritance
2 3

7. What will be the output of the following Java program?

  1.     class A 
  2.     {
  3.         public int i;
  4.         public int j;
  5.         A() 
  6.         {
  7.             i = 1;
  8.             j = 2;
  9. 	}
  10.     }    
  11.     class B extends A 
  12.     {
  13.         int a;
  14.         B() 
  15.         {
  16.             super();
  17.         } 
  18.     }    
  19.     class super_use 
  20.     {
  21.         public static void main(String args[])
  22.         {
  23.             B obj = new B();
  24.             System.out.println(obj.i + " " + obj.j)     
  25.         }
  26.    }

a) 1 2
b) 2 1
c) Runtime Error
d) Compilation Error

Answer: a
Clarification: Keyword super is used to call constructor of class A by constructor of class B. Constructor of a initializes i & j to 1 & 2 respectively.
output:

$ javac super_use.java
$ java super_use
1 2

250+ TOP MCQs on Java’s Built in Exceptions and Answers

Java MCQs on Java’s built in exceptions of Java Programming Language.

1. Which of these exceptions handles the situations when an illegal argument is used to invoke a method?
a) IllegalException
b) Argument Exception
c) IllegalArgumentException
d) IllegalMethodArgumentExcepetion

Answer: c
Clarification: None.

2. Which of these exceptions will be thrown if we declare an array with negative size?
a) IllegalArrayException
b) IllegalArraySizeExeption
c) NegativeArrayException
d) NegativeArraySizeExeption

Answer: d
Clarification: Array size must always be positive if we declare an array with negative size then built in exception “NegativeArraySizeException” is thrown by the java’s run time system.

3. Which of these packages contain all the Java’s built in exceptions?
a) java.io
b) java.util
c) java.lang
d) java.net

Answer: c
Clarification: None.

4. Which of these exceptions will be thrown if we use null reference for an arithmetic operation?
a) ArithmeticException
b) NullPointerException
c) IllegalAccessException
d) IllegalOperationException

Answer: b
Clarification: If we use null reference anywhere in the code where the value stored in that reference is used then NullPointerException occurs.

5. Which of these class is used to create user defined exception?
a) java.lang
b) Exception
c) RunTime
d) System

Answer: b
Clarification: Exception class contains all the methods necessary for defining an exception. The class contains the Throwable class.

6. What will be the output of the following Java program?

  1.     class exception_handling 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             try 
  6.             {
  7.                 int a[] = {1, 2,3 , 4, 5};
  8.                 for (int i = 0; i < 7; ++i) 
  9.                     System.out.print(a[i]);
  10.             }
  11.             catch(ArrayIndexOutOfBoundsException e) 
  12.             {
  13.         	System.out.print("0");        	
  14.             }
  15.         }
  16.     }

a) 12345
b) 123450
c) 1234500
d) Compilation Error

Answer: b
Clarification: When array index goes out of bound then ArrayIndexOutOfBoundsException exception is thrown by the system.
Output:

$ javac exception_handling.java
$ java exception_handling
123450

7. What will be the output of the following Java program?

  1.     class exception_handling 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             try 
  6.             {
  7.                 int a[] = {1, 2,3 , 4, 5};
  8.                 for (int i = 0; i < 5; ++i) 
  9.                     System.out.print(a[i]);
  10.                 int x = 1/0;
  11.             }
  12.             catch(ArrayIndexOutOfBoundsException e) 
  13.             {
  14.         	System.out.print("A");        	
  15.             }
  16.             catch(ArithmeticException e) 
  17.             {     	
  18.                 System.out.print("B");
  19.             }
  20.         }
  21.     }

a) 12345
b) 12345A
c) 12345B
d) Compilation Error

Answer: c
Clarification: There can be more than one catch of a single try block. Here Arithmetic exception occurs instead of Array index out of bound exception hence B is printed after 12345
Output:

$ javac exception_handling.java
$ java exception_handling
12345B

8. What will be the output of the following Java program?

  1.     class exception_handling 
  2.     {
  3.             static void throwexception() throws ArithmeticException 
  4.             {        
  5.                 System.out.print("0");
  6.                 throw new ArithmeticException ("Exception");
  7.             }
  8.             public static void main(String args[]) 
  9.             {
  10.             try 
  11.             {
  12.                 throwexception();
  13.             }
  14.             catch (ArithmeticException e) 
  15.             {
  16.                     System.out.println("A");
  17.             }
  18.         }
  19.     }

a) A
b) 0
c) 0A
d) Exception

Answer: c
Clarification: None.
Output:

$ javac exception_handling.java
$ java exception_handling
0A

9. What will be the output of the following Java program?

  1.     class exception_handling 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             try 
  6.              {
  7.                 int a = 1;
  8.                 int b = 10 / a;
  9.                 try 
  10.                 {
  11.                      if (a == 1)
  12.                          a = a / a - a;
  13.                      if (a == 2) 
  14.                      {
  15.                          int c[] = {1};
  16.                          c[8] = 9;
  17.                      }
  18.                 finally 
  19.                 {
  20.                     System.out.print("A");
  21.                 }
  22.  
  23.             }
  24.             catch (NullPointerException e) 
  25.             {
  26.                     System.out.println("B");
  27.             }
  28.         }
  29.     }

a) A
b) B
c) AB
d) BA

Answer: a
Clarification: The inner try block does not have a catch which can tackle ArrayIndexOutOfBoundException hence finally is executed which prints ‘A’ the outer try block does have catch for NullPointerException exception but no such exception occurs in it hence its catch is never executed and only ‘A’ is printed.
Output:

$ javac exception_handling.java
$ java exception_handling
A

10. What will be the output of the following Java program?

  1.     class exception_handling 
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5.             try 
  6.             {
  7.                 int a = args.length;
  8.                 int b = 10 / a;
  9.                 System.out.print(a);
  10.                 try 
  11.                 {
  12.                      if (a == 1)
  13.                          a = a / a - a;
  14.                      if (a == 2) 
  15.                      {
  16.                          int c = {1};
  17.                          c[8] = 9;
  18.                      }
  19.                 }
  20.                 catch (ArrayIndexOutOfBoundException e) 
  21.                 {
  22.                     System.out.println("TypeA");
  23.                 }
  24.                 catch (ArithmeticException e) 
  25.                 {
  26.                     System.out.println("TypeB");
  27.                 }
  28.         }
  29.     }

Note: Execution command line: $ java exception_handling one two
a) TypeA
b) TypeB
c) 0TypeA
d) 0TypeB

Answer: d
Clarification: Execution command line is “$ java exception_ handling one two” hence there are two input making args.length = 2, hence “c[8] = 9” in second try block is executing which throws ArrayIndexOutOfBoundException which is caught by catch of nested try block. Hence 0TypeB is printed.
Output:

$ javac exception_handling.java
$ java exception_handling
0TypeB

250+ TOP MCQs on Networking – Datagrams and Answers

This set of Java Multiple Choice Questions & Answers (MCQs) on “Networking – Datagrams”.

1. Which of these is a bundle of information passed between machines?
a) Mime
b) Cache
c) Datagrams
d) DatagramSocket

Answer: c
Clarification: The Datagrams are the bundle of information passed between machines.

2. Which of these class is necessary to implement datagrams?
a) DatagramPacket
b) DatagramSocket
c) All of the mentioned
d) None of the mentioned

Answer: c
Clarification: None.

3. Which of these method of DatagramPacket is used to find the port number?
a) port()
b) getPort()
c) findPort()
d) recievePort()

Answer: b
Clarification: None.

4. Which of these method of DatagramPacket is used to obtain the byte array of data contained in a datagram?
a) getData()
b) getBytes()
c) getArray()
d) recieveBytes()

Answer: a
Clarification: None.

5. Which of these methods of DatagramPacket is used to find the length of byte array?
a) getnumber()
b) length()
c) Length()
d) getLength()

Answer: d
Clarification: getLength returns the length of the valid data contained in the byte array that would be returned from the getData () method. This typically is not equal to length of whole byte array.

6. Which of these class must be used to send a datagram packets over a connection?
a) InetAdress
b) DatagramPacket
c) DatagramSocket
d) All of the mentioned

Answer: d
Clarification: By using 5 classes we can send and receive data between client and server, these are InetAddress, Socket, ServerSocket, DatagramSocket, and DatagramPacket.

7. Which of these method of DatagramPacket class is used to find the destination address?
a) findAddress()
b) getAddress()
c) Address()
d) whois()

Answer: b
Clarification: None.

8. Which of these is a return type of getAddress() method of DatagramPacket class?
a) DatagramPacket
b) DatagramSocket
c) InetAddress
d) ServerSocket

Answer: c
Clarification: None.

9. Which API gets the SocketAddress (usually IP address + port number) of the remote host that this packet is being sent to or is coming from.
a) getSocketAddress()
b) getAddress()
c) address()
d) none of the mentioned

Answer: a
Clarification: getSocketAddress() is used to get the socket address.

250+ TOP MCQs on Exception Handling and Answers

This set of Java Questions and Answers for Experienced people on “Exception Handling”.

1. Which of the following keywords is used for throwing exception manually?
a) finally
b) try
c) throw
d) catch

Answer: c
Clarification: “throw’ keyword is used for throwing exception manually in java program. User defined exceptions can be thrown too.

2. Which of the following classes can catch all exceptions which cannot be caught?
a) RuntimeException
b) Error
c) Exception
d) ParentException

Answer: b
Clarification: Runtime errors cannot be caught generally. Error class is used to catch such errors/exceptions.

3. Which of the following is a super class of all exception type classes?
a) Catchable
b) RuntimeExceptions
c) String
d) Throwable

Answer: d
Clarification: Throwable is built in class and all exception types are subclass of this class. It is the super class of all exceptions.

4. Which of the following operators is used to generate instance of an exception which can be thrown using throw?
a) thrown
b) alloc
c) malloc
d) new

Answer: d
Clarification: new operator is used to create instance of an exception. Exceptions may have parameter as a String or have no parameter.

5. Which of the following keyword is used by calling function to handle exception thrown by called function?
a) throws
b) throw
c) try
d) catch

Answer: a
Clarification: A method specifies behaviour of being capable of causing exception. Throws clause in the method declaration guards caller of the method from exception.

6. Which of the following handles the exception when a catch is not used?
a) finally
b) throw handler
c) default handler
d) java run time system

Answer: c
Clarification: Default handler is used to handle all the exceptions if catch is not used to handle exception. Finally is called in any case.

7. Which part of code gets executed whether exception is caught or not?
a) finally
b) try
c) catch
d) throw

Answer: a
Clarification: Finally block of the code gets executed regardless exception is caught or not. File close, database connection close, etc are usually done in finally.

8. Which of the following should be true of the object thrown by a thrown statement?
a) Should be assignable to String type
b) Should be assignable to Exception type
c) Should be assignable to Throwable type
d) Should be assignable to Error type

Answer: c
Clarification: The throw statement should be assignable to the throwable type. Throwable is the super class of all exceptions.

9. At runtime, error is recoverable.
a) True
b) False

Answer: b
Clarification: Error is not recoverable at runtime. The control is lost from the application.

Java for Experienced people, here is complete set on Multiple Choice Questions and Answers on Java.

contest

250+ TOP MCQs on Text Formatting and Answers

Java MCQs on text formatting in Java Programming Language.

1. Which of these package is used for text formatting in Java programming language?
a) java.text
b) java.awt
c) java.awt.text
d) java.io

Answer: a
Clarification: java.text allows formatting, searching and manipulating text.

2. Which of this class can be used to format dates and times?
a) Date
b) SimpleDate
c) DateFormat
d) textFormat

Answer: c
Clarification: DateFormat is an abstract class that provides the ability to format and parse dates and times.

3. Which of these method returns an instance of DateFormat that can format time information?
a) getTime()
b) getTimeInstance()
c) getTimeDateinstance()
d) getDateFormatinstance()

Answer: b
Clarification: getTimeInstance() method returns an instance of DateFormat that can format time information.

4. Which of these class allows us to define our own formatting pattern for dates and time?
a) DefinedDateFormat
b) SimpleDateFormat
c) ComplexDateFormat
d) UsersDateFormat

Answer: b
Clarification: The DateFormat is a concrete subclass of DateFormat. It allows you to define your own formatting patterns that are used to display date and time information.

5. Which of these formatting strings of SimpleDateFormat class is used to print AM or PM in time?
a) a
b) b
c) c
d) d

Answer: a
Clarification: By using format string “a” we can print AM/PM in time.

6. Which of these formatting strings of SimpleDateFormat class is used to print week of the year?
a) w
b) W
c) s
d) S

Answer: a
Clarification: By using format string “w” we can print week in a year whereas by using ‘W’ we can print week of a month.

7. What will be the output of the following Java program?

  1.     import java.text.*;
  2.     import java.util.*;
  3.     class Date_formatting
  4.     {	 
  5.         public static void main(String args[])
  6.         {
  7. 	    Date date = new Date();
  8. 	    SimpleDateFormat sdf;
  9.             sdf = new SimpleDateFormat("mm:hh:ss");
  10.             System.out.print(sdf.format(date));
  11.         }	
  12.     }

Note : The program is executed at 3 hour 55 minutes and 4 sec (24 hours time).
a) 3:55:4
b) 3.55.4
c) 55:03:04
d) 03:55:04

Answer: c
Clarification: None.
Output:

$ javac Date_formatting.java
$ java Date_formatting
55:03:04

8. What will be the output of the following Java program?

  1.     import java.text.*;
  2.     import java.util.*;
  3.     class Date_formatting
  4.     {	 
  5.         public static void main(String args[])
  6.         {
  7. 	    Date date = new Date();
  8. 	    SimpleDateFormat sdf;
  9.             sdf = new SimpleDateFormat("hh:mm:ss");
  10.             System.out.print(sdf.format(date));
  11.         }	
  12.     }

Note : The program is executed at 3 hour 55 minutes and 4 sec (24 hours time).
a) 3:55:4
b) 3.55.4
c) 55:03:04
d) 03:55:04

Answer: d
Clarification: The code “sdf = new SimpleDateFormat(“hh:mm:ss”);” create a SimpleDataFormat class with format hh:mm:ss where h is hours, m is month and s is seconds.
Output:

$ javac Date_formatting.java
$ java Date_formatting
03:55:04

9. What will be the output of the following Java program?

  1.     import java.text.*;
  2.     import java.util.*;
  3.     class Date_formatting
  4.     {	 
  5.         public static void main(String args[])
  6.         {
  7. 	    Date date = new Date();
  8. 	    SimpleDateFormat sdf;
  9.             sdf = new SimpleDateFormat("E MMM dd yyyy");
  10.             System.out.print(sdf.format(date));
  11.         }	
  12.     }

Note: The program is executed at 3 hour 55 minutes and 4 sec on Monday, 15 July(24 hours time).
a) Mon Jul 15 2013
b) Jul 15 2013
c) 55:03:04 Mon Jul 15 2013
d) 03:55:04 Jul 15 2013

Answer: a
Clarification: None.
Output:

$ javac Date_formatting.java
$ java Date_formatting
Mon Jul 15 2013

10. What will be the output of the following Java program?

  1.     import java.text.*;
  2.     import java.util.*;
  3.     class Date_formatting
  4.     {	 
  5.         public static void main(String args[])
  6.         {
  7. 	    Date date = new Date();
  8. 	    SimpleDateFormat sdf;
  9.             sdf = new SimpleDateFormat("z");
  10.             System.out.print(sdf.format(date));
  11.         }	
  12.     }

Note : The program is executed at 3 hour 55 minutes and 4 sec on Monday, 15 July(24 hours time).
a) z
b) Jul
c) Mon
d) PDT

Answer: d
Clarification: format string “z” is used to print time zone.
Output:

$ javac Date_formatting.java
$ java Date_formatting
PDT