250+ TOP MCQs on Coding best practices and Answers

This set of Java test on “Coding best practices”.

1. What should the return type of method where there is no return value?
a) Null
b) Empty collection
c) Singleton collection
d) Empty String

Answer: b
Clarification: Returning Empty collection is a good practice. It eliminates chances of unhandled null pointer exceptions.

2. What data structure should be used when number of elements is fixed?
a) Array
b) Array list
c) Vector
d) Set

Answer: a
Clarification: Array list has variable size. Array is stored in contiguous memory. Hence, reading is faster. Also, array is memory efficient.

3. What causes the program to exit abruptly and hence its usage should be minimalistic?
a) Try
b) Finally
c) Exit
d) Catch

Answer: c
Clarification: In case of exit, the program exits abruptly hence would never be able to debug the root cause of the issue.

4. Which of the following is good coding practice to determine oddity?
i)

  1. public boolen abc(int num)
  2. {
  3. 	return num % 2 == 1;
  4. }

ii)

  1. public boolean xyz(int num)
  2. {
  3. 	return (num & 1)!= 0;
  4.  }

a) i
b) ii
c) (i) causes compilation error
d) (ii) causes compilation error

Answer: b
Clarification: Arithmetic and logical operations are much faster than division and multiplication.

5. Which one of the following causes memory leak?
a) Release database connection when querying is complete
b) Use Finally block as much as possible
c) Release instances stored in static tables
d) Not using Finally block often

Answer: d
Clarification: Finally block is called in successful as well exception scenarios. Hence, all the connections are closed properly which avoids memory leak.

6. Which of the following is a best practice to measure time taken by a process for execution?
a) System.currentTimeMillis()
b) System.nanoTime()
c) System.getCurrentTime()
d) System.getProcessingTime()

Answer: b
Clarification: System.nanoTime takes around 1/100000 th of a second whereas System.currentTimeMillis takes around 1/1000th of a second.

7. What one of the following is best practice to handle Null Pointer exception?
i) int noOfStudents = line.listStudents().count;
ii) int noOfStudents = getCountOfStudents(line);

  1.     public int getCountOfStudents(List line)
  2.     {
  3. 	if(line != null)
  4.         {
  5. 		if(line.listOfStudents() != null)
  6.                 {
  7. 			return line.listOfStudents().size();
  8. 		}
  9. 	}
  10. 	throw new NullPointerException("List is empty");
  11.     }

a) Option (i)
b) Option (ii)
c) Compilation Error
d) Option (ii) gives incorrect result

Answer: b
Clarification: Null check must be done while dealing with nested structures to avoid null pointer exceptions.

8. Which of the below is true about java class structure?
a) The class name should start with lowercase
b) The class should have thousands of lines of code
c) The class should only contain those attribute and functionality which it should; hence keeping it short
d) The class attributes and methods should be public

Answer: c
Clarification: Class name should always start with upper case and contain those attribute and functionality which it should (Single Responsibility Principle); hence keeping it short. The attributes should be usually private with get and set methods.

9. Which of the below is false about java coding?
a) variable names should be short
b) variable names should be such that they avoid ambiguity
c) test case method names should be created as english sentences without spaces
d) class constants should be used when we want to share data between class methods

Answer: a
Clarification: variable names like i, a, abc, etc should be avoided. They should be real world names which avoid ambiguity. Test case name should explain its significance.

10. Which is better in terms of performance for iterating an array?
a) for(int i=0; i<100; i++)
b) for(int i=99; i>=0; i–)
c) for(int i=100; i<0; i++)
d) for(int i=99; i>0; i++)

Answer: b
Clarification: reverse traversal of array take half number cycles as compared to forward traversal. The other for loops will go in infinite loop.

To practice all areas of Java for tests, here is complete set on Multiple Choice Questions and Answers on Java.

contest

Advanced 250+ TOP MCQs on AutoCloseable, Closeable and Flushable Interfaces and Answers

