Java MCQ Number 01115

Java MCQ Set 1

1. Which of the following is not a class of java.util.regex?
a) Pattern class
b) matcher class
c) PatternSyntaxException
d) Regex class

Answer

Answer: d [Reason:] java.util.regex consists 3 classes. PatternSyntaxException indicates syntax error in regex.

2. What is the significance of Matcher class for regular expression in java?
a) interpretes pattern in the string
b) Performs match in the string
c) interpretest both pattern and performs match operations in the string
d) None of the mentioned.

Answer

Answer: c [Reason:] macther() method is invoked using matcher object which interpretes pattern and performs match operations in the input string.

3. Object of which class is used to compile regular expression?
a) Pattern class
b) Matcher class
c) PatternSyntaxException
d) None of the mentioned

Answer

Answer: a [Reason:] object of Pattern class can represent compiled regular expression.

4. Which capturing group can represent the entire expression?
a) group *
b) group 0
c) group * or group 0
d) Noe of the mentioned

Answer

Answer: b [Reason:] Group 0 is a special group which represents the entire expression.

5. groupCount reports total number of Capturing groups. True or False?
a) True
b) False

Answer

Answer: a [Reason:] groupCount reports total number of Capturing groups. this does not include special group, group 0.

6. Which of the following matches nonword character using regular expression in java?
a) w
b) W
c) s
d) S

Answer

Answer: b [Reason:] W matches nonword characters. [0-9], [A-Z] and _ (underscore) are word characters. All other than these characters are nonword characters.

7. Which of the following mtches end of the string using regular expression in java?
a) z
b)
c) *
d) Z

Answer

Answer: a [Reason:] z is used to match end of the entire string in regular expression in java.

8. What does public int end(int group) return?
a) offset from last character of the subsequent group
b) offset from first character of the subsequent group
c) offset from last character matched
d) offset from first character matched

Answer

Answer: a [Reason:] public int end(int group) returns offset from last character of the subsequent group.

9. what does public String replaceAll(string replace) do?
a) Replace all characters that matches pattern with replacement string
b) Replace first subsequence that matches pattern with replacement string
c) Replace all other than first subsequence of that matches pattern with replacement string
d) Replace every subsequence of the input sequence that matches pattern with replacement string

Answer

Answer: d [Reason:] replaceAll method replaces every subsequence of the sequence that matches pattern with replacement string.

10. What does public int start() return?
a) returns start index of the input string
b) returns start index of the current match
c) returns start index of the previous match
d) none of the mentioned

Answer

Answer: c [Reason:] public int start() returns index of the previous match in the input string.

Java MCQ Set 2

1. How an object can become serializable?
a) If class implements java.io.Serializable class
b) If class or any superclass implements java.io.Serializable interface
c) Any object is serializable
d) No object is serializable

Answer

Answer: b [Reason:] A Java object is serializable if class or any its superclass implements java.io.Serializable or its subinterface java.io.Externalizable.

2. What is serialization?
a) Turning object in memory into stream of bytes
b) Turning stream of bytes into an object in memory
c) Turning object in memory into stream of bits
d) Turning stream of bits into an object in memory

Answer

Answer: a [Reason:] Serialization in Java is the process of turning object in memory into stream of bytes.

3. What is deserialization?
a) Turning object in memory into stream of bytes
b) Turning stream of bytes into an object in memory
c) Turning object in memory into stream of bits
d) Turning stream of bits into an object in memory

Answer

Answer: b [Reason:] Deserialization is the reverse process of serialization which is turning stream of bytes into an object in memory.

4. How many methods Serializable has?
a) 1
b) 2
c) 3
d) 0

Answer

Answer: d [Reason:] Serializable interface does not have any method. It is also called as marker interface.

5. What type of members are not serialized?
a) Private
b) Protected
c) Static
d) Throwable

Answer

Answer: c [Reason:] All static and transient variables are not serialized.

6. If member does not implement serialization, which exception would be thrown?
a) RuntimeException
b) SerializableException
c) NotSerializableException
d) UnSerializedException

Answer

Answer: c [Reason:] If member of a class does not implement serialization, NotSerializationException will be thrown.

7. Default Serialization process cannot be overridden.
a) True
b) False

Answer

Answer: b [Reason:] Default serialization process can be overridden.

8. Which of the following methods is used to avoid serialization of new class whose super class already implements Serialization?
a) writeObject()
b) readWriteObject()
c) writeReadObject()
d) unSerializaedObject()

Answer

Answer: a [Reason:] writeObject() and readObject() methods should be implemented to avoid Java serialization.

