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)
-
public boolen abc(int num)
-
{
-
return num % 2 == 1;
-
}
ii)
-
public boolean xyz(int num)
-
{
-
return (num & 1)!= 0;
-
}
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);
-
public int getCountOfStudents(List line)
-
{
-
if(line != null)
-
{
-
if(line.listOfStudents() != null)
-
{
-
return line.listOfStudents().size();
-
}
-
}
-
throw new NullPointerException("List is empty");
-
}
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?
-
class access
-
{
-
public int x;
-
static int y;
-
void cal(int a, int b)
-
{
-
x += a ;
-
y += b;
-
}
-
}
-
class static_specifier
-
{
-
public static void main(String args[])
-
{
-
access obj1 = new access();
-
access obj2 = new access();
-
obj1.x = 0;
-
obj1.y = 0;
-
obj1.cal(1, 2);
-
obj2.x = 0;
-
obj2.cal(2, 3);
-
System.out.println(obj1.x + " " + obj2.y);
-
}
-
}
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?
-
class access
-
{
-
static int x;
-
void increment()
-
{
-
x++;
-
}
-
}
-
class static_use
-
{
-
public static void main(String args[])
-
{
-
access obj1 = new access();
-
access obj2 = new access();
-
obj1.x = 0;
-
obj1.increment();
-
obj2.increment();
-
System.out.println(obj1.x + " " + obj2.x);
-
}
-
}
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?
-
class static_out
-
{
-
static int x;
-
static int y;
-
void add(int a , int b)
-
{
-
x = a + b;
-
y = x + b;
-
}
-
}
-
class static_use
-
{
-
public static void main(String args[])
-
{
-
static_out obj1 = new static_out();
-
static_out obj2 = new static_out();
-
int a = 2;
-
obj1.add(a, a + 1);
-
obj2.add(5, a);
-
System.out.println(obj1.x + " " + obj2.y);
-
}
-
}
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?
-
class Output
-
{
-
public static void main(String args[])
-
{
-
int arr[] = {1, 2, 3, 4, 5};
-
for ( int i = 0; i < arr.length - 2; ++i)
-
System.out.println(arr[i] + " ");
-
}
-
}
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?
-
class Output
-
{
-
public static void main(String args[])
-
{
-
int a1[] = new int[10];
-
int a2[] = {1, 2, 3, 4, 5};
-
System.out.println(a1.length + " " + a2.length);
-
}
-
}
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?
-
double a = 0.02;
-
double b = 0.03;
-
double c = b - a;
-
System.out.println(c);
-
-
BigDecimal _a = new BigDecimal("0.02");
-
BigDecimal _b = new BigDecimal("0.03");
-
BigDecimal _c = b.subtract(_a);
-
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?
-
public class AddDemo
-
{
-
public static void main(String args[])
-
{
-
BigDecimal b = new BigDecimal("23.43");
-
BigDecimal br = new BigDecimal("24");
-
BigDecimal bres = b.add(new BigDecimal("450.23"));
-
System.out.println("Add: "+bres);
-
-
MathContext mc = new MathContext(2, RoundingMode.DOWN);
-
BigDecimal bdecMath = b.add(new BigDecimal("450.23"), mc);
-
System.out.println("Add using MathContext: "+bdecMath);
-
}
-
}
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.