This set of Advanced Java Multiple Choice Questions & Answers (MCQs) on “AutoCloseable, Closeable and Flushable Interfaces”.

1. Autocloseable was introduced in which Java version?
a) java SE 7
b) java SE 8
c) java SE 6
d) java SE 4

Answer: a
Clarification: Java 7 introduced autocloseable interface.

2. What is the alternative of using finally to close resource?
a) catch block
b) autocloseable interface to be implemented
c) try block
d) throw Exception

Answer: b
Clarification: Autocloseable interface provides close() method to close this resource and any other underlying resources.

3. Which of the below is a child interface of Autocloseable?
a) Closeable
b) Close
c) Auto
d) Cloneable

Answer: a
Clarification: A closeable interface extends autocloseable interface. A Closeable is a source or destination of data that can be closed.

4. It is a good practise to not throw which exception in close() method of autocloseable?
a) IOException
b) CustomException
c) InterruptedException
d) CloseException

Answer: c
Clarification: InterruptedException interacts with a thread’s interrupted status and runtime misbehavior is likely to occur if an InterruptedException is suppressed.

5. What will be the output of the following Java code snippet?

  1. try (InputStream is = ...) 
  2. {
  3.     // do stuff with is...
  4. } 
  5. catch (IOException e) 
  6. {
  7.     // handle exception
  8. }

a) Runtime Error
b) IOException
c) Compilation Error
d) Runs successfully

Answer: d
Clarification: Using java 7 and above, AutoCloseable objects can be opened in the try-block (within the ()) and will be automatically closed instead of using the finally block.

6. What is the difference between AutoCloseable and Closeable?
a) Closeable is an interface and AutoCloseable is a concrete class
b) Closeable throws IOException; AutoCloseable throws Exception
c) Closeable is a concept; AutoCloseable is an implementation
d) Closeable throws Exception; AutoCloseable throws IOException

Answer: b
Clarification: Closeable extends AutoCloseable and both are interfaces. Closeable throws IOException and AutoCloseable throws Exception.

7. What is the use of Flushable interface?
a) Flushes this stream by writing any buffered output to the underlying stream
b) Flushes this stream and starts reading again
c) Flushes this connection and closes it
d) Flushes this stream and throws FlushException

Answer: a
Clarification: Flushable interface provides flush() method which Flushes this stream by writing any buffered output to the underlying stream.

8. Which version of java added Flushable interface?
a) java SE 7
b) java SE 8
c) java SE 6
d) java SE 5

Answer: d
Clarification: Flushable and Closeable interface are added in java SE 5.

9. Does close() implicitly flush() the stream.
a) True
b) False

Answer: a
Clarification: close() closes the stream but it flushes it first.

10. AutoCloseable and Flushable are part of which package?
a) Autocloseable java.lang; Flushable java.io
b) Autocloseable java.io; Flushable java.lang
c) Autocloseable and Flushable java.io
d) Autocloseable and Flushable java.lang

Answer: a
Clarification: Autocloseable is a part of java.lang; Flushable is a part of java.io.

contest

250+ TOP MCQs on Data Type-Date, TimeZone and Answers

This set of Java Multiple Choice Questions & Answers (MCQs) on “Data Type – Date and TimeZone”.

1. How to format date from one form to another?
a) SimpleDateFormat
b) DateFormat
c) SimpleFormat
d) DateConverter

Answer: a
Clarification: SimpleDateFormat can be used as

Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-mm-dd'T'hh:MM:ss");
String nowStr = sdf.format(now);
System.out.println("Current Date: " + );

2. How to convert Date object to String?
a)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
sdf.parse(new Date());

b)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
sdf.format(new Date());

c)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
new Date().parse();

d)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
new Date().format();

Answer: b
Clarification: SimpleDateFormat takes a string containing pattern. sdf.format converts the Date object to String.

 
 

3. How to convert a String to a Date object?
a)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
sdf.parse(new Date());

b)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
sdf.format(new Date());

c)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
new Date().parse();

d)

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
new Date().format();