9. Which of the following methods is not used while Serialization and DeSerialization?
a) readObject()
b) readExternal()
c) readWriteObject()
d) writeObject()

Answer

Answer: c [Reason:] Using readObject(), writeObject(), readExternal() and writeExternal() methods Serialization and DeSerialization are implemented.

10. Serializaed object can be transfered via network.
a) True
b) False

Answer

Answer: a [Reason:] Serialized object can be transfered via network because Java serialized object remains in form of bytes which can be transmitted over network.

Java MCQ Set 3

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

Answer: b [Reason:] 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

Answer: a [Reason:] Array list has variable size. Array is stored in contigous 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

Answer: c [Reason:] 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) option (i) causes compilation error
d) option (ii) causes compilation error

Answer

Answer: b [Reason:] Arithmatic 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

Answer: d [Reason:] 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

Answer: b [Reason:] System.nanoTime takes around 1/100000th 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

Answer: b [Reason:] Null check must be done while dealing with nested structures to avoid nullpointer exceptions.

8. Which of the below is true about java class structure?
a) The classname should start with lower case
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

Answer: c [Reason:] Classname should always start with upper case and contain those attribute and functionality which it should (Single Responsibilty 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

Answer: a [Reason:] variable names like i, a, abc, etc should be avoided. They should be real world names which avoids 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

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

Java MCQ Set 4

1. Arrays in Java are implemented as?
a) class
b) object
c) variable
d) none of the mentioned

Answer

Answer: b [Reason:] None.

2. Which of these keywords is used to prevent content of a variable from being modified?
a) final
b) last
c) constant
d) static

Answer

Answer: a [Reason:] A variable can be declared final, doing so prevents its content from being modified. Final variables must be initialized when it is declared.

3. Which of these cannot be declared static?
a) class
b) object
c) variable
d) method

Answer

Answer: b [Reason:] static statements are run as soon as class containing then is loaded, prior to any object declaration.

4. Which of the following statements are incorrect?
a) static methods can call other static methods only
b) static methods must only access static data
c) static methods can not refer to this or super in any way
d) when object of class is declared, each object contains its own copy of static variables

Answer

Answer: d [Reason:] All objects of class share same static variable, when object of a class are declared, all the objects share same copy of static members, no copy of static variables are made.

5. Which of the following statements are incorrect?
a) Variables declared as final occupy memory
b) final variable must be initialized at the time of declaration
c) Arrays in java are implemented as an object
d) All arrays contain an attribute-length which contains the number of elements stored in the array

Answer

Answer: a [Reason:] None.

6. Which of these methods must be made static?
a) main()
b) delete()
c) run()
d) finalize()

Answer

Answer: a [Reason:] main() method must be declared static, main() method is called by Java’s run time system before any object of any class exists.

7. What is the output of this program?

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

a) 1 2
b) 2 3
c) 3 2
d) 1 5

Answer

Answer: d [Reason:] None.
output:
$ javac static_specifier.java
$ java static_specifier
1 5

8. What is the output of this program?

  1.     class access
  2.     {
  3.        static int x;
  4.        void increment()
  5.        {
  6.            x++;
  7.        }   
  8.      }   
  9.     class static_use 
  10.     {
  11.         public static void main(String args[])
  12.         {
  13.             access obj1 = new access();
  14.             access obj2 = new access();
  15.             obj1.x = 0;   
  16.             obj1.increment();
  17.             obj2.increment();
  18.             System.out.println(obj1.x + " " + obj2.x);
  19.          }
  20.    }

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

Answer

Answer: c [Reason:] All objects of class share same static variable, all the objects share same copy of static members, obj1.x and obj2.x refer to same element of class which has been incremented twice and its value is 2.
output:
$ javac static_use.java
$ java static_use
2 2

9. What is the output of this program?

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

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

Answer

Answer: c [Reason:] None.
output:
$ javac static_use.java
$ java static_use
7 9

10. What is the output of this program?

  1.     class Output 
  2.     {
  3.         public static void main(String args[])
  4.         {
  5.             int arr[] = {1, 2, 3, 4, 5};
  6.             for ( int i = 0; i < arr.length - 2; ++i)
  7.                 System.out.println(arr[i] + " ");
  8.         } 
  9.     }

a) 1 2
b) 1 2 3
c) 1 2 3 4
d) 1 2 3 4 5

Answer

Answer: b [Reason:] arr.length() is 5, so the loop is executed for three times.
output:
$ javac Output.java
$ java Output
1 2 3

11. What is the output of this program?

  1.     class Output 
  2.     {
  3.         public static void main(String args[])
  4.         {
  5.             int a1[] = new int[10];
  6.             int a2[] = {1, 2, 3, 4, 5};
  7.             System.out.println(a1.length + " " + a2.length);
  8.         } 
  9.     }