Answer: a
Clarification: SimpleDateFormat takes a string containing pattern. sdf.parse converts the String to Date object.

 
 

4. Is SimpleDateFormat thread safe?
a) True
b) False

Answer: b
Clarification: SimpleDateFormat is not thread safe. In the multithreaded environment, we need to manage threads explicitly.

5. How to identify if a timezone is eligible for DayLight Saving?
a) useDaylightTime() of Time class
b) useDaylightTime() of Date class
c) useDaylightTime() of TimeZone class
d) useDaylightTime() of DateTime class

Answer: c
Clarification: public abstract boolean useDaylightTime() is provided in TimeZone class.

6. What is the replacement of joda time library in java 8?
a) java.time (JSR-310)
b) java.date (JSR-310)
c) java.joda
d) java.jodaTime

Answer: a
Clarification: In java 8, we are asked to migrate to java.time (JSR-310) which is a core part of the JDK which replaces joda library project.

7. How is Date stored in database?
a) java.sql.Date
b) java.util.Date
c) java.sql.DateTime
d) java.util.DateTime

Answer: a
Clarification: java.sql.Date is the datatype of Date stored in database.

8. What does LocalTime represent?
a) Date without time
b) Time without Date
c) Date and Time
d) Date and Time with timezone

Answer: b
Clarification: LocalTime of joda library represents time without date.

9. How to get difference between two dates?
a) long diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();
b) long diffInMilli = java.time.difference(dateTime1, dateTime2).toMillis();
c) Date diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();
d) Time diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();

Answer: a
Clarification: Java 8 provides a method called between which provides Duration between two times.

10. How to get UTC time?
a) Time.getUTC();
b) Date.getUTC();
c) Instant.now();
d) TimeZone.getUTC();

Answer: c
Clarification: In java 8, Instant.now() provides current time in UTC/GMT.

250+ TOP MCQs on Overloading Methods & Argument Passing and Answers

Java MCQs on overloading methods & argument passing in Java Programming Language.

1. What is the process of defining two or more methods within same class that have same name but different parameters declaration?
a) method overloading
b) method overriding
c) method hiding
d) none of the mentioned

Answer: a
Clarification: Two or more methods can have same name as long as their parameters declaration is different, the methods are said to be overloaded and process is called method overloading. Method overloading is a way by which Java implements polymorphism.

2. Which of these can be overloaded?
a) Methods
b) Constructors
c) All of the mentioned
d) None of the mentioned

Answer: c
Clarification: None.

3. Which of these is correct about passing an argument by call-by-value process?
a) Copy of argument is made into the formal parameter of the subroutine
b) Reference to original argument is passed to formal parameter of the subroutine
c) Copy of argument is made into the formal parameter of the subroutine and changes made on parameters of subroutine have effect on original argument
d) Reference to original argument is passed to formal parameter of the subroutine and changes made on parameters of subroutine have effect on original argument

Answer: a
Clarification: When we pass an argument by call-by-value a copy of argument is made into the formal parameter of the subroutine and changes made on parameters of subroutine have no effect on original argument, they remain the same.

4. What is the process of defining a method in terms of itself, that is a method that calls itself?
a) Polymorphism
b) Abstraction
c) Encapsulation
d) Recursion

Answer: d
Clarification: None.

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

  1. class San
  2. {
  3.  public void m1 (int i,float f)
  4.  {
  5.   System.out.println(" int float method");
  6.  }
  7.  
  8.  public void m1(float f,int i);
  9.   {
  10.   System.out.println("float int method");
  11.   }
  12.  
  13.   public static void main(String[]args)
  14.   {
  15.     San s=new San();
  16.         s.m1(20,20);
  17.   }
  18. }

a) int float method
b) float int method
c) compile time error
d) run time error