a) 10 5
b) 5 10
c) 0 10
d) 0 5

Answer

Answer: a [Reason:] Arrays in java are implemented as objects, they contain an attribute that is length which contains the number of elements that can be stored in the array. Hence a1.length gives 10 and a2.length gives 5.
output:
$ javac Output.java
$ java Output
10 5

Java MCQ Set 5

1. Which of the following is the advantage of BigDecimal over double?
a) Syntax
b) Memory usage
c) Garbage creation
d) Precision

Answer

Answer: d [Reason:] BigDecimal has unnatural syntax, needs more memory and creates great amount of garbage. But it has high precision which is useful for some calculations like money.

2. Which of the below datatype doesnt support overloaded methods for +,-,* and /?
a) int
b) float
c) double
d) BigDecimal

Answer

Answer: d [Reason:] int, float, double provide overloaded methods for +,-,* and /. BigDecimal does not provide these overloaded methods.

3. What is the output of below code snippet?

  1.    double a = 0.02;
  2.    double b = 0.03;
  3.    double c = b - a;
  4.    System.out.println(c);
  5.  
  6.    BigDecimal _a = new BigDecimal("0.02");
  7.    BigDecimal _b = new BigDecimal("0.03");
  8.    BigDecimal _c = b.subtract(_a);
  9.    System.out.println(_c);

a) 0.009999999999999998
0.01
b) 0.01
0.009999999999999998
c) 0.01
0.01
d) 0.009999999999999998
0.009999999999999998

Answer

Answer: a [Reason:] BigDecimal provides more precision as compared to double. Double is faster in terms of performance as compared to BigDecimal.

4. What is the base of BigDecimal data type?
a) Base 2
b) Base 8
c) Base 10
d) Base e

Answer

Answer: c [Reason:] A BigDecimal is n*10^scale where n is an arbitrary large signed integer. Scale can be thought of as the number of digits to move the decimal point to left or right.

5. What is the limitation of toString() method of BigDecimal?
a) There is no limitation
b) toString returns null
c) toString returns the number in expanded form
d) toString uses scientific notation

Answer

Answer: d [Reason:] toString() of BigDecimal uses scientific notation to represent numbers known as canonical representation. We must use toPlainString() to avoid scientific notation.

6. Which of the following is not provided by BigDecimal?
a) scale manipulation
b) + operator
c) rounding
d) hashing

Answer

Answer: b [Reason:] toBigInteger() converts BigDecimal to a BigInteger.toBigIntegerExact() converts this BigDecimal to a BigInteger by checking for lost information.

7. BigDecimal is a part of which package?
a) java.lang
b) java.math
c) java.util
d) java.io

Answer

Answer: b [Reason:] BigDecimal is a part of java.math. This package provides various classes for storing numbers and mathematical operations.

8. What is BigDecimal.ONE?
a) wrong statement
b) custom defined statement
c) static variable with value 1 on scale 10
d) static variable with value 1 on scale 0

Answer

Answer: d [Reason:] BigDecimal.ONE is a static variable of BigDecimal class with value 1 on scale 0.

9. Which class is a library of functions to perform arithmetic operations of BigInteger and BigDecimal?
a) MathContext
b) MathLib
c) BigLib
d) BigContext

Answer

Answer: a [Reason:] MathContext class is a library of functions to perform arithmetic operations of BigInteger and BigDecimal.

10. What is the output of below code snippet?

  1. public class AddDemo 
  2. {
  3. public static void main(String args[]) 
  4.         {
  5. BigDecimal b = new BigDecimal("23.43");
  6. BigDecimal br = new BigDecimal("24");
  7. BigDecimal bres = b.add(new BigDecimal("450.23"));
  8. System.out.println("Add: "+bres);
  9.  
  10. 		MathContext mc = new MathContext(2, RoundingMode.DOWN);
  11. BigDecimal bdecMath = b.add(new BigDecimal("450.23"), mc);
  12. System.out.println("Add using MathContext: "+bdecMath);
  13. }
  14. }

a) Compilature failure
b) Add: 684.66
Add using MathContext: 6.8E+2
c) Runtime exception
d) Add 6.8E+2
Add using MathContext: 684.66

Answer

Answer: b [Reason:] add() adds the two numbers, MathContext provides library for carrying out various arithmetic operations.

ed010d383e1f191bdb025d5985cc03fc?s=120&d=mm&r=g

DistPub Team

Distance Publisher (DistPub.com) provide project writing help from year 2007 and provide writing and editing help to hundreds student every year.