Answer: c
Clarification: While resolving overloaded method, compiler automatically promotes if exact match is not found. But in this case, which one to promote is an ambiguity.

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

  1.     class overload 
  2.     {
  3.         int x;
  4.  	int y;
  5.         void add(int a) 
  6.         {
  7.             x =  a + 1;
  8.         }
  9.         void add(int a, int b)
  10.         {
  11.             x =  a + 2;
  12.         }        
  13.     }    
  14.     class Overload_methods 
  15.     {
  16.         public static void main(String args[])
  17.         {
  18.             overload obj = new overload();   
  19.             int a = 0;
  20.             obj.add(6);
  21.             System.out.println(obj.x);     
  22.         }
  23.    }

a) 5
b) 6
c) 7
d) 8

Answer: c
Clarification: None.
output:

$ javac Overload_methods.java
$ java Overload_methods
7

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

  1.     class overload 
  2.     {
  3.         int x;
  4.  	int y;
  5.         void add(int a)
  6.         {
  7.             x =  a + 1;
  8.         }
  9.         void add(int a , int b)
  10.         {
  11.             x =  a + 2;
  12.         }        
  13.     }    
  14.     class Overload_methods 
  15.     {
  16.         public static void main(String args[])
  17.         {
  18.             overload obj = new overload();   
  19.             int a = 0;
  20.             obj.add(6, 7);
  21.             System.out.println(obj.x);     
  22.         }
  23.     }

a) 6
b) 7
c) 8
d) 9

Answer: c
Clarification: None.
output:

$ javac Overload_methods.java
$ java Overload_methods
8

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

  1.    class overload 
  2.    {
  3.         int x;
  4.  	double y;
  5.         void add(int a , int b) 
  6.         {
  7.             x = a + b;
  8.         }
  9.         void add(double c , double d)
  10.         {
  11.             y = c + d;
  12.         }
  13.         overload() 
  14.         {
  15.             this.x = 0;
  16.             this.y = 0;
  17.         }        
  18.     }    
  19.     class Overload_methods 
  20.     {
  21.         public static void main(String args[])
  22.         {
  23.             overload obj = new overload();   
  24.             int a = 2;
  25.             double b = 3.2;
  26.             obj.add(a, a);
  27.             obj.add(b, b);
  28.             System.out.println(obj.x + " " + obj.y);     
  29.         }
  30.    }

a) 6 6
b) 6.4 6.4
c) 6.4 6
d) 4 6.4

Answer: d
Clarification: For obj.add(a,a); ,the function in line number 4 gets executed and value of x is 4. For the next function call, the function in line number 7 gets executed and value of y is 6.4
output:

$ javac Overload_methods.java
$ java Overload_methods 
4 6.4

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

  1.     class test 
  2.     {
  3.         int a;
  4.         int b;
  5.         void meth(int i , int j) 
  6.         {
  7.             i *= 2;
  8.             j /= 2;
  9.         }          
  10.     }    
  11.     class Output 
  12.     {
  13.         public static void main(String args[])
  14.         {
  15.             test obj = new test();
  16. 	    int a = 10;
  17.             int b = 20;             
  18.             obj.meth(a , b);
  19.             System.out.println(a + " " + b);        
  20.         } 
  21.     }

a) 10 20
b) 20 10
c) 20 40
d) 40 20

Answer: a
Clarification: Variables a & b are passed by value, copy of their values are made on formal parameters of function meth() that is i & j. Therefore changes done on i & j are not reflected back on original arguments. a & b remain 10 & 20 respectively.
output:

$ javac Output.java
$ java Output
10 20

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

  1.     class test 
  2.     {
  3.         int a;
  4.         int b;
  5.         test(int i, int j) 
  6.         {
  7.             a = i;
  8.             b = j;
  9.         }
  10.         void meth(test o) 
  11.         {
  12.             o.a *= 2;
  13.             O.b /= 2;
  14.         }          
  15.     }    
  16.     class Output 
  17.     {
  18.         public static void main(String args[])
  19.         {
  20.             test obj = new test(10 , 20);
  21.             obj.meth(obj);
  22.             System.out.println(obj.a + " " + obj.b);        
  23.         } 
  24.     }

a) 10 20
b) 20 10
c) 20 40
d) 40 20

Answer: b
Clarification: Class objects are always passed by reference, therefore changes done are reflected back on original arguments. obj.meth(obj) sends object obj as parameter whose variables a & b are multiplied and divided by 2 respectively by meth() function of class test. a & b becomes 20 & 10 respectively.
output:

$ javac Output.java
$ java Output
20 10

250+ TOP MCQs on Searching & Modifying a String and Answers

Java MCQs on searching and modifying a string of Java Programming Language.

1. Which of this method of class String is used to extract a substring from a String object?
a) substring()
b) Substring()
c) SubString()
d) None of the mentioned

Answer: a
Clarification: None.

2. What will s2 contain after following lines of Java code?

 String s1 = "one";
String s2 = s1.concat("two")

a) one
b) two
c) onetwo
d) twoone

Answer: c
Clarification: Two strings can be concatenated by using concat() method.

3. Which of these method of class String is used to remove leading and trailing whitespaces?
a) startsWith()
b) trim()
c) Trim()
d) doTrim()

Answer: b
Clarification: None.

4. What is the value returned by function compareTo() if the invoking string is greater than the string compared?
a) zero
b) value less than zero
c) value greater than zero
d) none of the mentioned

Answer: c
Clarification:

 if (s1 == s2) then 0, if(s1 &gt; s2) &gt; 0, if (s1 &lt; s2) then &lt; 0.

5. Which of the following statement is correct?
a) replace() method replaces all occurrences of one character in invoking string with another character
b) replace() method replaces only first occurrences of a character in invoking string with another character
c) replace() method replaces all the characters in invoking string with another character
d) replace() replace() method replaces last occurrence of a character in invoking string with another character

Answer: a
Clarification: replace() method replaces all occurrences of one character in invoking string with another character.

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         { 
  5.            String c = "  Hello World  ";
  6.            String s = c.trim();
  7.            System.out.println("""+s+""");
  8.         }
  9.     }

a) “”Hello World””
b) “”Hello World”
c) “Hello World”
d) Hello world

Answer: c
Clarification: trim() method is used to remove leading and trailing whitespaces in a string.
Output:

$ javac output.java
$ java output
"Hello World"

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         { 
  5.            String s1 = "one";
  6.            String s2 = s1 + " two";
  7.            System.out.println(s2);
  8.         }
  9.     }

a) one
b) two
c) one two
d) compilation error

Answer: c
Clarification: None.
Output:

$ javac output.java
$ java output
one two

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         { 
  5.            String s1 = "Hello";
  6.            String s2 = s1.replace('l','w');
  7.            System.out.println(s2);
  8.         }
  9.     }

a) hello
b) helwo
c) hewlo
d) hewwo

Answer: d
Clarification: replace() method replaces all occurrences of one character in invoking string with another character. s1.replace(‘l’,’w’) replaces every occurrence of ‘l’ in hello by ‘w’, giving hewwo.
Output:

$ javac output.java
$ java output
hewwo

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         {
  5.            String s1 = "Hello World";
  6.            String s2 = s1.substring(0 , 4);
  7.            System.out.println(s2);
  8.         }
  9.    }

a) Hell
b) Hello
c) Worl
d) World

Answer: a
Clarification: substring(0,4) returns the character from 0 th position to 3 rd position.
output:

$ javac output.java
$ java output 
Hell

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

  1.     class output 
  2.     {
  3.         public static void main(String args[])
  4.         {             String s = "Hello World";
  5.              int i = s.indexOf('o');
  6.              int j = s.lastIndexOf('l');
  7.              System.out.print(i + " " + j);
  8.  
  9.         }
  10.    }

a) 4 8
b) 5 9
c) 4 9
d) 5 8

Answer: c
Clarification: indexOf() method returns the index of first occurrence of the character where as lastIndexOf() returns the index of last occurrence of the character.
output:

$ javac output.java
$ java output  
4 9

250+ TOP MCQs on Java.lang – Boolean Wrapper Advance and Answers

This set of Java Multiple Choice Questions & Answers (MCQs) on “Java.lang – Boolean Wrapper Advance”.

1. Which of these methods of Boolean wrapper returns boolean equivalent of an object.
a) getBool()
b) booleanValue()
c) getbooleanValue()
d) getboolValue()

Answer: b
Clarification: None.

2. Which of the following constant are defined in Boolean wrapper?
a) TRUE
b) FALSE
c) TYPE
d) All of the mentioned

Answer: d
Clarification: Boolean wrapper defines 3 constants – TRUE, FALSE & TYPE.

3. Which of these methods return string equivalent of Boolean object?
a) getString()
b) toString()
c) converString()
d) getStringObject()

Answer: b
Clarification: None.

4. Which of these methods is used to know whether a string contains “true”?
a) valueOf()
b) valueOfString()
c) getString()
d) none of the mentioned

Answer: a
Clarification: valueOf() returns true if the specified string contains “true” in lower or uppercase and false otherwise.

5. Which of these class have only one field?
a) Character
b) Boolean
c) Byte
d) void

Answer: d
Clarification: Void class has only one field – TYPE, which holds a reference to the Class object for type void. We do not create an instance of this class.

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

  1.     class Output
  2.     {
  3.         public static void main(String args[])
  4.         {
  5.             String str = "true";
  6.             boolean x = Boolean.valueOf(str);
  7.             System.out.print(x);
  8.         }
  9.     }

a) True
b) False
c) Compilation Error
d) Runtime Error

Answer: a
Clarification: valueOf() returns true if the specified string contains “true” in lower or uppercase and false otherwise.
Output:

$ javac Output.java
$ java Output
true

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

  1.     class Output
  2.     {
  3.         public static void main(String args[])
  4.         {
  5.             String str = "true false true";
  6.             boolean x = Boolean.valueOf(str);
  7.             System.out.print(x);
  8.         }
  9.     }

a) True
b) False
c) Compilation Error
d) Runtime Error

Answer: b
Clarification: valueOf() returns true if the specified string contains “true” in lower or uppercase and false otherwise.
Output:

$ javac Output.java
$ java Output
false

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

  1.     class Output
  2.     {
  3.         public static void main(String args[])
  4.         {
  5.             String str = "TRUE";
  6.             boolean x = Boolean.valueOf(str);
  7.             System.out.print(x);
  8.         }
  9.     }

a) True
b) False
c) Compilation Error
d) Runtime Error

Answer: a
Clarification: valueOf() returns a Boolean instance representing the specified boolean value. If the specified boolean value is true, this method returns Boolean.TRUE; if it is false, this method returns Boolean.FALSE. If a new Boolean instance is not required, this method should generally be used in preference to the constructor Boolean(boolean), as this method is likely to yield significantly better space and time.
Output:

$ javac Output.java
$ java Output
true

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

  1.     class Output 
  2.     {
  3.         public static void main(String args[])
  4.         {
  5. 	    String str = "true false";
  6.             boolean x = Boolean.parseBoolean(str);
  7.             System.out.print(x);
  8.         }
  9.     }

a) True
b) False
c) System Dependent
d) Compilation Error

Answer: b
Clarification: parseBoolean() Parses the string argument as a boolean. The boolean returned represents the value true if the string argument is not null and is equal, ignoring case, to the string “true”.
Example: Boolean.parseBoolean(“True”) returns true.
Example: Boolean.parseBoolean(“yes”) returns false.
Output:

$ javac Output.java
$ java Output
false

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

  1.     class Output
  2.     {
  3.         public static void main(String args[]) 
  4.         {
  5. 	   String x = Boolean.toString(false);
  6.         }
  7.     }

a) True
b) False
c) System Dependent
d) Compilation Error

Answer: b
Clarification: toString() Returns a String object representing the specified boolean. If the specified boolean is true, then the string “true” will be returned, otherwise the string “false” will be returned.
Output:

$ javac Output.java
$ java Output
false