Java Questions
Java Questions
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Concepts of OOPs”.
Answer: d
Explanation: There are 4 OOPS concepts in Java. Inheritance, Encapsulation, Polymorphism and Abstraction.
Answer: a
Explanation: There are two type of polymorphism in Java. Compile time polymorphism (overloading) and runtime
polymorphism (overriding).
Answer: b
Explanation: Overloading is determined at compile time. Hence, it is also known as compile time polymorphism.
Answer: d
Explanation: Overloading occurs when more than one method with same name but different constructor and also
when same signature but different number of parameters and/or parameter type.
5. Which concept of Java is a way of converting real world objects in terms of class?
a) Polymorphism
b) Encapsulation
c) Abstraction
d) Inheritance
View Answer
Answer: c
Explanation: Abstraction is concept of defining real world objects in terms of classes or interfaces.
6. Which concept of Java is achieved by combining methods and attribute into a class?
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstration
View Answer
Answer: a
Explanation: Encapsulation is implemented by combining methods and attribute into a class. The class acts like a
container of encapsulating properties.
7. What is it called if an object has its own lifecycle and there is no owner?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
View Answer
Answer: d
Explanation: It is a relationship where all objects have their own lifecycle and there is no owner. This occurs where
many to many relationship is available, instead of one to one or one to many.
8. What is it called where child object gets killed if parent object is killed?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
View Answer
Answer: b
Explanation: Composition occurs when child object gets killed if parent object gets killed. Aggregation is also known
as strong Aggregation.
9. What is it called where object has its own lifecycle and child object cannot belong to another parent object?
a) Aggregation
b) Compostion
c) Encapsulation
d) Association
View Answer
Answer: a
Explanation: Aggregation occurs when objects have their own life cycle and child object can associate with only one
parent object.
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “JDK-JRE-JIT-JVM”.
Answer: b
Explanation: JDK is core component of Java Environment and provides all the tools, executables and binaries
required to compile, debug and execute a Java Program.
2. Which component is responsible for converting byte code into machine specific code?
a) JVM
b) JDK
c) JIT
d) JRE
View Answer
Answer: a
Explanation: JVM is responsible to converting byte code to the machine specific code. JVM is also platform
dependent and provides core java functions like garbage collection,memory management, security etc.
Answer: d
Explanation: JRE is the implementation of JVM, it provides platform to execute java programs.
Answer: c
Explanation: JIT optimise byte code to machine specific language code by compiling similar byte codes at same
time.This reduces overall time taken for compilation of byte code to machine specific language.
Answer: a
Explanation: Java is called ‘Platform Independent Language’ as it primarily works on the principle of ‘compile once,
run everywhere’.
Answer: c
Explanation: main method cannot be private as it is invoked by external method. Other identifier are valid with main
method.
Answer: b
Explanation: Java files have .java extension.
Answer: a
Explanation: The compiled java files have .class extension.
9. How can we identify whether a compilation unit is class or interface from a .class file?
a) Java source file header
b) Extension of compilation unit
c) We cannot differentiate between class and interface
d) The class or interface name should be postfixed with unit type
View Answer
Answer: a
Explanation: The Java source file contains a header that declares the type of class or interface, its visibility with
respect to other classes, its name and any superclass it may extend, or interface it implements.
Answer: b
Explanation: Interpreters read high level language (interprets it) and execute the program. Interpreters are normally
not passing through byte-code and jit compilation.
Answer: b
Explanation: Memory is allocated to an object using new operator. box obj; just declares a reference to object, no
memory is allocated to it hence it points to NULL.
Answer: a
Explanation: None.
Answer: a
Explanation: None.
Answer: a
Explanation: Every class does not need to have a main() method, there can be only one main() method which is
made public.
1. class main_class
2. {
4. {
5. int x = 9;
6. if (x == 9)
7. {
8. int x = 8;
9. System.out.println(x);
10. }
11. }
12. }
a) 9
b) 8
c) Compilation error
d) Runtime error
View Answer
Answer: c
Explanation: Two variables with the same name can’t be created in a class.
output:
$ javac main_class.java
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Duplicate local variable x
Answer: a
Explanation: None.
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. }
7. class mainclass
8. {
10. {
13. obj.height = 2;
16. System.out.print(y);
17. }
18. }
a) 12
b) 200
c) 400
d) 100
View Answer
Answer: b
Explanation: None.
output:
$ javac mainclass.java
$ java mainclass
200
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. }
7. class mainclass
8. {
10. {
13. obj1.height = 1;
14. obj1.length = 2;
15. obj1.width = 1;
17. System.out.println(obj2.height);
18. }
19. }
a) 1
b) 2
c) Runtime error
d) Garbage value
View Answer
Answer: a
Explanation: When we assign an object to another object of same type, all the elements of right side object gets
copied to object on left side of equal to, =, operator.
output:
$ javac mainclass.java
$ java mainclass
1
2. {
3. int width;
4. int height;
5. int length;
6. }
7. class mainclass
8. {
10. {
12. System.out.println(obj);
13. }
14. }
a) 0
b) 1
c) Runtime error
d) classname@hashcode in hexadecimal form
View Answer
Answer: d
Explanation: When we print object internally toString() will be called to return string into this
format classname@hashcode in hexadecimal form.
output:
$ javac mainclass.java
$ java mainclass
box@130671e
This section of our 1000+ Java MCQs focuses on Methods of Java Programming Language.
1. What is the return type of a method that does not returns any value?
a) int
b) float
c) void
d) double
View Answer
Answer: c
Explanation: Return type of an 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
View Answer
Answer: b
Explanation: 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
View Answer
Answer: d
Explanation: 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.
Answer: a
Explanation: main() method can be defined only once in a program. Program execution begins from the main()
method by java’s run time system.
Answer: d
Explanation: 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.
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. int volume;
8. {
9. volume = width*height*length;
10. }
11. }
13. {
15. {
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
View Answer
Answer: c
Explanation: None.
output:
$ Prameterized_method.java
$ Prameterized_method
6
1. class equality
2. {
3. int x;
4. int y;
5. boolean isequal()
6. {
7. return(x == y);
8. }
9. }
11. {
13. {
15. obj.x = 5;
16. obj.y = 5;
17. System.out.println(obj.isequal());
18. }
19. }
a) false
b) true
c) 0
d) 1
View Answer
Answer: b
Explanation: None.
output:
$ javac Output.java
$ java Output
true
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. }
13. {
15. {
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
View Answer
Answer:c
Explanation: None.
output:
$ javac Output.java
$ java Output
25
1. class Output
2. {
3.
6. return;
7. }
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
View Answer
Answer: d
Explanation: sum is a variable argument method and hence it can take any number as argument.
1. class area
2. {
3. int width;
4. int length;
5. int volume;
6. area()
7. {
8. width=5;
9. length=6;
10. }
12. {
15. }
17. {
19. {
21. obj.volume();
22. System.out.println(obj.volume);
23. }
24. }
a) 0
b) 1
c) 30
d) error
View Answer
Answer: d
Explanation: Variable height is not defined.
output:
$ javac cons_method.java
$ java cons_method
error: cannot find symbol height
This section of our 1000+ Java MCQs focuses constructors and garbage collection of Java Programming Language.
Answer: d
Explanation: Constructors does not have any return type, not even void.
2. Which keyword is used by method to refer to the object that invoked it?
a) import
b) catch
c) abstract
d) this
View Answer
Answer: d
Explanation: this keyword can be used inside any method to refer to the current object. this is always a reference to
the object on which the method was invoked.
3. Which of the following is a method having same name as that of its class?
a) finalize
b) delete
c) class
d) constructor
View Answer
Answer: d
Explanation: 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 operator is used by Java run time implementations to free the memory of an object when it is no longer
needed?
a) delete
b) free
c) new
d) none of the mentioned
View Answer
Answer: d
Explanation: Java handles deallocation of memory automatically, we do not need to explicitly delete an element.
Garbage collection only occurs during execution of the program. When no references to the object exist, that object
is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.
5. Which function is used to perform some action when the object is to be destroyed?
a) finalize()
b) delete()
c) main()
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. int volume;
7. box()
8. {
9. width = 5;
10. height = 5;
11. length = 6;
12. }
14. {
16. }
17. }
19. {
21. {
23. obj.volume();
24. System.out.println(obj.volume);
25. }
26. }
a) 100
b) 150
c) 200
d) 250
View Answer
Answer: b
Explanation: None.
output:
$ constructor_output.java
$ constructor_output
150
1. class San
2. {
3. San()throws IOException
4. {
5.
6. }
7.
8. }
10. {
11. Foundry()
12. {
13.
14. }
16. {
17.
18. }
19. }
Answer: a
Explanation: If parent class constructor throws any checked exception, compulsory child class constructor should
throw the same checked exception as its parent, otherwise code won’t compile.
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. int volume;
7. void finalize()
8. {
9. volume = width*height*length;
10. System.out.println(volume);
11. }
13. {
15. System.out.println(volume);
16. }
17. }
19. {
21. {
23. obj.width=5;
24. obj.height=5;
25. obj.length=6;
26. obj.volume();
27. }
28. }
a) 150
b) 200
c) Run time error
d) Compilation error
View Answer
Answer: a
Explanation: None.
output:
$ javac Output.java
$ java Output
150
1. class area
2. {
3. int width;
4. int length;
5. int area;
7. {
8. this.width = width;
9. this.length = length;
10. }
11.
12. }
14. {
16. {
20. }
21. }
a) 0 0
b) 5 6
c) 6 5
d) 5 5
View Answer
Answer: c
Explanation: this keyword can be used inside any method to refer to the current object. this is always a reference to
the object on which the method was invoked.
output:
$ javac Output.java
$ java Output
65
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Constructor”.
Answer: a
Explanation: Object of private constructor can only be createed withing class. Private constructor is used in singleton
pattern.
Answer: c
Explanation: this() and super() cannot be used in a method. This throws compile time error.
Answer: c
Explanation: Default, parameterised constructors can be defined.
Answer: d
Explanation: Class class provides list of methods for use like getInstance().
Answer: b
Explanation: Constructor returns a new object with variables defined as in the class. Instance variables are newly
created and only one copy of static variables are created.
Answer: b
Explanation: No instance can be created of abstract class. Only pointer can hold instance of object.
Answer: b
Explanation: Protected access modifier means that constructor can be accessed by child classes of the parent class
and classes in the same package.
Answer: d
Explanation: “this” is an important keyword in java. It helps to distinguish between local variable and variables
passed in the method as parameters.
Answer: d
Explanation: The class compiles successfully. But the object creation of that class gives compilation error.
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Heap and Garbage Collection”.
Answer: c
Explanation: JVM is the super set which contains heap, stack, objects, pointers, etc.
Answer: a
Explanation: A new object is always created in young space.Once young space is full, a special young collection is run
where objects which have lived long enough are moved to old space and memory is freed up in young space for new
objects.
Answer: b
Explanation: A mark and sweep garbage collection consists of two phases, the mark phase and the sweep phase.I
mark phase all the objects reachable by java threads, native handles and other root sources are marked alive and
others are garbage. In sweep phase, the heap is traversed to find gaps between live objects and the gaps are marked
free list used for allocating memory to new objects.
Answer: c
Explanation: The Xms flag has no default value, and Xmx typically has a default value of 256MB. A common use for
these flags is when you encounter a java.lang.OutOfMemoryError.
6. How to get prints of shared object memory maps or heap memory maps for a given process?
a) jmap
b) memorymap
c) memorypath
d) jvmmap
View Answer
Answer: a
Explanation: We can use jmap as jmap -J-d64 -heap pid .
Answer: c
Explanation: The thread is paused when garbage collection runs which slows the application performance.
Answer: a
Explanation: Memory leak is like holding a strong reference to an object although it would never be needed
anymore. Objects that are reachable but not live are considered memory leaks. Various tools help us to identify
memory leaks.
This section of our 1000+ Java MCQs focuses on overloading methods & argument passing in Java Programming
Language.
1. What is 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
View Answer
Answer: a
Explanation: 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.
Answer: c
Explanation: None.
Answer: a
Explanation: 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
View Answer
Answer: d
Explanation: None.
1. class San
2. {
4. {
6. }
7.
9. {
11. }
12.
14. {
16. s.m1(20,20);
17. }
18. }
Answer: c
Explanation: While resolving overloaded method, compiler automatically promotes if exact match is not found. But
in this case, which one to promote is an ambiguity.
1. class overload
2. {
3. int x;
4. int y;
5. void add(int a)
6. {
7. x = a + 1;
8. }
10. {
11. x = a + 2;
12. }
13. }
15. {
17. {
19. int a = 0;
20. obj.add(6);
21. System.out.println(obj.x);
22. }
23. }
a) 5
b) 6
c) 7
d) 8
View Answer
Answer: c
Explanation: None.
output:
$ javac Overload_methods.java
$ java Overload_methods
7
1. class overload
2. {
3. int x;
4. int y;
5. void add(int a)
6. {
7. x = a + 1;
8. }
10. {
11. x = a + 2;
12. }
13. }
15. {
17. {
19. int a = 0;
21. System.out.println(obj.x);
22. }
23. }
a) 6
b) 7
c) 8
d) 9
View Answer
Answer: c
Explanation: None.
output:
$ javac Overload_methods.java
$ java Overload_methods
8
1. class overload
2. {
3. int x;
4. double y;
6. {
7. x = a + b;
8. }
10. {
11. y = c + d;
12. }
13. overload()
14. {
15. this.x = 0;
16. this.y = 0;
17. }
18. }
20. {
22. {
24. int a = 2;
29. }
30. }
a) 6 6
b) 6.4 6.4
c) 6.4 6
d) 4 6.4
View Answer
Answer: d
Explanation: 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
1. class test
2. {
3. int a;
4. int b;
6. {
7. i *= 2;
8. j /= 2;
9. }
10. }
12. {
14. {
20. }
21. }
a) 10 20
b) 20 10
c) 20 40
d) 40 20
View Answer
Answer: a
Explanation: 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
1. class test
2. {
3. int a;
4. int b;
5. test(int i, int j)
6. {
7. a = i;
8. b = j;
9. }
11. {
12. o.a *= 2;
13. O.b /= 2;
14. }
15. }
17. {
19. {
21. obj.meth(obj);
24. }
a) 10 20
b) 20 10
c) 20 40
d) 40 20
View Answer
Answer: b
Explanation: 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
Answer: b
Explanation: Garbage Collection cannot be controlled by program.
This section of our 1000+ Java MCQs focuses on access control of Java Programming Language.
Answer: b
Explanation: main() method must be specified public as it called by Java run time system, outside of the program. If
no access specifier is used then by default member is public within its own package & cannot be accessed by Java
run time system.
2. Which of these is used to access member of class before object of that class is created?
a) public
b) private
c) static
d) protected
View Answer
Answer: c
Explanation: None.
3. Which of these is used as default for a member of a class if no access specifier is used for it?
a) private
b) public
c) public, within its own package
d) protected
View Answer
Answer: a
Explanation: 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 by which we can control what parts of a program can access the members of a class?
a) Polymorphism
b) Abstraction
c) Encapsulation
d) Recursion
View Answer
Answer: c
Explanation: None.
Answer: c
Explanation: private members of a class can not be inherited by a sub class.
1. class access
2. {
3. public int x;
4. private int y;
6. {
7. x = a + 1;
8. y = b;
9. }
10. }
14. {
18. }
19. }
a) 3 3
b) 2 3
c) Runtime Error
d) Compilation Error
View Answer
Answer: c
Explanation: None.
output:
$ javac access_specifier.java
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The field access.y is not visible
1. class access
2. {
3. public int x;
4. private int y;
6. {
7. x = a + 1;
8. y = b;
9. }
11. {
13. }
14. }
15. class access_specifier
16. {
18. {
21. System.out.println(obj.x);
22. obj.print();
23. }
24. }
a) 2 3
b) 3 3
c) Runtime Error
d) Compilation Error
View Answer
Answer: b
Explanation: None.
output:
$ javac access_specifier.java
$ java access_specifier
33
1. class static_out
2. {
3. static int x;
4. static int y;
6. {
7. x = a + b;
8. y = x + b;
9. }
10. }
12. {
13. public static void main(String args[])
14. {
17. int a = 2;
21. }
22. }
a) 7 7
b) 6 6
c) 7 9
d) 9 7
View Answer
Answer: c
Explanation: None.
output:
$ javac static_use.java
$ java static_use
6 6.4
9. Which of these access specifier must be used for class so that it can be inherited by another sub class?
a) public
b) private
c) protected
d) none of the mentioned
View Answer
Answer: a
Explanation: None.
1. class test
2. {
3. int a;
4. int b;
5. test(int i, int j)
6. {
7. a = i;
8. b = j;
9. }
11. {
12. o.a *= 2;
13. O.b /= 2;
14. }
15. }
17. {
19. {
21. obj.meth(obj);
23. }
24. }
a) 10 20
b) 20 10
c) 20 40
d) 40 20
View Answer
Answer: b
Explanation: 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
This set of Java Interview Questions and Answers focuses on “Access Control – 2”.
1. Which one of the following is not an access modifier?
a) Public
b) Private
c) Protected
d) Void
View Answer
Answer: d
Explanation: Public, private, protected and default are the access modifiers.
Answer: a
Explanation: The variables should be private and should be accessed with get and set methods.
3. Which of the following modifier means a particular variable cannot be accessed within the package?
a) private
b) public
c) protected
d) default
View Answer
Answer: a
Explanation: Private variables are accessible only within the class.
Answer: c
Explanation: The protected access modifier is accessible within package and outside the package but only through
inheritance. The protected access modifier can be used with data member, method and constructor. It cannot be
applied on the class.
Answer: b
Explanation: If we make any class constructor private, we cannot create the instance of that class from outside the
class.
6. All the variables of interface should be ?
a) default and final
b) default and static
c) public,static and final
d) protect, static and final
View Answer
Answer: c
Explanation: Variables of an interface are public, static and final by default because the interfaces cannot be
instantiated, final ensures the value assigned cannot be changed with the implementing class and public for it to be
accessible by all the implementing classes.
Answer: d
Explanation: Final class cannot be inherited. This helps when we do not want classes to provide extension to these
classes.
8. How many copies of static and class variables are created when 10 objects are created of a class?
a) 1, 10
b) 10, 10
c) 10, 1
d) 1, 1
View Answer
Answer: a
Explanation: Only one copy of static variables is created when a class is loaded. Each object instantiated has its own
copy of instance variables.
Answer: b
Explanation: Protected class member (method or variable) is like package-private (default visibility), except that it
also can be accessed from subclasses. Since there is no such concept as ‘subpackage’ or ‘package-inheritance’ in
Java, declaring class protected or package-private would be the same thing.
This set of Java Question Bank focuses on “Arrays Revisited & Keyword static”.
Answer: b
Explanation: 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
View Answer
Answer: a
Explanation: A variable can be declared final, doing so prevents its content from being modified. Final variables must
be initialized when it is declared.
Answer: b
Explanation: static statements are run as soon as class containing then is loaded, prior to any object declaration.
Answer: d
Explanation: 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.
Answer: a
Explanation: None.
Answer: a
Explanation: main() method must be declared static, main() method is called by Java’s run time system before any
object of any class exists.
1. class access
2. {
3. public int x;
4. static int y;
6. {
7. x += a ;
8. y += b;
9. }
10. }
12. {
14. {
17. obj1.x = 0;
18. obj1.y = 0;
23. }
24. }
a) 1 2
b) 2 3
c) 3 2
d) 1 5
View Answer
Answer: d
Explanation: None.
output:
$ javac static_specifier.java
$ java static_specifier
15
1. class access
2. {
3. static int x;
4. void increment()
5. {
6. x++;
7. }
8. }
9. class static_use
10. {
12. {
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
View Answer
Answer: c
Explanation: 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
22
1. class static_out
2. {
3. static int x;
4. static int y;
6. {
7. x = a + b;
8. y = x + b;
9. }
10. }
12. {
14. {
17. int a = 2;
21. }
22. }
a) 7 7
b) 6 6
c) 7 9
d) 9 7
View Answer
Answer: c
Explanation: None.
output:
$ javac static_use.java
$ java static_use
79
1. class Output
2. {
4. {
8. }
9. }
a) 1 2
b) 1 2 3
c) 1 2 3 4
d) 1 2 3 4 5
View Answer
Answer: b
Explanation: arr.length() is 5, so the loop is executed for three times.
output:
$ javac Output.java
$ java Output
123
2. {
4. {
8. }
9. }
a) 10 5
b) 5 10
c) 0 10
d) 0 5
View Answer
Answer: a
Explanation: 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
This section of our 1000+ Java MCQs focuses on String class of Java Programming Language.
1. String in Java is a?
a) class
b) object
c) variable
d) character array
View Answer
Answer: a
Explanation: None.
2. Which of these method of String class is used to obtain character at specified index?
a) char()
b) Charat()
c) charat()
d) charAt()
View Answer
Answer: d
Explanation: None.
3. Which of these keywords is used to refer to member of base class from a sub class?
a) upper
b) super
c) this
d) none of the mentioned
View Answer
Answer: b
Explanation: Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword
super.
4. Which of these method of String class can be used to test to strings for equality?
a) isequal()
b) isequals()
c) equal()
d) equals()
View Answer
Answer: d
Explanation: None.
Answer: b
Explanation: Strings in Java are immutable that is they can not be modified.
1. class string_demo
2. {
4. {
6. System.out.println(obj);
7. }
8. }
a) I
b) like
c) Java
d) IlikeJava
View Answer
Answer: d
Explanation: Java defines an operator +, it is used to concatenate strings.
output:
$ javac string_demo.java
$ java string_demo
IlikeJava
1. class string_class
2. {
4. {
6. System.out.println(obj.charAt(3));
7. }
8. }
a) I
b) L
c) K
d) E
View Answer
Answer: a
Explanation: charAt() is a method of class String which gives the character specified by the index. obj.charAt(3) gives
4th character i:e I.
output:
$ javac string_class.java
$ java string_class
I
1. class string_class
2. {
4. {
6. System.out.println(obj.length());
7. }
8. }
a) 9
b) 10
c) 11
d) 12
View Answer
Answer: c
Explanation: None.
output:
$ javac string_class.java
$ java string_class
11
1. class string_class
2. {
4. {
10. }
11. }
a) hello hello
b) world world
c) hello world
d) world hello
View Answer
Answer: c
Explanation: None.
output:
$ javac string_class.java
$ java string_class
hello world
1. class string_class
2. {
4. {
9. }
10. }
a) false false
b) true true
c) true false
d) false true
View Answer
Answer: d
Explanation: equals() is method of class String, it is used to check equality of two String objects, if they are equal,
true is retuned else false.
output:
$ javac string_class.java
$ java string_class
false true
This set of Java Questions and Answers for Entrance exams focuses on “Methods Taking Parameters”.
1. Which of these is the method which is executed first before execution of any other thing takes place in a program?
a) main method
b) finalize method
c) static method
d) private method
View Answer
Answer: c
Explanation: If a static method is present in the program then it will be executed first, then main will be executed.
2. What is the process of defining more than one method in a class differentiated by parameters?
a) Function overriding
b) Function overloading
c) Function doubling
d) None of the mentioned
View Answer
Answer:b
Explanation: 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 these can be used to differentiate two or more methods having same name?
a) Parameters data type
b) Number of parameters
c) Return type of method
d) All of the mentioned
View Answer
Answer: d
Explanation: None.
4. Which of these data type can be used for a method having a return statement in it?
a) void
b) int
c) float
d) both int and float
View Answer
Answer: d
Explanation: None.
Answer: d
Explanation: Even if a method is returning a value, it is not necessary to store that value.
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. int volume;
8. {
10. }
11. }
14. {
16. obj.height = 1;
17. obj.length = 5;
18. obj.width = 5;
20. System.out.println(obj.volume);
21. }
22. }
a) 0
b) 1
c) 6
d) 25
View Answer
Answer: c
Explanation: None
output:
$ Prameterized_method.java
$ Prameterized_method
6
1. class equality
2. {
3. int x;
4. int y;
5. boolean isequal()
6. {
7. return(x == y);
8. }
9. }
13. {
15. obj.x = 5;
16. obj.y = 5;
17. System.out.println(obj.isequal);
18. }
19. }
a) false
b) true
c) 0
d) 1
View Answer
Answer: b
Explanation: None
output:
$ javac Output.java
$ java Output
true
1. class box
2. {
3. int width;
4. int height;
5. int length;
6. int volume;
7. void volume()
8. {
10. }
12. {
13. volume = x;
14. }
15. }
17. {
19. {
21. obj.height = 1;
22. obj.length = 5;
23. obj.width = 5;
24. obj.volume(5);
25. System.out.println(obj.volume);
26. }
27. }
a) 0
b) 5
c) 25
d) 26
View Answer
Answer:b
Explanation: None.
output:
$ javac Output.java
$ java Output
5
1. class Output
2. {
4. {
5. int x , y = 1;
6. x = 10;
7. if(x != 10 && x / 0 == 0)
8. System.out.println(y);
9. else
10. System.out.println(++y);
11. }
12. }
a) 1
b) 2
c) Runtime Error
d) Compilation Error
View Answer
Answer: d
Explanation: main() method must be made public. Without main() being public java run time system will not be able
to access main() and will not be able to execute the code.
output:
$ javac Output.java
Error: Main method not found in class Output, please define the main method as:
public static void main(String[] args)
1. class area
2. {
3. int width;
4. int length;
5. int height;
6. area()
7. {
8. width = 5;
9. length = 6;
10. height = 1;
11. }
13. {
15. }
16. }
20. {
22. obj.volume();
23. System.out.println(obj.volume);
24. }
25. }
a) 0
b) 1
c) 25
d) 30
View Answer
Answer: d
Explanation: None.
output:
$ javac cons_method.java
$ java cons_method
30
This section of our 1000+ Java MCQs focuses on Command Line Arguments in Java Programming Language.
Answer: a
Explanation: Only main() method can be given parameters via using command line arguments.
Answer: c
Explanation: None.
3. How many arguments can be passed to main()?
a) Infinite
b) Only 1
c) System Dependent
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
Answer: c
Explanation: args in an array of String.
Answer: b
Explanation: All command Line arguments are passed as a string. We must convert numerical value to their internal
forms manually.
6. What is the output of this program, Command line execution is done as – “java Output This is a command Line”?
1. class Output
2. {
4. {
5. System.out.print("args[0]");
6. }
7. }
a) java
b) Oupput
c) This
d) is
View Answer
Answer: c
Explanation: None.
Output:
$ javac Output.javac
java Output This is a command Line
This
7. What is the output of this program, Command line exceution is done as – “java Output This is a command Line”?
1. class Output
2. {
4. {
5. System.out.print("args[3]");
6. }
7. }
a) java
b) is
c) This
d) command
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.javac
java Output This is a command Line
command
8. What is the output of this program, Command line execution is done as – “java Output This is a command Line”?
1. class Output
2. {
4. {
5. System.out.print("args");
6. }
7. }
a) This
b) java Output This is a command Line
c) This is a command Line
d) Compilation Error
View Answer
Answer: c
Explanation: None.
Output:
$ javac Output.javac
java Output This is a command Line
This is a command Line
9. What is the output of this program, Command line execution is done as – “java Output command Line 10 A b 4
N”?
1. class Output
2. {
4. {
5. System.out.print("(int)args[2] * 2");
6. }
7. }
a) java
b) 10
c) 20
d) b
View Answer
Answer: c
Explanation: None.
Output:
$ javac Output.javac
java Output command Line 10 A b 4 N
20
10. What is the output of this program, Command line execution is done as – “java Output command Line 10 A b 4
N”?
1. class Output
2. {
4. {
5. System.out.print("args[6]");
6. }
7. }
a) java
b) 10
c) b
d) N
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.javac
java Output command Line 10 A b 4 N
N
This set of Java Questions and Answers for Freshers focuses on “Command Line Arguments – 2”.
1. What would be the output of following snippet, if attempted to compile and run this code with command line
argument “java abc Rakesh Sharma”?
2. {
3. int a=2000;
5. {
7. }
8. }
Answer: a
Explanation: Main method is static and cannot access non static variable a.
2. What would be the output of following snippet, if attempted to compile and execute?
1. class abc
2. {
4. {
5. if(args.length>0)
6. System.out.println(args.length);
7. }
8. }
Answer: d
Explanation: As no argument is passed to the code, the length of args is 0. So the code will not print.
3. What would be the output of following snippet, if compiled and executed with command line argument “java abc
1 2 3”?
2. {
4. {
6. {
7. System.out.println(xyz[n]+"");
8. }
9. }
10. }
a) 1 2
b) 2 3
c) 1 2 3
d) Compilation error
View Answer
Answer: b
Explantion: The index of array starts with 0. Since the loop is starting with 1 it will print 2 3.
4. What is the output of the following snippet running with “java demo I write java code”?
2. {
4. {
5. System.out.println(args[0]+""+args[args.length-1]);
6. }
7. }
Answer: d
Explanation: The index of array starts with 0 till length – 1. Hence it would print “I code”.
5. What would be the output of the following snippet, if compiled and executed with command line “hello there”?
2. {
3. String[] xyz;
4.
6. {
7. xyz=argv;
8. }
9.
11. {
12. System.out.println(argv[1]);
13. }
14. }
Answer:a
Explanation: Error would be “Cannot make static reference to a non static variable”. Even if main method was not
static, the array argv is local to the main method and would not be visible within runMethod.
Answer: a
Explanation: Arguments tab is used to pass command line argument in eclipse.
Answer: b
Explanation: JCommander is a very small Java framework that makes it trivial to parse command line parameters.
8. Which annotation is used to represent command line input and assigned to correct data type?
a) @Input
b) @Variable
c) @CommandLine
d) @Parameter
View Answer
Answer: d
Explanation: @Parameter, @Parameter(names = { “-log”, “-verbose” }, description = “Level of verbosity”), etc are
various forms of using @Parameter
9. What is the output of below snippet run as $ java Demo –length 512 –breadth 2 -h 3 ?
1. class Demo {
2. @Parameter(names={"--length"})
3. int length;
4.
5. @Parameter(names={"--breadth"})
6. int breadth;
7.
8. @Parameter(names={"--height","-h"})
9. int height;
10.
12. {
16. }
17.
19. {
21. }
22. }
a) 2 512 3
b) 2 2 3
c) 512 2 3
d) 512 512 3
View Answer
Answer: c
Explanation: JCommander helps easily pass commandline arguments. @Parameter assigns input to desired
parameter.
Answer: b
Explanation: JCommander supports the @syntax, which allows us to put all our options into a file and pass this file as
parameter.
/tmp/parameters
-verbose
file1
file2
$ java Main @/tmp/parameters
This section of our 1000+ Java MCQs focuses on recursion of Java Programming Language.
2. Which of these data types is used by operating system to manage the Recursion in Java?
a) Array
b) Stack
c) Queue
d) Tree
View Answer
Answer: b
Explanation: Recursions are always managed by using stack.
3. Which of these will happen if recursive method does not have a base case?
a) An infinite loop occurs
b) System stops the program after some time
c) After 1000000 calls it will be automatically stopped
d) None of the mentioned
View Answer
Answer: a
Explanation: If a recursive method does not have a base case then an infinite loop occurs which results in
stackoverflow.
Answer: d
Explanation: Recursion is always managed by operating system.
Answer: a
Explanation: None.
1. class recursion
2. {
4. {
5. int result;
7. return result;
8. }
9. }
11. {
13. {
15. System.out.print(obj.func(12));
16. }
17. }
a) 0
b) 1
c) Compilation Error
d) Runtime Error
View Answer
Answer: d
Explanation: Since the base case of the recursive function func() is not defined hence infinite loop occurs and results
in stackoverflow.
Output:
$ javac Output.javac
$ java Output
Exception in thread “main” java.lang.StackOverflowError
1. class recursion
2. {
4. {
5. int result;
6. if (n == 1)
7. return 1;
10. }
11. }
13. {
15. {
17. System.out.print(obj.func(5));
18. }
19. }
a) 0
b) 1
c) 120
d) None of the mentioned
View Answer
Answer: b
Explanation: None.
Output:
$ javac Output.javac
$ java Output
1
1. class recursion
2. {
3. int fact(int n)
4. {
5. int result;
6. if (n == 1)
7. return 1;
8. result = fact(n - 1) * n;
9. return result;
10. }
11. }
12. class Output
13. {
15. {
17. System.out.print(obj.fact(5));
18. }
19. }
a) 24
b) 30
c) 120
d) 720
View Answer
Answer: c
Explanation: fact() method recursively calculates factorial of a number, when value of n reaches 1, base case is
excuted and 1 is returned.
Output:
$ javac Output.javac
$ java Output
120
1. class recursion
2. {
3. int fact(int n)
4. {
5. int result;
6. if (n == 1)
7. return 1;
8. result = fact(n - 1) * n;
9. return result;
10. }
11. }
13. {
14. public static void main(String args[])
15. {
17. System.out.print(obj.fact(1));
18. }
19. }
a) 1
b) 30
c) 120
d) Runtime Error
View Answer
Answer: a
Explanation: fact() method recursively calculates factorial of a number, when value of n reaches 1, base case is
excuted and 1 is returned.
Output:
$ javac Output.javac
$ java Output
1
1. class recursion
2. {
3. int fact(int n)
4. {
5. int result;
6. if (n == 1)
7. return 1;
8. result = fact(n - 1) * n;
9. return result;
10. }
11. }
13. {
15. {
16. recursion obj = new recursion() ;
17. System.out.print(obj.fact(6));
18. }
19. }
a) 1
b) 30
c) 120
d) 720
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.javac
$ java Output
720
This section of our 1000+ Java MCQs focuses on method overriding in Java Programming Language.
1. Which of these keyword can be used in subclass to call the constructor of superclass?
a) super
b) this
c) extent
d) extends
View Answer
Answer: a
Explanation: None.
2. What is the process of defining a method in subclass having same name & type signature as a method in its
superclass?
a) Method overloading
b) Method overriding
c) Method hiding
d) None of the mentioned
View Answer
Answer: b
Explanation: None.
4. Which of these is correct way of calling a constructor having no parameters, of superclass A by subclass B?
a) super(void);
b) superclass.();
c) super.A();
d) super();
View Answer
Answer: d
Explanation: None.
5. At line number 2 below, choose 3 valid data-type attributes/qualifiers among “final, static, native, public, private,
abstract, protected”
2. {
4. }
Answer: d
Explanation: Every interface variable is implicitly public static and final.
Answer: c
Explanation: None.
1. class Alligator
2. {
4. {
7. System.out.println(y[2][1]);
8. }
9. }
a) 2
b) 3
c) 7
d) Compilation Error
View Answer
Answer: c
Explanation: Both x,and y are pointing to the same array.
1. final class A
2. {
3. int i;
4. }
5. class B extends A
6. {
7. int j;
9. }
11. {
13. {
15. obj.display();
16. }
17. }
a) 2 2
b) 3 3
c) Runtime Error
d) Compilation Error
View Answer
Answer: d
Explanation: class A has been declared final hence it cannot be inherited by any other class. Hence class B does not
have member i, giving compilation error.
output:
$ javac inheritance.java
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
i cannot be resolved or is not a field
1. class Abc
2. {
4. {
7. }
8. }
a) Compilation error
b) An exception is thrown at run time
c) The variable first is set to null
d) The variable first is set to elements[0].
View Answer
Answer: d
Explanation: The value at the 0th position will be assigned to the variable first.
1. class A
2. {
3. int i;
5. {
6. System.out.println(i);
7. }
8. }
9. class B extends A
10. {
11. int j;
12. public void display()
13. {
14. System.out.println(j);
15. }
16. }
18. {
20. {
22. obj2.i = 1;
23. obj2.j = 2;
24. A r;
25. r = obj2;
26. r.display();
27. }
28. }
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: r is reference of type A, the program assigns a reference of object obj2 to r and uses that reference to
call function display() of class B.
output:
$ javac Dynamic_dispatch.java
$ java Dynamic_dispatch
2
This section of our 1000+ Java MCQs focuses on Object class of Java Programming Language.
Answer: b
Explanation: Object class is superclass of every class in Java.
Answer: c
Explanation: None.
3. Which of these method of Object class is used to obtain class of an object at run time?
a) get()
b) void getclass()
c) Class getclass()
d) None of the mentioned
View Answer
Answer: c
Explanation: None.
Answer: d
Explanation: Declaring a class final implicitly declares all of its methods final, and makes the class inheritable.
5. Which of these keywords cannot be used for a class which has been declared final?
a) abstract
b) extends
c) abstract and extends
d) none of the mentioned
View Answer
Answer: a
Explanation: A abstract class is incomplete by itself and relies upon its subclasses to provide complete
implementation. If we declare a class final then no class can inherit that class, an abstract class needs its subclasses
hence both final and abstract cannot be used for a same class.
6. Which of these class relies upon its subclasses for complete implementation of its methods?
a) Object class
b) abstract class
c) ArrayList class
d) None of the mentioned
View Answer
Answer: b
Explanation: None.
1. abstract class A
2. {
3. int i;
5. }
6. class B extends A
7. {
8. int j;
9. void display()
10. {
11. System.out.println(j);
12. }
13. }
15. {
17. {
19. obj.j=2;
20. obj.display();
21. }
22. }
a) 0
b) 2
c) Runtime Error
d) Compilation Error
View Answer
Answer: b
Explanation: class A is an abstract class, it contains a abstract function display(), the full implementation of display()
method is given in its subclass B, Both the display functions are the same. Prototype of display() is defined in class A
and its implementation is given in class B.
output:
$ javac Abstract_demo.java
$ java Abstract_demo
2
1. class A
2. {
3. int i;
4. int j;
5. A()
6. {
7. i = 1;
8. j = 2;
9. }
10. }
12. {
14. {
17. System.out.print(obj1.equals(obj2));
18. }
19. }
a) false
b) true
c) 1
d) Compilation Error
View Answer
Answer: a
Explanation: obj1 and obj2 are two different objects. equals() is a method of Object class, Since Object class is
superclass of every class it is available to every object.
output:
$ javac Output.java
$ java Output
false
1. class Output
2. {
4. {
6. System.out.print(obj.getclass());
7. }
8. }
a) Object
b) class Object
c) class java.lang.Object
d) Compilation Error
View Answer
Answer: c
Explanation: None.
output:
$ javac Output.java
$ java Output
class java.lang.Object
1. class A
2. {
3. int i;
4. int j;
5. A()
6. {
7. i = 1;
8. j = 2;
9. }
10. }
12. {
14. {
16. System.out.print(obj1.toString());
17. }
18. }
a) true
b) false
c) String associated with obj1
d) Compilation Error
View Answer
Answer: c
Explanation: toString() is method of class Object, since it is superclass of every class, every object has this method.
toString() returns the string associated with the calling object.
output:
$ javac Output.java
$ java Output
A@1cd2e5f
This section of our 1000+ Java MCQs focuses on Abstract class in Java Programming Language.
Answer: b
Explanation: None.
Answer: a
Explanation: Thread is not an abstract class.
3. If a class inheriting an abstract class does not define all of its function then it will be known as?
a) Abstract
b) A simple class
c) Static class
d) None of the mentioned
View Answer
Answer: a
Explanation: Any subclass of an abstract class must either implement all of the abstract method in the superclass or
be itself declared abstract.
Answer: c
Explanation: Abstract class cannot be directly initiated with new operator, Since abstract class does not contain any
definition of implementation it is not possible to create an abstract object.
Answer: a
Explanation: None.
1. class A
2. {
3. public int i;
4. private int j;
5. }
6. class B extends A
7. {
8. void display()
9. {
13. }
15. {
17. {
19. obj.i=1;
20. obj.j=2;
21. obj.display();
22. }
23. }
a) 2 2
b) 3 3
c) Runtime Error
d) Compilation Error
View Answer
Answer: d
Explanation: Class contains a private member variable j, this cannot be inherited by subclass B and does not have
access to it.
output:
$ javac inheritance.java
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The field A.j is not visible
1. class A
2. {
3. public int i;
4. public int j;
5. A()
6. {
7. i = 1;
8. j = 2;
9. }
10. }
12. {
13. int a;
14. B()
15. {
16. super();
17. }
18. }
20. {
22. {
25. }
26. }
a) 1 2
b) 2 1
c) Runtime Error
d) Compilation Error
View Answer
Answer: a
Explanation: 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
12
1. abstract class A
2. {
3. int i;
6. class B extends A
7. {
8. int j;
9. void display()
10. {
11. System.out.println(j);
12. }
13. }
15. {
17. {
19. obj.j=2;
20. obj.display();
21. }
22. }
a) 0
b) 2
c) Runtime Error
d) Compilation Error
View Answer
Answer: b
Explanation: class A is an abstract class, it contains a abstract function display(), the full implementation of display()
method is given in its subclass B, Both the display functions are the same. Prototype of display() is defined in class A
and its implementation is given in class B.
output:
$ javac Abstract_demo.java
$ java Abstract_demo
2
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;
13. {
14. System.out.println(j);
15. }
16. }
18. {
20. {
22. obj.i=1;
23. obj.j=2;
24. obj.display();
25. }
26. }
a) 0
b) 1
c) 2
d) Compilation Error
View Answer
Answer: c
Explanation: 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 method_overriding.java
$ java method_overriding
2
1. class A
2. {
3. public int i;
4. protected int j;
5. }
6. class B extends A
7. {
8. int j;
9. void display()
10. {
11. super.j = 3;
13. }
14. }
16. {
18. {
20. obj.i=1;
21. obj.j=2;
22. obj.display();
23. }
24. }
a) 1 2
b) 2 1
c) 1 3
d) 3 1
View Answer
Answer: a
Explanation: Both class A & B have member with same name that is j, member of class B will be called by default if
no specifier is used. I contains 1 & j contains 2, printing 1 2.
output:
$ javac Output.java
$ java Output
12
This section of our 1000+ Java MCQs focuses on Inheritance of Java Programming Language.
Answer: d
Explanation: None.
2. Which of these keywords is used to refer to member of base class from a sub class?
a) upper
b) super
c) this
d) none of the mentioned
View Answer
Answer: b
Explanation: Whenever a subclass needs to refer to its immediate superclass, it can do so by use of the keyword
super.
Answer: b
Explanation: A class member declared protected becomes private member of subclass.
Answer: c
Explanation: None.
5. Which two classes use the Shape class correctly?
/* code here */
/* code here */
a) B,E
b) A,C
c) C,E
d) T,H
View Answer
Answer: a
Explanation: If one is extending any class, then they should use extends keyword not implements.
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;
13. {
14. System.out.println(j);
15. }
16. }
18. {
22. obj.i=1;
23. obj.j=2;
24. obj.display();
25. }
26. }
a) 0
b) 1
c) 2
d) Compilation Error
View Answer
Answer: c
Explanation: 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
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;
12. }
13. }
17. {
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
View Answer
Answer: c
Explanation: None
output:
$ javac inheritance.java
$ java inheritance
23
1. class A
2. {
3. public int i;
4. private int j;
5. }
6. class B extends A
7. {
8. void display()
9. {
12. }
13. }
14. class inheritance
15. {
17. {
19. obj.i=1;
20. obj.j=2;
21. obj.display();
22. }
23. }
a) 2 2
b) 3 3
c) Runtime Error
d) Compilation Error
View Answer
Answer: d
Explanation: Class contains a private member variable j, this cannot be inherited by subclass B and does not have
access to it.
output:
$ javac inheritance.java
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
The field A.j is not visible
1. class A
2. {
3. public int i;
4. public int j;
5. A()
6. {
7. i = 1;
8. j = 2;
9. }
10. }
13. int a;
14. B()
15. {
16. super();
17. }
18. }
20. {
22. {
25. }
26. }
a) 1 2
b) 2 1
c) Runtime Error
d) Compilation Error
View Answer
Answer: a
Explanation: 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
12
1. class A
2. {
3. public int i;
4. protected int j;
5. }
6. class B extends A
7. {
8. int j;
9. void display()
10. {
11. super.j = 3;
13. }
14. }
16. {
18. {
20. obj.i=1;
21. obj.j=2;
22. obj.display();
23. }
24. }
a) 1 2
b) 2 1
c) 1 3
d) 3 1
View Answer
Answer: a
Explanation: Both class A & B have member with same name that is j, member of class B will be called by default if
no specifier is used. I contains 1 & j contains 2, printing 1 2.
output:
$ javac Output.java
$ java Output
12
This set of Java Interview Questions and Answers for freshers focuses on “Inheritance – 2”.
Answer: b
Explanation: Inheritance is way of acquiring attributes and methods of parent class. Java supports hierarchical
inheritance directly.
Answer: a
Explanation: Multiple inheritance in java is implemented using interfaces. Multiple interfaces can be implemented by
a class.
Answer: d
Explanation: All classes in java are inherited from Object class. Interfaces are not inherited from Object Class.
4. In order to restrict a variable of a class from inheriting to sub class, how variable should be declared?
a) Protected
b) Private
c) Public
d) Static
View Answer
Answer: b
Explanation: By declaring variable private, the variable will not be available in inherited to sub class.
5. If super class and sub class have same variable name, which keyword should be used to use super class?
a) super
b) this
c) upper
d) classname
View Answer
Answer: a
Explanation: Super keyword is used to access hidden super class variable in sub class.
Answer: d
Explanation: Interface is implemented using implements keyword. A concrete class must implement all the methods
of an iterface, else it must be declared abstract.
Answer: c
Explanation: Class can be extended using extends keyword. One class can extend only one class. A final class cannot
be extended.
9. What would be the result if class extends two interfaces and both have method with same name and signature?
a) Runtime error
b) Compile time error
c) Code runs successfully
d) First called method is executed successfully
View Answer
Answer: b
Explanation: In case of such conflict, compiler will not be able to link a method call due to ambiguity. It will throw
compile time error.
Answer: a
Explanation: Java supports multiple level inheritance through implementing multiple interfaces.
This section of our 1000+ Java MCQs focuses on string handling in Java Programming Language.
Answer: b
Explanation: None.
2. Which of these operators can be used to concatenate two or more String objects?
a) +
b) +=
c) &
d) ||
View Answer
Answer: a
Explanation: Operator + is used to concatenate strings, Example String s = “i ” + “like ” + “java”; String s contains “I
like java”.
3. Which of these method of class String is used to obtain length of String object?
a) get()
b) Sizeof()
c) lengthof()
d) length()
View Answer
Answer: d
Explanation: Method length() of string class is used to get the length of the object which invoked method length().
4. Which of these method of class String is used to extract a single character from a String object?
a) CHARAT()
b) chatat()
c) charAt()
d) ChatAt()
View Answer
Answer: c
Explanation: None.
Answer: a
Explanation: None.
1. class String_demo
2. {
4. {
7. System.out.println(s);
8. }
9. }
a) a
b) b
c) c
d) abc
View Answer
Answer: d
Explanation: String(chars) is a constructor of class string, it initializes string s with the values stored in character array
chars, therefore s contains “abc”.
output:
$ javac String_demo.java
$ java String_demo
abc
1. class String_demo
2. {
4. {
7. System.out.println(s);
8. }
9. }
a) ABC
b) BCD
c) CDA
d) ABCD
View Answer
Answer: b
Explanation: ascii is an array of integers which contains ascii codes of Characters A, B, C, D. String(ascii, 1, 3) is an
constructor which initializes s with Characters corresponding to ascii codes stored in array ascii, starting position
being given by 1 & ending position by 3, Thus s stores BCD.
output:
$ javac String_demo.java
$ java String_demo
BCD
1. class String_demo
2. {
4. {
7. String s1 = "abcd";
11. }
12. }
a) 3 0
b) 0 3
c) 3 4
d) 4 3
View Answer
Answer: d
Explanation: None.
output:
$ javac String_demo.java
$ java String_demo
43
2. {
3. int i;
4. int j;
5. A()
6. {
7. i = 1;
8. j = 2;
9. }
10. }
12. {
14. {
16. System.out.print(obj1.toString());
17. }
18. }
a) True
b) False
c) String associated with obj1
d) Compilation Error
View Answer
Answer: c
Explanation: toString() is method of class Object, since it is superclass of every class, every object has this method.
toString() returns the string associated with the calling object.
output:
$ javac Output.java
$ java Output
A@1cd2e5f
This section of our 1000+ Java MCQs focuses on character extraction of Java Programming Language.
1. Which of these method of class String is used to extract more than one character at a time a String object?
a) getchars()
b) GetChars()
c) Getchars()
d) getChars()
View Answer
Answer: d
Explanation: None.
2. Which of these methods is an alternative to getChars() that stores the characters in an array of bytes?
a) getBytes()
b) GetByte()
c) giveByte()
d) Give Bytes()
View Answer
Answer: a
Explanation: getBytes() stores the character in an array of bytes. It uses default character to byte conversions
provided by platform.
3. In below code, what can directly access and change the value of the variable name?
1. package test;
2. class Target
3. {
5. }
a) any class
b) only the Target class
c) any class in the test package
d) any class that extends Target
View Answer
Answer: c
Explanation: Any class in the test package can access and change name.
2. {
3. Integer i;
4. int x;
5. public Boxer1(int y)
6. {
7. x = i+y;
8. System.out.println(x);
9. }
11. {
13. }
14. }
Answer: d
Explanation: Because we are performing operation on reference variable which is null.
5. Which of these methods can be used to convert all characters in a String into a character array?
a) charAt()
b) both getChars() & charAt()
c) both toCharArray() & getChars()
d) all of the mentioned
View Answer
Answer: c
Explanation: charAt() return one character only not array of character.
1. class output
2. {
4. {
6. int start = 2;
7. int end = 9;
9. c.getChars(start,end,s,0);
10. System.out.println(s);
11. }
12. }
a) Hello, i love java
b) i love ja
c) lo i lo
d) llo i l
View Answer
Answer: d
Explanation: getChars(start,end,s,0) returns an array from the string c, starting index of array is pointed by start and
ending index is pointed by end. s is the target character array where the new string of letters is going to be stored
and the new string will be stored from 0th position in s.
Output:
$ javac output.java
$ java output
llo i l
1. class output
2. {
4. {
7. }
8. }
a) 6 4 6 9
b) 5 4 5 9
c) 7 8 8 9
d) 4 3 6 9
View Answer
Answer: a
Explanation: indexof(‘c’) and lastIndexof(‘c’) are pre defined function which are used to get the index of first and last
occurrence of
the character pointed by c in the given array.
Output:
$ javac output.java
$ java output
6469
1. class output
2. {
7. {
8. if(Character.isDigit(c[i]))
9. System.out.println(c[i]+" is a digit");
10. if(Character.isWhitespace(c[i]))
12. if(Character.isUpperCase(c[i]))
14. if(Character.isLowerCase(c[i]))
16. i=i+3;
17. }
18. }
19. }
Answer: c
Explanation: Character.isDigit(c[i]),Character.isUpperCase(c[i]),Character.isWhitespace(c[i]) are the function of
library java.lang. They are used to find weather the given character is of specified type or not. They return true or
false i:e Boolean variable.
Output:
$ javac output.java
$ java output
a is a lower case Letter
A is an Upper Case Letter
1. class String_demo
2. {
3. public static void main(String args[])
4. {
7. System.out.println(s);
8. }
9. }
a) a
b) b
c) c
d) abc
View Answer
Answer: d
Explanation: String(chars) is a constructor of class string, it initializes string s with the values stored in character array
chars, therefore s contains “abc”.
output:
$ javac String_demo.java
$ java String_demo
abc
1. class output
2. {
4. {
5. char ch;
6. ch = "hello".charAt(1);
7. System.out.println(ch);
8. }
9. }
a) h
b) e
c) l
d) o
View Answer
Answer: b
Explanation: “hello” is a String literal, method charAt() returns the character specified at the index position.
Character at index position 1 is e of hello, hence ch contains e.
output:
$ javac output.java
$ java output
e
This section of our 1000+ Java MCQs focuses on String comparision in Java Programming Language.
1. Which of these method of class String is used to compare two String objects for their equality?
a) equals()
b) Equals()
c) isequal()
d) Isequal()
View Answer
Answer: a
Explanation: None.
2. Which of these methods is used to compare a specific region inside a string with another specific region in another
string?
a) regionMatch()
b) match()
c) RegionMatches()
d) regionMatches()
View Answer
Answer: d
Explanation: None.
3. Which of these method of class String is used to check weather a given object starts with a particular string literal?
a) startsWith()
b) endsWith()
c) Starts()
d) ends()
View Answer
Answer: a
Explanation: Method startsWith() of string class is used to check whether the String in question starts with a
specified string. It is specialized form of method regionMatches().
4. What is the value returned by unction compareTo() if the invoking string is less than the string compared?
a) zero
b) value less than zero
c) value greater than zero
d) none of the mentioned
View Answer
Answer: b
Explanation: compareTo() function returns zero when both the strings are equal, it returns a value less than zero if
the invoking string is less than the other string being compared and value greater than zero when invoking string is
greater than the string compared to.
5. Which of these data type value is returned by equals() method of String class?
a) char
b) int
c) boolean
d) all of the mentioned
View Answer
Answer: c
Explanation: equals() method of string class returns boolean value true if both the string are equal and false if they
are unequal.
1. class output
2. {
4. {
6. boolean var;
7. var = c.startsWith("hello");
8. System.out.println(var);
9. }
10. }
a) true
b) false
c) 0
d) 1
View Answer
Answer: b
Explanation: startsWith() method is case sensitive “hello” and “Hello” are treated differently, hence false is stored in
var.
Output:
$ javac output.java
$ java output
false
1. class output
2. {
4. {
5. String s1 = "Hello i love java";
8. }
9. }
a) true true
b) false false
c) true false
d) false true
View Answer
Answer: d
Explanation: The == operator compares two object references to see whether they refer to the same instance, where
as equals() compares the content of the two objects.
Output:
$ javac output.java
$ java output
false true
1. class output
2. {
4. {
5. String s1 = "Hello";
7. String s3 = "HELLO";
9. }
10. }
a) true true
b) false false
c) true false
d) false true
View Answer
Answer: c
Explanation: None.
Output:
$ javac output.java
$ java output
true false
9. In the below code, which code fragment should be inserted at line 3 so that the output will be: “123abc 123abc”?
2 String s1 = "123";
a) sb1.append(“abc”); s1.append(“abc”);
b) sb1.append(“abc”); s1.concat(“abc”);
c) sb1.concat(“abc”); s1.append(“abc”);
d) sb1.append(“abc”); s1 = s1.concat(“abc”);
View Answer
Answer: d
Explanation: append() is stringbuffer method and concat is String class method.
append() is stringbuffer method and concat is String class method.
1. class output
2. {
4. {
8. if(chars[i].compareTo(chars[j]) == 0)
9. System.out.print(chars[j]);
10. }
11. }
a) ab
b) bc
c) ca
d) ac
View Answer
Answer: d
Explanation: compareTo() function returns zero when both the strings are equal, it returns a value less than zero if
the invoking string is less than the other string being compared and value greater than zero when invoking string is
greater than the string compared to.
output:
$ javac output.java
$ java output
ac
This section of our 1000+ Java MCQs focuses on searching and modifying a string of Java Programming Language.
1. Which of these 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
View Answer
Answer: a
Explanation: None.
String s1 = "one";
String s2 = s1.concat("two")
a) one
b) two
c) onetwo
d) twoone
View Answer
Answer: c
Explanation: 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()
View Answer
Answer: b
Explanation: 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
View Answer
Answer: c
Explanation: if (s1 == s2) then 0, if(s1 > s2) > 0, if (s1 < s2) then < 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 occurances 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
View Answer
Answer: a
Explanation: replace() method replaces all occurrences of one character in invoking string with another character.
1. class output
2. {
4. {
6. String s = c.trim();
7. System.out.println("\""+s+"\"");
8. }
9. }
a) “”Hello World””
b) “”Hello World”
c) “Hello World”
d) Hello world
View Answer
Answer: c
Explanation: trim() method is used to remove leading and trailing whitespaces in a string.
Output:
$ javac output.java
$ java output
“Hello World”
1. class output
2. {
4. {
5. String s1 = "one";
8. }
9. }
a) one
b) two
c) one two
d) compilation error
View Answer
Answer: c
Explanation: None.
Output:
$ javac output.java
$ java output
one two
1. class output
2. {
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
View Answer
Answer: d
Explanation: 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
1. class output
2. {
4. {
7. System.out.println(s2);
8. }
9. }
a) Hell
b) Hello
c) Worl
d) World
View Answer
Answer: a
Explanation: substring(0,4) returns the character from 0 th position to 3 rd position.
output:
$ javac output.java
$ java output
Hell
1. class output
2. {
5. int i = s.indexOf('o');
6. int j = s.lastIndexOf('l');
8.
9. }
10. }
a) 4 8
b) 5 9
c) 4 9
d) 5 8
View Answer
Answer: c
Explanation: 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
49
This section of our 1000+ Java MCQs focuses on StringBuffer class of Java Programming Language.
1. Which of these class is used to create an object whose character sequence is mutable?
a) String()
b) StringBuffer()
c) Both of the mentioned
d) None of the mentioned
View Answer
Answer: b
Explanation: StringBuffer represents growable and writeable character sequence.
2. Which of these method of class StringBuffer is used to concatenate the string representation to the end of
invoking string?
a) concat()
b) append()
c) join()
d) concatenate()
View Answer
Answer: b
Explanation: None.
3. Which of these method of class StringBuffer is used to find the length of current character sequence?
a) length()
b) Length()
c) capacity()
d) Capacity()
View Answer
Answer: a
Explanation: None.
Answer: a
Explanation: reverse() method reverses all characters. It returns the reversed object on which it was called.
1. class output
2. {
4. {
7. }
8. }
a) 6 4 6 9
b) 5 4 5 9
c) 7 8 8 9
d) 1 14 8 15
View Answer
Answer: a
Explantion: indexof(‘c’) and lastIndexof(‘c’) are pre defined function which are used to get the index of first and last
occurrence of
the character pointed by c in the given array.
Output:
$ javac output.java
$ java output
1 14 8 15
1. class output
2. {
4. {
5. StringBuffer c = new StringBuffer("Hello");
6. c.delete(0,2);
7. System.out.println(c);
8. }
9. }
a) He
b) Hel
c) lo
d) llo
View Answer
Answer: d
Explanation: delete(0,2) is used to delete the characters from 0 th position to 1 st position.
Output:
$ javac output.java
$ java output
llo
1. class output
2. {
4. {
7. c.append(c1);
8. System.out.println(c);
9. }
10. }
a) Hello
b) World
c) Helloworld
d) Hello World
View Answer
Answer: d
Explanation: append() method of class StringBuffer is used to concatenate the string representation to the end of
invoking string.
Output:
$ javac output.java
$ java output
Hello World
1. class output
2. {
4. {
6. StringBuffer s2 = s1.reverse();
7. System.out.println(s2);
8. }
9. }
a) Hello
b) olleH
c) HelloolleH
d) olleHHello
View Answer
Answer: b
Explanation: reverse() method reverses all characters. It returns the reversed object on which it was called.
Output:
$ javac output.java
$ java output
olleH
1. class output
2. {
3. class output
4. {
6. {
9. {
10. i++;
11. if(Character.isDigit(c[i]))
13. if(Character.isWhitespace(c[i]))
15. if(Character.isUpperCase(c[i]))
17. if(Character.isLowerCase(c[i]))
19. i++;
20. }
21. }
22. }
Answer: c
Explanation: Character.isDigit(c[i]),Character.isUpperCase(c[i]),Character.isWhitespace(c[i]) are the function of
library java.lang they are used to find whether the given character is of specified type or not. They return true or
false i:e Boolean variable.
Output:
$ javac output.java
$ java output
1 is a digit
a is a lower case Letter
This section of our 1000+ Java MCQs focuses on StringBuffer class’s methods of Java Programming Language.
1. Which of these method of class StringBuffer is used to extract a substring from a String object?
a) substring()
b) Substring()
c) SubString()
d) None of the mentioned
View Answer
Answer: a
Explanation: None.
StringBuffer s1 = "one";
StringBuffer s2 = s1.append("two")
a) one
b) two
c) onetwo
d) twoone
View Answer
Answer: c
Explanation: Two strings can be concatenated by using append() method.
Answer: a
Explanation: reverse() method reverses all characters. It returns the reversed object on which it was called.
4. Which of these method of class StringBuffer is used to get the length of sequence of characters?
a) length()
b) capacity()
c) Length()
d) Capacity()
View Answer
Answer: a
Explanation: length()- returns the length of String the StringBuffer would create whereas capacity() returns total
number of characters that can be supported before it is grown.
Answer: d
Explanation: None.
1. class output
2. {
3. public static void main(String args[])
4. {
6. System.out.println(c.length());
7. }
8. }
a) 4
b) 5
c) 6
d) 7
View Answer
Answer: b
Explanation: length() method is used to obtain length of StringBuffer object, length of “Hello” is 5.
Output:
$ javac output.java
$ java output
5
1. class output
2. {
4. {
6. sb.replace(1,3,"Java");
7. System.out.println(sb);
8. }
9. }
a) Hello java
b) Hellojava
c) HJavalo
d) Hjava
View Answer
Answer: c
Explanation: The replace() method replaces the given string from the specified beginIndex and endIndex.
$ javac output.java
$ java output
HJavalo
8. What is the output of this program?
1. class output
2. {
4. {
6. s1.setCharAt(1,'x');
7. System.out.println(s1);
8. }
9. }
a) xello
b) xxxxx
c) Hxllo
d) Hexlo
View Answer
Answer: c
Explanation: None.
Output:
$ javac output.java
$ java output
Hxllo
1. class output
2. {
4. {
7. System.out.println(s1);
8. }
9. }
a) HelloGoodWorld
b) HellGoodoWorld
c) HellGood oWorld
d) Hello Good World
View Answer
Answer: d
Explanation: The insert() method inserts one string into another. It is overloaded to accept values of all simple types,
plus String and Objects. Sting is inserted into invoking object at specified position. “Good ” is inserted in “Hello
World” T index 6 giving “Hello Good World”.
output:
$ javac output.java
$ java output
Hello Good World
1. class output
2. {
4. {
6. s1.insert(1,"Java");
7. System.out.println(s1);
8. }
9. }
a) hello
b) java
c) Hello Java
d) HelloJava
View Answer
Answer: d
Explanation: Insert method will insert string at a specified position
Output:
$ javac output.java
$ java output
HelloJava
This section of our 1000+ Java MCQs focuses on java.lang library of Java Programming Language.
Answer: a
Explanation: None.
Answer: d
Explanation: Number is an abstract class containing subclasses Double, Float, Byte, Short, Integer and Long.
Answer: c
Explanation: None.
5. Which of the following is method of wrapper Float for converting the value of an object into byte?
a) bytevalue()
b) byte byteValue()
c) Bytevalue()
d) Byte Bytevalue().
View Answer
Answer: b
Explanation: None.
6. Which of these methods is used to check for infinitely large and small values?
a) isInfinite()
b) isNaN()
c) Isinfinite()
d) IsNaN()
View Answer
Answer: a
Explanation: isinfinite() method returns true is the value being tested is infinitely large or small in magnitude.
7. Which of the following package stores all the simple data types in java?
a) lang
b) java
c) util
d) java.packages
View Answer
Answer: a
Explanation: None.
1. class isinfinite_output
2. {
4. {
6. boolean x = d.isInfinite();
7. System.out.print(x);
8. }
9. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: c
Explanation: isInfinite() method returns true is the value being tested is infinitely large or small in magnitude. 1/0. is
infinitely large in magnitude hence true is stored in x.
Output:
$ javac isinfinite_output.java
$ java isinfinite_output
true
1. class isNaN_output
2. {
4. {
6. boolean x = d.isNaN();
7. System.out.print(x);
8. }
9. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: d
Explanation: isisNaN() method returns true is the value being tested is a number. 1/0. is infinitely large in magnitude,
which cant not be defined as a number hence false is stored in x.
Output:
$ javac isNaN_output.java
$ java isNaN_output
false
1. class binary
2. {
4. {
6. System.out.print(Integer.toBinaryString(num));
7. }
8. }
a) 1001
b) 10011
c) 11011
d) 10001
View Answer
Answer: d
Explanation: None.
output:
$ javac binary.java
$ java binary
10001
Java Questions & Answers – Java.lang – Integer, Long & Character Wrappers
This section of our 1000+ Java MCQs focuses on Integer, Long & Character wrappers of Java Programming Language.
1. Which of these is a wrapper for data type int?
a) Integer
b) Long
c) Byte
d) Double
View Answer
Answer: a
Explanation: None.
2. Which of the following methods is a method of wrapper Integer for obtaining hash code for the invoking object?
a) int hash()
b) int hashcode()
c) int hashCode()
d) Integer hashcode()
View Answer
Answer: c
Explanation: None.
Answer: d
Explanation: Number is an abstract class containing subclasses Double, Float, Byte, Short, Integer and Long.
Answer: b
Explanation: None.
5. Which of the following is method of wrapper Integer for converting the value of an object into int?
a) bytevalue()
b) int intValue();
c) Bytevalue()
d) Byte Bytevalue()
View Answer
Answer: b
Explanation: None.
Answer: b
Explanation: long longValue() is used to obtain value of invoking object as a long.
1. class Output
2. {
4. {
8. System.out.print(Character.isUpperCase(a[2]));
9. }
10. }
Answer: b
Explanation: Character.isDigit(a[0]) checks for a[0], whether it is a digit or not, since a[0] i:e ‘a’ is a character false is
returned. a[3] is a whitespace hence Character.isWhitespace(a[3]) returns a true. a[2] is an upper case letter i:e ‘A’
hence Character.isUpperCase(a[2]) returns true.
Output:
$ javac Output.java
$ java Output
false true true
1. class Output
2. {
4. {
6. byte x = i.byteValue();
7. System.out.print(x);
8. }
9. }
a) 0
b) 1
c) 256
d) 257
View Answer
Answer: b
Explanation: i.byteValue() method returns the value of wrapper i as a byte value. i is 257, range of byte is 256
therefore i value exceeds byte range by 1 hence 1 is returned and stored in x.
Output:
$ javac Output.java
$ java Output
1
1. class Output
2. {
4. {
6. float x = i.floatValue();
7. System.out.print(x);
8. }
9. }
a) 0
b) 1
c) 257
d) 257.0
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.java
$ java Output
257.0
1. class Output
2. {
4. {
6. System.out.print(i.hashCode());
7. }
8. }
a) 256
b) 256.0
c) 256.00
d) 257.00
View Answer
Answer: a
Explanation: None.
Output:
$ javac Output.java
$ java Output
256
Java Questions & Answers – Java.lang – Void, Process & System Class
This section of our 1000+ Java MCQs focuses on Void, Process & System classes of Java Programming Language.
Answer: a
Explanation: The Void class has one field, TYPE, which holds a reference to the Class object for the type void.
Answer: b
Explanation: Kills the subprocess. The subprocess represented by this Process object is forcibly terminated.
Answer: d
Explanation: Standard output variable ‘out’ is defined in System class. out is usually used in print statement i:e
System.out.print().
Answer: b
Explanation: None.
5. Which of the following is method of System class is used to find how long a program takes to execute?
a) currenttime()
b) currentTime()
c) currentTimeMillis()
d) currenttimeMillis()
View Answer
Answer: c
Explanation: None.
Answer: d
Explanation: System class holds a collection of static methods and variables. The standard input, output and error
output of java run time are stored in the in, out and err variables of System class.
1. class Output
2. {
4. {
6. start = System.currentTimeMillis();
8. end = System.currentTimeMillis();
9. System.out.print(end - start);
10. }
11. }
a) 0
b) 1
c) 1000
d) System Dependent
View Answer
Answer: d
Explanation: end time is the time taken by loop to execute it can be any non zero value depending on the System.
Output:
$ javac Output.java
$ java Output
78
1. class Output
2. {
4. {
7. System.arraycopy(a , 0, b, 0, a.length);
9. }
10. }
a) ABCDEF ABCDEF
b) ABCDEF GHIJKL
c) GHIJKL ABCDEF
d) GHIJKL GHIJKL
View Answer
Answer: a
Explanation: System.arraycopy() is a method of class System which is used to copy a string into another string.
Output:
$ javac Output.java
$ java Output
ABCDEF ABCDEF
2. {
4. {
7. System.arraycopy(a, 2, b, 1, a.length-2);
9. }
10. }
a) ABCDEF GHIJKL
b) ABCDEF GCDEFL
c) GHIJKL ABCDEF
d) GCDEFL GHIJKL
View Answer
Answer: b
Explanation: None.
Output:
$ javac Output.java
$ java Output
ABCDEF GCDEFL
1. class Output
2. {
4. {
7. System.arraycopy(a, 1, b, 3, 0);
9. }
10. }
a) ABCDEF GHIJKL
b) ABCDEF GCDEFL
c) GHIJKL ABCDEF
d) GCDEFL GHIJKL
View Answer
Answer: a
Explanation: Since last parameter of System.arraycopy(a,1,b,3,0) is 0 nothing is copied from array a to array b, hence
b remains as it is.
Output:
$ javac Output.java
$ java Output
ABCDEF GHIJKL
This section of our 1000+ Java MCQs focuses on Object & Math classes of Java Programming Language.
Answer: d
Explanation: The object class class is superclass of all other classes.
2. Which of these method of Object class can generate duplicate copy of the object on which it is called?
a) clone()
b) copy()
c) dublicate()
d) dito()
View Answer
Answer: a
Explanation: None.
Answer: c
Explanation: None.
Answer: a
Explanation: Math class contains all the floating point functions that are used for geometry, trignometry, as well as
several general purpose methods. Example : sin(), cos(), exp(), sqrt() etc.
6. Which of these class encapsulate the run time state of an object or an interface?
a) Class
b) Object
c) Runtime
d) System
View Answer
Answer: a
Explanation: None.
7. What is the value of “d” after this line of code has been executed?
a) 2
b) 3
c) 4
d) 2.5
View Answer
Answer: b
Explanation: The Math.random() method returns a number greater than or equal to 0 and less than 1. so 2.5 will be
greater than or equal to 2.5 and less than 3.5, we can be sure that Math.round() will round that number to 3.
1. class Output
2. {
4. {
5. int x = 3.14;
7. System.out.print(y);
8. }
9. }
a) 0
b) 3
c) 3.0
d) 3.1
View Answer
Answer: b
Explanation: None.
Output:
$ javac Output.java
$ java Output
3
1. class Output
2. {
4. {
5. double x = 3.1;
6. double y = 4.5;
7. double z = Math.max( x, y );
8. System.out.print(z);
9. }
10. }
a) true
b) flase
c) 3.1
d) 4.5
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.java
$ java Output
4.5
1. class Output
2. {
3. public static void main(String args[])
4. {
5. double x = 2.0;
6. double y = 3.0;
7. double z = Math.pow( x, y );
8. System.out.print(z);
9. }
10. }
a) 2.0
b) 4.0
c) 8.0
d) 9.0
View Answer
Answer: c
Explanation: Math.pow(x, y) methods returns value of y to the power x, i:e x ^ y, 2.0 ^ 3.0 = 8.0.
Output:
$ javac Output.java
$ java Output
8.0
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “System Class Advance”.
Answer: c
Explanation: System class methods throw SecurityException.
Answer: a
Explanation: None.
Answer: a
Explanation: load() methods loads the dynamic library whose name is specified.
Answer: c
Explanation: None.
5. Which of these values are returns under the case of normal termination of a program?
a) 0
b) 1
c) 2
d) 3
View Answer
Answer: a
Explanation: None.
1. import java.lang.System;
2. class Output
3. {
5. {
7. start = System.currentTimeMillis();
9. end = System.currentTimeMillis();
11. }
12. }
a) 0
b) 1
c) 1000
d) System Dependent
View Answer
Answer: d
Explanation: End time is the time taken by loop to execute it can be any non zero value depending on the System.
Output:
$ javac Output.java
$ java Output
78
1. import java.lang.System;
2. class Output
3. {
5. {
8. System.arraycopy(a, 0, b, 0, a.length);
10. }
11. }
a) ABCDEF ABCDEF
b) ABCDEF GHIJKL
c) GHIJKL ABCDEF
d) GHIJKL GHIJKL
View Answer
Answer: a
Explanation: System.arraycopy() is a method of class System which is used to copy a string into another string.
Output:
$ javac Output.java
$ java Output
ABCDEF ABCDEF
1. import java.lang.System;
2. class Output
3. {
10. }
11. }
a) ABCDEF ABCDEF
b) ABCDEF GHIJKL
c) ABCDEF GHIABC
d) GHIJKL GHIJKL
View Answer
Answer: c
Explanation: System.arraycopy() is a method of class System which is used to copy a string into another string.
Output:
$ javac Output.java
$ java Output
ABCDEF GHIABC
1. import java.lang.System;
2. class Output
3. {
5. {
10. }
11. }
a) ABCDEF ABCDEF
b) ABCDEF GHIJKL
c) ABCDEF GHIABC
d) ABCDEF GHICDL
View Answer
Answer: d
Explanation: System.arraycopy() is a method of class System which is used to copy a string into another string.
Output:
$ javac Output.java
$ java Output
ABCDEF GHICDL
10. What value will this program return to Java run-time system?
1. import java.lang.System;
2. class Output
3. {
5. {
6. System.exit(5);
7. }
8. }
a) 0
b) 1
c) 4
d) 5
View Answer
Answer: d
Explanation: None.
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Double & Float Wrappers”.
Answer: d
Explanation: Number is an abstract class containing subclasses Double, Float, Byte, Short, Integer and Long.
3. Which of these methods can be used to check whether the given value is a number or not?
a) isNaN()
b) isNumber()
c) checkNaN()
d) checkNumber()
View Answer
Answer: a
Explanation: isNaN() methods returns true if num specified is not a number, otherwise it returns false.
4. Which of these method of Double wrapper can be used to check weather a given value is infinite or not?
a) Infinite()
b) isInfinite()
c) checkInfinite()
d) None of the mentioned
View Answer
Answer: b
Explanation: isInfinite() methods returns true if specified value is an infinite value otherwise it returns false.
Answer: d
Explanation: compareTo() methods compare the specified object to be double, if it is not then ClassCastException is
thrown.
1. class Output
2. {
4. {
6. boolean x = i.isNaN();
7. System.out.print(x);
8. }
9. }
a) true
b) false
c) 0
d) 1
View Answer
Answer: b
Explanation: i.isNaN() method returns returns true if i is not a number and false when i is a number. Here false is
returned because i is a number i:e 257.5.
Output:
$ javac Output.java
$ java Output
false
1. class Output
2. {
4. {
6. byte x = i.byteValue();
7. System.out.print(x);
8. }
9. }
a) 0
b) 1
c) 256
d) 257
View Answer
Answer: b
Explanation: i.byteValue() method returns the value of wrapper i as a byte value. i is 257, range of byte is 256
therefore i value exceeds byte range by 1 hence 1 is returned and stored in x.
Output:
$ javac Output.java
$ java Output
1
1. class Output
2. {
6. int x = i.intValue();
7. System.out.print(x);
8. }
9. }
a) 0
b) 1
c) 256
d) 257
View Answer
Answer: d
Explanation: i.intValue() method returns the value of wrapper i as a Integer. i is 257.578 is double number when
converted to an integer data type its value is 257.
Output:
$ javac Output.java
$ java Output
257
1. class Output
2. {
4. {
6. float x = i.floatValue();
7. System.out.print(x);
8. }
9. }
a) 0
b) 257.0
c) 257.57812
d) 257.578123456789
View Answer
Answer: c
Explanation: floatValue() converts the value of wrapper i into float, since float can measure till 5 places after decimal
hence 257.57812 is stored in floating point variable x.
Output:
$ javac Output.java
$ java Output
257.57812
1. class Output
2. {
4. {
7. try
8. {
9. int x = i.compareTo(y);
10. System.out.print(x);
11. }
12. catch(ClassCastException e)
13. {
14. System.out.print("Exception");
15. }
16. }
17. }
a) 0
b) 1
c) Exception
d) None of the mentioned
View Answer
Answer: b
Explanation: i.compareTo() methods two double values, if they are equal then 0 is returned and if not equal then 1 is
returned, here 257.57812 and 257.578123456789 are not equal hence 1 is returned and stored in x.
Output:
$ javac Output.java
$ java Output
1
This section of our 1000+ Java MCQs focuses on java.io library of Java Programming Language.
1. Which of these packages contain classes and interfaces used for input & output operations of a program?
a) java.util
b) java.lang
c) java.io
d) all of the mentioned
View Answer
Answer: c
Explanation: java.io provides support for input and output operations.
Answer: a
Explanation: None.
Answer: c
Explanation: None.
4. Which of these class is not related to input and output stream in terms of functioning?
a) File
b) Writer
c) InputStream
d) Reader
View Answer
Answer: a
Explanation: A File describes properties of a file, a File object is used to obtain or manipulate the information
associated with a disk file, such as the permissions, time date, and directories path, and to navigate subdirectories.
Answer: c
Explanation: None.
6. Which of these is method for testing whether the specified element is a file or a directory?
a) IsFile()
b) isFile()
c) Isfile()
d) isfile()
View Answer
Answer: b
Explanation: isFile() returns true if called on a file and returns false when called on a directory.
1. import java.io.*;
2. class files
3. {
5. {
7. System.out.print(obj.getName());
8. }
9. }
a) java
b) system
c) java/system
d) /java/system
View Answer
Answer: b
Explanation: obj.getName() returns the name of the file.
Output:
$ javac files.java
$ java files
system
1. import java.io.*;
2. class files
3. {
5. {
7. System.out.print(obj.getAbsolutePath());
8. }
9. }
Answer: d
Explanation: None.
Output:
$ javac files.java
$ java files
\java\system
1. import java.io.*;
2. class files
3. {
5. {
7. System.out.print(obj.canWrite());
9. }
10. }
Answer: d
Explanation: None.
Output:
$ javac files.java
$ java files
false false
2. class files
3. {
5. {
7. System.out.print(obj.getParent());
9. }
10. }
Answer: c
Explanation: getparent() giver the parent directory of the file and isfile() checks weather the present file is a
directory or a file in the disk
Output:
$ javac files.java
$ java files
\java false
This section of our 1000+ Java MCQs focuses on java.io byte streams of Java Programming Language.
1. Which of these classes is used for input and output operation when working with bytes?
a) InputStream
b) Reader
c) Writer
d) All of the mentioned
View Answer
Answer: a
Explanation: InputStream & OutputStream are designed for byte stream. Reader and writer are designed for
character stream.
Answer: c
Explanation: None.
3. Which of these method of InputStream is used to read integer representation of next available byte input?
a) read()
b) scanf()
c) get()
d) getInteger()
View Answer
Answer: a
Explanation: None.
Answer: d
Explanation: Every method of OutputStream returns void and throws an IOExeption in case of errors.
5. Which of these is a method to clear all the data present in output buffers?
a) clear()
b) flush()
c) fflush()
d) close()
View Answer
Answer: b
Explanation: None.
Answer: b
Explanation: write() and print() are the two methods of OutputStream that are used for printing the byte data.
1. import java.io.*;
2. class filesinputoutput
3. {
4. public static void main(String args[])
5. {
7. System.out.print(obj.available());
8. }
9. }
Answer: c
Explanation: obj.available() returns the number of bytes.
Output:
$ javac filesinputoutput.java
$ java filesinputoutput
1422
(Output will be different in your case)
1. import java.io.*;
3. {
5. {
10. {
11. int c;
13. {
14. if(i == 0)
15. {
16. System.out.print((char)c);
17. }
18. }
19. }
20. }
21. }
a) abc
b) ABC
c) ab
d) AB
View Answer
Answer: a
Explanation: None.
Output:
$ javac filesinputoutput.java
$ java filesinputoutput
abc
1. import java.io.*;
3. {
5. {
10. {
11. int c;
13. {
14. if (i == 0)
15. {
16. System.out.print(Character.toUpperCase((char)c));
17. }
18. }
19. }
20. }
21. }
a) abc
b) ABC
c) ab
d) AB
View Answer
Answer: b
Explanation: None.
Output:
$ javac filesinputoutput.java
$ java filesinputoutput
ABC
1. import java.io.*;
3. {
5. {
10. {
11. int c;
13. {
14. if (i == 0)
15. {
16. System.out.print(Character.toUpperCase((char)c));
17. obj2.write(1);
18. }
19. }
20. System.out.print(obj2);
21. }
22. }
23. }
a) AaBaCa
b) ABCaaa
c) AaaBaaCaa
d) AaBaaCaaa
View Answer
Answer: d
Explanation: None.
Output:
$ javac filesinputoutput.java
$ java filesinputoutput
AaBaaCaaa
This section of our 1000+ Java MCQs focuses on character streams of Java Programming Language.
1. Which of these stream contains the classes which can work on character stream?
a) InputStream
b) OutputStream
c) Character Stream
d) All of the mentioned
View Answer
Answer: c
Explanation: InputStream & OutputStream classes under byte stream they are not streams. Character Stream
contains all the classes which can work with Unicode.
Answer: a
Explanation: None.
3. Which of these method of FileReader class is used to read characters from a file?
a) read()
b) scanf()
c) get()
d) getInteger()
View Answer
Answer: a
Explanation: None.
4. Which of these class can be used to implement input stream that uses a character array as the source?
a) BufferedReader
b) FileReader
c) CharArrayReader
d) FileArrayReader
View Answer
Answer: c
Explanation: CharArrayReader is an implementation of an input stream that uses character array as a source. Here
array is the input source.
5. Which of these is a method to clear all the data present in output buffers?
a) clear()
b) flush()
c) fflush()
d) close()
View Answer
Answer: b
Explanation: None.
6. Which of these classes can return more than one character to be returned to input stream?
a) BufferedReader
b) Bufferedwriter
c) PushbachReader
d) CharArrayReader
View Answer
Answer: c
Explanation: PushbackReader class allows one or more characters to be returned to the input stream. This allows
looking ahead in input stream and performing action accordingly.
1. import java.io.*;
2. class filesinputoutput
3. {
5. {
7. System.out.print(obj.available());
8. }
9. }
Answer: c
Explanation: obj.available() returns the number of bytes.
Output:
$ javac filesinputoutput.java
$ java filesinputoutput
1422
(Output will be different in your case)
1. import java.io.*;
2. class Chararrayinput
3. {
5. {
9. obj.getChars(0,length,c,0);
12. int i;
13. try
14. {
16. {
17. System.out.print((char)i);
18. }
19. }
23. e.printStackTrace();
24. }
25. }
26. }
a) abc
b) abcd
c) abcde
d) abcdef
View Answer
Answer: d
Explanation: None.
Output:
$ javac Chararrayinput.java
$ java Chararrayinput
abcdef
1. import java.io.*;
2. class Chararrayinput
3. {
5. {
12. int i;
13. try
14. {
16. {
17. System.out.print((char)i);
18. }
19. }
21. {
23. e.printStackTrace();
24. }
25. }
26. }
a) abc
b) abcd
c) abcde
d) abcdef
View Answer
Answer: a
Explanation: None.
Output:
$ javac Chararrayinput.java
$ java Chararrayinput
abc
1. import java.io.*;
2. class Chararrayinput
3. {
5. {
12. int i;
13. int j;
14. try
15. {
17. {
18. System.out.print((char)i);
19. }
20. }
22. {
24. e.printStackTrace();
25. }
26. }
27. }
a) abc
b) abcd
c) abcde
d) None of the mentioned
View Answer
Answer: d
Explanation: No output is printed. CharArrayReader object input1 contains string “abcdefgh” whereas object input2
contains string “bcde”, when while((i=input1.read())==(j=input2.read())) is executed the starting character of each
object is compared since they are unequal control comes out of loop and nothing is printed on the screen.
Output:
$ javac Chararrayinput.java
$ java Chararrayinput
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Memory Management”.
Answer: d
Explanation: There are only 3 type of memory segment. Stack Segment, Heap Segment and Code Segment.
2. Does code Segment loads the java code?
a) True
b) False
View Answer
Answer: a
Explanation: Code Segment loads compiled java bytecode.Byte code is platform independent.
3. What is JVM?
a) Bootstrap
b) Interpretor
c) Extension
d) Compiler
View Answer
Answer: b
Explanation: JVM is interpretor. It reads .class files which is the byte code generated by compiler line by line and
converts it into native OS code.
Answer: a
Explanation: Bootstrap is a class loader. It loads the classes into memory.
Answer: b
Explanation: Extension loads jar files from lib/ext directory of the JRE.This gives the basic functionality available.
Answer: d
Explanation: Young generation is further classified into Eden space and Survivor space. Old generation is also the
tenured space. Permanent generation is the non heap space.
Answer: c
Explanation: Metaspace is the replacement of PermGen in java 8. It is very similar to PermGen except that it resizes
itself dynamically. Thus, it is unbounded.
Answer: d
Explanation: The permanent generation holds objects which JVM finds convenient to have the garbage collector.
Objects describing classes and methods, as well as the classes and methods themselves are a part of Permanent
generation.
Answer: b
Explanation: When a string is created ; if the string already exists in the pool, the reference of the existing string will
be returned, else a new object is created and its reference is returned.
Answer: a
Explanation: We can import the same package or same class multiple times. Neither compiler nor JVM complains will
complain about it. JVM will internally load the class only once no matter how many times we import the same class
or package.
This section of our 1000+ Java MCQs focuses on Java’s built in exceptions of Java Programming Language.
1. Which of these exceptions handles the situations when illegal argument is used to invoke a method?
a) IllegalException
b) Argument Exception
c) IllegalArgumentException
d) IllegalMethodArgumentExcepetion
View Answer
Answer: c
Explanation: 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
View Answer
Answer: d
Explanation: 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.
Answer: c
Explanation: 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
View Answer
Answer: b
Explanation: If we use null reference anywhere in the code where the value stored in that reference is used then
NullPointerException occurs.
Answer: b
Explanation: Exception class contains all the methods necessary for defining an exception. The class contains the
Throwable class.
1. class exception_handling
2. {
5. try
6. {
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
View Answer
Answer: b
Explanation: When array index goes out of bound then ArrayIndexOutOfBoundsException exception is thrown by the
system.
Output:
$ javac exception_handling.java
$ java exception_handling
123450
1. class exception_handling
2. {
4. {
5. try
6. {
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) Comiplation Error
View Answer
Answer: d
Explanation: 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
1. class exception_handling
2. {
4. {
5. System.out.print("0");
7. }
10. try
11. {
12. throwexception();
13. }
15. {
16. System.out.println("A");
17. }
18. }
19. }
a) A
b) 0
c) 0A
d) Exception
View Answer
Answer: c
Explanation: None.
Output:
$ javac exception_handling.java
$ java exception_handling
0A
1. class exception_handling
2. {
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. {
16. c[8] = 9;
17. }
18. finally
19. {
20. System.out.print("A");
21. }
22.
23. }
25. {
26. System.out.println("B");
27. }
28. }
29. }
a) A
b) B
c) AB
d) BA
View Answer
Answer: c
Explanation: 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
1. class exception_handling
2. {
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. {
17. c[8] = 9;
18. }
19. }
21. {
22. System.out.println("TypeA");
23. }
25. {
26. System.out.println("TypeB");
27. }
28. }
29. }
a) TypeA
b) TypeB
c) 0TypeA
d) 0TypeB
Note: Execution command line: $ java exception_handling one two
View Answer
Answer: c
Explanation: 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
This section of our 1000+ Java MCQs focuses on rounding functions in Java Programming Language.
Answer: a
Explanation: None.
2. Which of these method return a smallest whole number greater than or equal to variable X?
a) double ceil(double X)
b) double floor(double X)
c) double max(double X)
d) double min(double X)
View Answer
Answer: a
Explanation: ceil(double X) returns the smallest whole number greater than or equal to variable X.
3. Which of these method return a largest whole number less than or equal to variable X?
a) double ceil(double X)
b) double floor(double X)
c) double max(double X)
d) double min(double X)
View Answer
Answer: b
Explanation: double floor(double X) returns a largest whole number less than or equal to variable X.
Answer: d
Explanation: rint() rounds up a variable to nearest integer.
5. Which of these class contains only floating point functions?
a) Math
b) Process
c) System
d) Object
View Answer
Answer: a
Explanation: Math class contains all the floating point functions that are used for geometry, trigonometry, as well as
several general purpose methods. Example : sin(), cos(), exp(), sqrt() etc.
Answer: a
Explanation: abs() returns the absolute value of a variable.
1. class A
2. {
3. int x;
4. int y;
5. void display()
6. {
8. }
9. }
11. {
13. {
16. obj1.x = 1;
17. obj1.y = 2;
18. obj2 = obj1.clone();
19. obj1.display();
20. obj2.display();
21. }
22. }
a) 1 2 0 0
b) 1 2 1 2
c) 0 0 0 0
d) System Dependent
View Answer
Answer: b
Explanation: clone() method of object class is used to generate duplicate copy of the object on which it is called.
Copy of obj1 is generated and stored in obj2.
Output:
$ javac Output.java
$ java Output
1212
1. class Output
2. {
4. {
5. double x = 3.14;
7. System.out.print(y);
8. }
9. }
a) 0
b) 3
c) 3.0
d) 3.1
View Answer
Answer: b
Explanation: None.
Output:
$ javac Output.java
$ java Output
3
9. What is the output of this program?
1. class Output
2. {
4. {
5. double x = 3.14;
7. System.out.print(y);
8. }
9. }
a) 0
b) 3
c) 3.0
d) 4
View Answer
Answer: d
Explanation: ciel(double X) returns the smallest whole number greater than or equal to variable x.
Output:
$ javac Output.java
$ java Output
4
1. class Output
2. {
4. {
5. double x = 3.14;
7. System.out.print(y);
8. }
9. }
a) 0
b) 3
c) 3.0
d) 4
View Answer
Answer: d
Explanation: double floor(double X) returns a largest whole number less than or equal to variable X. Here the
smallest whole number less than 3.14 is 3.
Output:
$ javac Output.java
$ java Output
3
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Java.lang – Byte & Short Wrappers”.
1. Which of these methods of Byte wrapper can be used to obtain Byte object from a string?
a) toString()
b) getString()
c) decode()
d) encode()
View Answer
Answer: c
Explanation: decode() methods returns a Byte object that contains the value specified by string.
2. Which of the following methods Byte wrapper return the value as a double?
a) doubleValue()
b) converDouble()
c) getDouble()
d) getDoubleValue()
View Answer
Answer: a
Explanation: doubleValue() returns the value of invoking object as double.
Answer: d
Explanation: Number is an abstract class containing subclasses Double, Float, Byte, Short, Integer and Long.
4. Which of these methods is not defined in both Byte and Short wrappers?
a) intValue()
b) isInfinite()
c) toString()
d) hashCode()
View Answer
Answer: b
Explanation: isInfinite() methods is defined in Integer and Long Wrappers, returns true if specified value is an infinite
value otherwise it returns false.
Answer: d
Explanation: compareTo() methods compare the specified object to be double, if it is not then ClassCastException is
thrown.
1. class Output
2. {
4. {
6. Double x = i.MAX_VALUE;
7. System.out.print(x);
8. }
9. }
a) 0
b) 1.7976931348623157E308
c) 1.7976931348623157E30
d) None of the mentioned
View Answer
Answer: b
Explanation: The super class of Double class defines a constant MAX_VALUE above which a number is considered to
be infinity. MAX_VALUE is 1.7976931348623157E308.
Output:
$ javac Output.java
$ java Output
1.7976931348623157E308
1. class Output
2. {
6. Double x = i.MIN_VALUE;
7. System.out.print(x);
8. }
9. }
a) 0
b) 4.9E-324
c) 1.7976931348623157E308
d) None of the mentioned
View Answer
Answer: b
Explanation: The super class of Byte class defines a constant MIN_VALUE below which a number is considered to be
negative infinity. MIN_VALUE is 4.9E-324.
Output:
$ javac Output.java
$ java Output
4.9E-324
1. class Output
2. {
4. {
6. byte x = i.byteValue();
7. System.out.print(x);
8. }
9. }
a) 0
b) 1
c) 256
d) 257
View Answer
Answer: b
Explanation: i.byteValue() method returns the value of wrapper i as a byte value. i is 257, range of byte is 256
therefore i value exceeds byte range by 1 hence 1 is returned and stored in x.
Output:
$ javac Output.java
$ java Output
1
1. class Output
2. {
4. {
6. float x = i.floatValue();
7. System.out.print(x);
8. }
9. }
a) 0
b) 257.0
c) 257.57812
d) 257.578123456789
View Answer
Answer: c
Explanation: floatValue() converts the value of wrapper i into float, since float can measure till 5 places after decimal
hence 257.57812 is stored in floating point variable x.
Output:
$ javac Output.java
$ java Output
257.57812
1. class Output
2. {
4. {
7. try
8. {
9. int x = i.compareTo(y);
10. System.out.print(x);
11. }
12. catch(ClassCastException e)
13. {
14. System.out.print("Exception");
15. }
16. }
17. }
a) 0
b) 1
c) Exception
d) None of the mentioned
View Answer
Answer: b
Explanation: i.compareTo() methods two double values, if they are equal then 0 is returned and if not equal then 1 is
returned, here 257.57812 and 257.578123456789 are not equal hence 1 is returned and stored in x.
Output:
$ javac Output.java
$ java Output
1
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Character Wrapper Advance”.
1. Which of these methods of Character wrapper can be used to obtain the char value contained in Character object.
a) get()
b) getVhar()
c) charValue()
d) getCharacter()
View Answer
Answer: c
Explanation: To obtain the char value contained in a Character object, we use charValue() method.
Answer: d
Explanation: Character wrapper defines 5 constants – MAX_RADIX, MIN_RADIX, MAX_VALUE, MIN_VALUE & TYPE.
3. Which of these is a super class of Character wrapper?
a) Long
b) Digits
c) Float
d) Number
View Answer
Answer: d
Explanation: Number is an abstract class containing subclasses Double, Float, Byte, Short, Character, Integer and
Long.
4. Which of these methods is used to know whether a given Character object is part of Java’s Identifiers?
a) isIdentifier()
b) isJavaIdentifier()
c) isJavaIdentifierPart()
d) none of the mentioned
View Answer
Answer: c
Explanation: None.
Answer: d
Explanation: isDefined() returns true if ch is defined by Unicode. Otherwise, it returns false.
1. class Output
2. {
4. {
5. int a = Character.MAX_VALUE;
6. System.out.print((char)a);
7. }
8. }
a) <
b) >
c) ?
d) $
View Answer
Answer: c
Explanation: Character.MAX_VALUE returns the largest character value, which is of character ‘?’.
Output:
$ javac Output.java
$ java Output
?
1. class Output
2. {
4. {
5. int a = Character.MIN_VALUE;
6. System.out.print((char)a);
7. }
8. }
a) <
b) !
c) @
d) Space
View Answer
Answer: d
Explanation: Character.MIN_VALUE returns the smallest character value, which is of space character ‘ ‘.
Output:
$ javac Output.java
$ java Output
1. class Output
2. {
4. {
8. System.out.print(Character.isUpperCase(a[2]));
9. }
10. }
Answer: b
Explanation: Character.isDigit(a[0]) checks for a[0], whether it is a digit or not, since a[0] i:e ‘a’ is a character false is
returned. a[3] is a whitespace hence Character.isWhitespace(a[3]) returns a true. a[2] is an upper case letter i:e ‘A’
hence Character.isUpperCase(a[2]) returns true.
Output:
$ javac Output.java
$ java Output
false true true
1. class Output
2. {
4. {
6. a = Character.toUpperCase(a);
7. System.out.print(a);
8. }
9. }
a) b
b) c
c) B
d) C
View Answer
Answer: c
Explanation: None.
Output:
$ javac Output.java
$ java Output
B
1. class Output
2. {
3. public static void main(String args[])
4. {
5. char a = '@';
6. boolean x = Character.isLetter(a);
7. System.out.print(x);
8. }
9. }
a) b
b) c
c) B
d) C
View Answer
Answer: c
Explanation: None.
Output:
$ javac Output.java
$ java Output
B
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Java.lang – Boolean Wrapper Advance”.
Answer: b
Explanation: None.
Answer: d
Explanation: Boolean wrapper defines 3 constants – TRUE, FALSE & TYPE.
Answer: b
Explanation: None.
Answer: a
Explanation: valueOf() returns true if the specified string contains “true” in lower or uppercase and false otherwise.
Answer: d
Explanation: Void class has only one field – TYPE, ehich holds a reference to the Class object for type void. We do not
create instance of this class.
1. class Output
2. {
4. {
6. boolean x = Boolean.valueOf(str);
7. System.out.print(x);
8. }
9. }
a) True
b) False
c) Compilation Error
d) Runtime Error
View Answer
Answer: a
Explanation: valueOf() returns true if the specified string contains “true” in lower or uppercase and false otherwise.
Output:
$ javac Output.java
$ java Output
true
1. class Output
2. {
4. {
6. boolean x = Boolean.valueOf(str);
7. System.out.print(x);
8. }
9. }
a) True
b) False
c) Compilation Error
d) Runtime Error
View Answer
Answer: b
Explanation: valueOf() returns true if the specified string contains “true” in lower or uppercase and false otherwise.
Output:
$ javac Output.java
$ java Output
false
1. class Output
2. {
4. {
6. boolean x = Boolean.valueOf(str);
7. System.out.print(x);
8. }
9. }
a) True
b) False
c) Compilation Error
d) Runtime Error
View Answer
Answer: a
Explanation: 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
1. class Output
2. {
4. {
6. boolean x = Boolean.parseBoolean(str);
7. System.out.print(x);
8. }
9. }
a) True
b) False
c) System Dependent
d) Compilation Error
View Answer
Answer: b
Explanation: 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
1. class Output
2. {
4. {
5. String x = Boolean.toString(false);
6. }
7. }
a) True
b) False
c) System Dependent
d) Compilation Error
View Answer
Answer: b
Explanation: 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
java Questions & Answers – Java.lang – Miscellaneous Math Methods & StrictMath Class
This section of our 1000+ Java MCQs focuses on miscellaneous Math methods & StrictMath class of Java
Programming Language.
1. Which of these class contains all the methods present in Math class?
a) SystemMath
b) StrictMath
c) Compiler
d) ClassLoader
View Answer
Answer: b
Explanation: SystemMath class defines complete set of mathematical methods that are parallel those in Math class.
The difference is that the StrictMath version is guaranteed to generate precisely identical results across all Java
implementations.
Answer: b
Explanation: None.
3. Which of these method returns the remainder of dividend / devisor?
a) remainder()
b) getRemainder()
c) CSIremainder()
d) IEEEremainder()
View Answer
Answer: d
Explanation: IEEEremainder() returns the remainder of dividend / devisor.
Answer: b
Explanation: None.
Answer: c
Explanation: toRadian() and toDegree() methods were added by Java 2.0 before that there was no method which
could directly convert degree into radians and vice versa.
6. Which of these method return a smallest whole number greater than or equal to variable X?
a) double ciel(double X)
b) double floor(double X)
c) double max(double X)
d) double min(double X)
View Answer
Answer: a
Explanation: ciel(double X) returns the smallest whole number greater than or equal to variable X.
1. class Output
2. {
4. {
5. double x = 3.14;
8. }
9. }
a) 0
b) 179
c) 180
d) 360
View Answer
Answer: b
Explanation: 3.14 in degree 179.9087. We usually take it to be 180. Buts here we have type casted it to integer data
type hence 179.
Output:
$ javac Output.java
$ java Output
179
1. class Output
2. {
4. {
5. double x = 3.14;
7. System.out.print(y);
8. }
9. }
a) 0
b) 3
c) 3.0
d) 3.1
View Answer
Answer: a
Explanation: None.
Output:
$ javac Output.java
$ java Output
0
1. class Output
2. {
4. {
5. double x = 102;
6. double y = 5;
8. System.out.print(z);}
9. }
10. }
a) 0
b) 1
c) 2
d) 3
View Answer
Answer: b
Explanation: IEEEremainder() returns the remainder of dividend / devisor. Here dividend is 102 and devisor is 5
therefore remainder is 2. It is similar to modulus – ‘%’ operator of C/C++ language.
Output:
$ javac Output.java
$ java Output
2
1. class Output
2. {
4. {
6. System.out.print(y);
7. }
8. }
a) Yes
b) No
c) Compiler Dependent
d) Operating System Dependent
View Answer
Answer: b
Explanation: There is no relation between random numbers generated previously in Java
This section of our 1000+ Java MCQs focuses Runtime & ClassLoader classes of Java Programming Language.
Answer: c
Explanation: None.
Answer: c
Explanation: Every method of Runtime class throws SecurityException.
3. Which of these methods returns the total number of bytes of memory available to the program?
a) getMemory()
b) TotalMemory()
c) SystemMemory()
d) getProcessMemory()
View Answer
Answer: b
Explanation: TotalMemory() returns the total number of bytes available to the program.
Answer: d
Explanation: None.
Answer: d
Explanation: None.
1. class X
2. {
3. int a;
4. double b;
5. }
6. class Y extends X
7. {
8. int c;
9. }
11. {
13. {
18. System.out.print(obj.getSuperclass());
19. }
20. }
a) X
b) Y
c) class X
d) class Y
View Answer
Answer: c
Explanation: getSuperClass() returns the super class of an object. b is an object of class Y which extends class X ,
Hence Super class of b is X. therefore class X is printed.
Output:
$ javac Output.java
$ java Output
class X
1. class X
2. {
3. int a;
4. double b;
5. }
6. class Y extends X
7. {
8. int c;
9. }
11. {
13. {
18. System.out.print(b.equals(a));
19. }
20. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.java
$ java Output
false
1. class X
2. {
3. int a;
4. double b;
5. }
6. class Y extends X
7. {
8. int c;
9. }
11. {
13. {
18. System.out.print(obj.isInstance(a));
19. }
20. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: d
Explanation: Although class Y extends class X but still a is not considered related to Y. hence isInstance() returns
false.
Output:
$ javac Output.java
$ java Output
false
1. class X
2. {
3. int a;
4. double b;
5. }
6. class Y extends X
7. {
8. int c;
9. }
11. {
13. {
18. System.out.print(obj.isLocalClass());
19. }
20. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.java
$ java Output
false
This section of our 1000+ Java MCQs focuses Class of java.lang library of Java Programming Language.
Answer: a
Explanation: None.
Answer: d
Explanation: Boolean wrapper defines 3 constants – TRUE, FLASE & TYPE.
Answer: a
Explanation: None.
Answer: a
Explanation: valueOf() returns true if the specified string contains “true” in lower or uppercase and false otherwise.
1. class X
2. {
3. int a;
4. double b;
5. }
6. class Y extends X
7. {
8. int c;
9. }
11. {
13. {
18. System.out.print(obj.getName());
19. }
20. }
a) X
b) Y
c) a
d) b
View Answer
Answer: a
Explanation: getClass() is used to obtain the class of an object, here ‘a’ is an object of class ‘X’. hence a.getClass()
returns ‘X’ which is stored in class Class object obj.
Output:
$ javac Output.java
$ java Output
X
1. class X
2. {
3. int a;
4. double b;
5. }
6. class Y extends X
7. {
8. int c;
9. }
11. {
13. {
18. System.out.print(obj.getSuperclass());
19. }
20. }
a) X
b) Y
c) class X
d) class Y
View Answer
Answer: c
Explanation: getSuperClass() returns the super class of an object. b is an object of class Y which extends class X ,
Hence Super class of b is X. therefore class X is printed.
Output:
$ javac Output.java
$ java Output
class X
8. What is the output of this program?
1. class X
2. {
3. int a;
4. double b;
5. }
6. class Y extends X
7. {
8. int c;
9. }
11. {
13. {
18. System.out.print(b.equals(a));
19. }
20. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.java
$ java Output
false
1. class X
2. {
3. int a;
4. double b;
5. }
6. class Y extends X
7. {
8. int c;
9. }
11. {
13. {
18. System.out.print(obj.isInstance(a));
19. }
20. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: d
Explanation: Although class Y extends class X but still a is not considered related to Y. hence isInstance() returns
false.
Output:
$ javac Output.java
$ java Output
false
1. class X
2. {
3. int a;
4. double b;
5. }
6. class Y extends X
7. {
8. int c;
9. }
11. {
13. {
18. System.out.print(obj.isLocalClass());
19. }
20. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.java
$ java Output
false
Java Questions & Answers – Java.lang – ThreadGroup class & Runnable Interface
This set of Java online test focuses on “Java.lang – ThreadGroup class & Runnable Interface”.
1. Which of interface contains all the methods used for handling thread related operations in Java?
a) Runnable interface
b) Math interface
c) System interface
d) ThreadHandling interface
View Answer
Answer: a
Explanation: Runnable interface defines all the methods for handling thread operations in Java.
Answer: c
Explanation: Thread class is used to make threads in java, Thread encapsulates a thread of execution. To create a
new thread the program will either extend Thread or implement the Runnable interface.
Answer: a
Explanation: None.
4. Which of these method of Thread class is used to suspend a thread for a period of time?
a) sleep()
b) terminate()
c) suspend()
d) stop()
View Answer
Answer: a
Explanation: None.
Answer: c
Explanation: toRadian() and toDegree() methods were added by Java 2.0 before that there was no method which
could directly convert degree into radians and vice versa.
2. {
3. Thread t1,t2;
4. newthread()
5. {
6. t1 = new Thread(this,"Thread_1");
7. t2 = new Thread(this,"Thread_2");
8. t1.start();
9. t2.start();
10. }
12. {
13. t2.setPriority(Thread.MAX_PRIORITY);
14. System.out.print(t1.equals(t2));
15. }
16. }
18. {
20. {
22. }
23. }
a) true
b) false
c) truetrue
d) falsefalse
View Answer
Answer: d
Explanation: Threads t1 & t2 are created by class newthread that is implementing runnable interface, hence both the
threads are provided their own run() method specifying the actions to be taken. When constructor of newthread
class is called first the run() method of t1 executes than the run method of t2 printing 2 times “false” as both the
threads are not equal one is having different priority than other, hence falsefalse is printed.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
falsefalse
7. What is the output of this program?
2. {
3. Thread t;
4. newthread()
5. {
7. t.start();
8. }
10. {
11. t.setPriority(Thread.MAX_PRIORITY);
12. System.out.println(t);
13. }
14. }
16. {
18. {
20. }
21. }
a) Thread[New Thread,0,main].
b) Thread[New Thread,1,main].
c) Thread[New Thread,5,main].
d) Thread[New Thread,10,main].
View Answer
Answer: d
Explanation: Thread t has been made with default priority value 5 but in run method the priority has been explicitly
changed to MAX_PRIORITY of class thread, that is 10 by code ‘t.setPriority(Thread.MAX_PRIORITY);’ using the
setPriority function of thread t.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Thread[New Thread,10,main]
8. What is the output of this program?
2. {
3. Thread t;
4. newthread()
5. {
7. t.start();
8. }
9. }
11. {
13. {
15. }
16. }
a) My Thread
b) Thread[My Thread,5,main].
c) Compilation Error
d) Runtime Error
View Answer
Answer: c
Explanation: Thread t has been made by using Runnable interface, hence it is necessary to use inherited abstract
method run() method to specify instructions to be implemented on the thread, since no run() method is used it gives
a compilation error.
Output:
$ javac multithreaded_programing.java
The type newthread must implement the inherited abstract method Runnable.run()
2. {
3. Thread t;
4. newthread()
5. {
7. t.start();
8. }
10. {
11. System.out.println(t.getName());
12. }
13. }
15. {
17. {
19. }
20. }
a) My Thread
b) Thread[My Thread,5,main].
c) Compilation Error
d) Runtime Error
View Answer
Answer: a
Explanation: None.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
My Thread
2. {
3. Thread t;
4. newthread()
5. {
8. }
10. {
11. System.out.println(t);
12. }
13. }
15. {
17. {
19. }
20. }
a) My Thread
b) Thread[My Thread,5,main].
c) Compilation Error
d) Runtime Error
View Answer
Answer: b
Explanation: None.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Thread[My Thread,5,main]
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Environment Properties”.
Answer: c
Explanation: Java application uses ProcessBuilder object to create a new process. By default, same set of
environment variables passed which are set in application’s virtual machine process.
2. Which of the following is true about Java system properties?
a) Java system properties are accessible by any process
b) Java system properties are accessible by processes they are added to
c) Java system properties are retrieved by System.getenv()
d) Java system prooerties are set by System.setenv()
View Answer
Answer: b
Explanation: Java system properties are only used and accessible by the processes they are added.
Answer: a
Explanation: Java system properties can be set at runtime using System.setProperty(name, value) or using
System.getProperties().load() methods.
Answer: c
Explanation: java.home is the installation directory of Java Runtime Environment.
Answer: d
Explanation: System.getProperty(“variable”) returns null value. Because, variable is not a property and if property
does not exist, this method returns null value.
Answer: c
Explanation: The changes made by setProperties method are not persistent. Hence, it does not affect future
invocation.
Answer: d
Explanation: @Autowired
private Environment env;
This is how environment variables are injected in the class where they can be used.
Answer: a
Explanation: @Value are used to inject the properties and assign them to variables.
Answer: b
Explanation: JAVA_HOME is used to store path to the java installation.
Answer: c
Explanation: This method can be used to load files using relative path to the package of the class.
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Serialization – 1”.
Answer: a
Explanation: Serialization is the process of writing the state of an object to a byte stream. This is used when you
want to save the state of your program to persistent storage area.
Answer: a
Explanation: Serialization and deserialization occur automatically by java run time system, Garbage collection also
occur automatically but is done by CPU or the operating system not by the java run time system.
Answer: b
Explanation: None.
Answer: c
Explanation: ObjectOutput interface extends the DataOutput interface and supports object serialization.
5. Which of these is a method of ObjectOutput interface used to finalize the output state so that any buffers are
cleared?
a) clear()
b) flush()
c) fflush()
d) close()
View Answer
Answer: b
Explanation: None.
6. Which of these is method of ObjectOutput interface used to write the object to input or output stream as
required?
a) write()
b) Write()
c) StreamWrite()
d) writeObject()
View Answer
Answer: d
Explanation: writeObject() is used to write an object into invoking stream, it can be input stream or output stream.
1. import java.io.*;
2. class serialization
3. {
5. {
6. try
7. {
11. oos.writeObject(object1);
12. oos.flush();
13. oos.close();
14. }
15. catch(Exception e)
16. {
18. System.exit(0);
19. }
20. try
21. {
27. System.out.println(object2);
28. }
30. {
32. System.exit(0);
33. }
34. }
35. }
37. {
38. String s;
39. int i;
40. double d;
42. {
43. this.d = d;
44. this.i = i;
45. this.s = s;
46. }
47. }
Answer: a
Explanation: None.
Output:
$ javac serialization.java
$ java serialization
s=Hello; i=-7; d=2.1E10
2. class serialization
3. {
5. {
6. try
7. {
11. oos.writeObject(object1);
12. oos.flush();
13. oos.close();
14. }
15. catch(Exception e)
16. {
18. System.exit(0);
19. }
20. try
21. {
22. int x;
25. x = ois.readInt();
26. ois.close();
27. System.out.println(x);
28. }
30. {
31. System.out.print("deserialization");
32. System.exit(0);
33. }
34. }
35. }
37. {
38. String s;
39. int i;
40. double d;
42. {
43. this.d = d;
44. this.i = i;
45. this.s = s;
46. }
47. }
a) -7
b) Hello
c) 2.1E10
d) deserialization
View Answer
Answer: d
Explanation: x = ois.readInt(); will try to read an integer value from the stream ‘serial’ created before, since stream
contains an object of Myclass hence error will occur and it will be catched by catch printing deserialization.
Output:
$ javac serialization.java
$ java serialization
deserialization
1. import java.io.*;
2. class Chararrayinput
3. {
12. int i;
13. int j;
14. try
15. {
17. {
18. System.out.print((char)i);
19. }
20. }
22. {
23. e.printStackTrace();
24. }
25. }
26. }
a) abc
b) abcd
c) abcde
d) None of the mentioned
View Answer
Answer: d
Explanation: No output is printed. CharArrayReader object input1 contains string “abcdefgh” whereas object input2
contains string “bcde”, when while((i=input1.read())==(j=input2.read())) is executed the starting character of each
object is compared since they are unequal control comes out of loop and nothing is printed on the screen.
Output:
$ javac Chararrayinput.java
$ java Chararrayinput
10. What is the output of this program?
1. import java.io.*;
2. class streams
3. {
5. {
6. try
7. {
10. oos.writeFloat(3.5);
11. oos.flush();
12. oos.close();
13. }
14. catch(Exception e)
15. {
17. System.exit(0);
18. }
19. try
20. {
21. float x;
24. x = ois.readInt();
25. ois.close();
26. System.out.println(x);
27. }
29. {
30. System.out.print("deserialization");
31. System.exit(0);
32. }
33. }
34. }
a) 3
b) 3.5
c) serialization
d) deserialization
View Answer
Answer: b
Explanation: oos.writeFloat(3.5); writes in output stream which is extracted by x = ois.readInt(); and stored in x
hence x contains 3.5.
Output:
$ javac streams.java
$ java streams
3.5
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Serialization – 2”.
Answer: b
Explanation: 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
View Answer
Answer: a
Explanation: 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
View Answer
Answer: b
Explanation: Deserialization is the reverse process of serialization which is turning stream of bytes into an object in
memory.
Answer: d
Explanation: Serializable interface does not have any method. It is also called as marker interface.
Answer: c
Explanation: All static and transient variables are not serialized.
Answer: c
Explanation: If member of a class does not implement serialization, NotSerializationException will be thrown.
Answer: b
Explanation: 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()
View Answer
Answer: a
Explanation: 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()
View Answer
Answer: c
Explanation: Using readObject(), writeObject(), readExternal() and writeExternal() methods Serialization and
DeSerialization are implemented.
Answer: a
Explanation: Serialized object can be transfered via network because Java serialized object remains in form of bytes
which can be transmitted over network.
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Serialization & Deserialization”.
Answer: d
Explanation: Deserialization is a process by which the data written in the stream can be extracted out from the
stream.
Answer: d
Explanation: Serialization, deserialization and Memory allocation occur automatically by java run time system.
Answer: b
Explanation: None.
Answer: d
Explanation: ObjectInput interface extends the DataInput interface and supports object serialization.
5. Which of these is a method of ObjectInput interface used to deserialize an object from a stream?
a) int read()
b) void close()
c) Object readObject()
d) Object WriteObject()
View Answer
Answer: c
Explanation: None.
Answer: b
Explanation: ObjectInputStream class extends the InputStream class and implements the ObjectInput interface.
1. import java.io.*;
2. class streams
3. {
5. {
6. try
7. {
11. oos.flush();
12. oos.close();
13. }
14. catch(Exception e)
15. {
17. System.exit(0);
18. }
19. try
20. {
21. int z;
24. z = ois.readInt();
25. ois.close();
26. System.out.println(x);
27. }
29. {
30. System.out.print("deserialization");
31. System.exit(0);
32. }
33. }
34. }
a) 5
b) void
c) serialization
d) deserialization
View Answer
Answer: a
Explanation: oos.writeInt(5); writes integer 5 in the Output stream which is extracted by z = ois.readInt(); and stored
in z hence z contains 5.
Output:
$ javac streams.java
$ java streams
5
1. import java.io.*;
2. class serialization
3. {
5. {
6. try
7. {
11. oos.writeObject(object1);
12. oos.flush();
13. oos.close();
14. }
15. catch(Exception e)
16. {
18. System.exit(0);
19. }
20. try
21. {
22. int x;
25. x = ois.readInt();
26. ois.close();
27. System.out.println(x);
28. }
30. {
31. System.out.print("deserialization");
32. System.exit(0);
33. }
34. }
35. }
37. {
38. String s;
39. int i;
40. double d;
42. {
43. this.d = d;
44. this.i = i;
45. this.s = s;
46. }
47. }
a) -7
b) Hello
c) 2.1E10
d) deserialization
View Answer
Answer: d
Explanation: x = ois.readInt(); will try to read an integer value from the stream ‘serial’ created before, since stream
contains an object of Myclass hence error will occur and it will be catched by catch printing deserialization.
Output:
$ javac serialization.java
$ java serialization
deserialization
2. class streams
3. {
5. {
6. try
7. {
10. oos.writeFloat(3.5);
11. oos.flush();
12. oos.close();
13. }
14. catch(Exception e)
15. {
17. System.exit(0);
18. }
19. try
20. {
23. ois.close();
24. System.out.println(ois.available());
25. }
27. {
28. System.out.print("deserialization");
29. System.exit(0);
30. }
31. }
32. }
a) 1
b) 2
c) 3
d) 0
View Answer
Answer: d
Explanation: New input stream is linked to streal ‘serials’, an object ‘ois’ of ObjectInputStream is used to access this
newly created stream, ois.close(); closes the stream hence we can’t access the stream and ois.available() returns 0.
Output:
$ javac streams.java
$ java streams
0
1. import java.io.*;
2. class streams
3. {
5. {
6. try
7. {
10. oos.writeFloat(3.5);
11. oos.flush();
12. oos.close();
13. }
14. catch(Exception e)
15. {
17. System.exit(0);
18. }
19. try
20. {
23. System.out.println(ois.available());
24. }
26. {
27. System.out.print("deserialization");
28. System.exit(0);
29. }
30. }
31. }
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: d
Explanation: oos.writeFloat(3.5); writes 3.5 in output stream. A new input stream is linked to stream ‘serials’, an
object ‘ois’ of ObjectInputStream is used to access this newly created stream, ois.available() gives the total number
of byte in the input stream since a float was written in the stream thus the stream contains 4 byte, hence 4 is
returned and printed.
Output:
$ javac streams.java
$ java streams
4
11. What will be printed to the output and written to the file, in the below program?
1. import java.io.FileOutputStream;
3. {
5. {
6. try
7. {
11. fout.write(b);
12. fout.close();
13. System.out.println("Success");
15. }
16. }
Answer: a
Explanation: First, it will print “Success” and besides that it will write “Welcome to Sanfoundry” to the file
sanfoundry.txt.
This section of our 1000+ Java MCQs focuses on networking basics of Java Programming Language.
Answer: c
Explanation: None.
2. Which of these is a protocol for breaking and sending packets to an address across a network?
a) TCIP/IP
b) DNS
c) Socket
d) Proxy Server
View Answer
Answer: a
Explanation: TCP/IP – Transfer control protocol/Internet Protocol is used to break data into small packets an send
them to an address across a network.
Answer: b
Explanation: None.
Answer: c
Explanation: None.
Answer: d
Explanation: None.
Answer: c
Explanation: InetAddress class encapsulate both IP address and DNS, we can interact with this class by using name of
an IP host.
1. import java.net.*;
2. class networking
3. {
5. {
8. boolean x = obj1.equals(obj2);
9. System.out.print(x);
10. }
11. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: c
Explanation: None.
Output:
$ javac networking.java
$ java networking
true
1. import java.net.*;
2. class networking
3. {
5. {
8. boolean x = obj1.equals(obj2);
9. System.out.print(x);
10. }
11. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: d
Explanation: InetAddress obj1 = InetAddress.getByName(“cisco.com”); creates object obj1 having DNS and IP
address of cisco.com, InetAddress obj2 = InetAddress.getByName(“sanfoundry.com”); creates obj2 having DNS and
IP address of sanfoundry.com , since both these address point to two different locations false is returned by
obj1.equals(obj2);.
Output:
$ javac networking.java
$ java networking
true
1. import java.io.*;
2. import java.net.*;
4. {
6. {
7. try
8. {
14. }
15. }
a) Protocol: http
b) Host Name: www.sanfoundry.com
c) Port Number: -1
d) all above mentioned
View Answer
Answer: d
Explanation: getProtocol() give protocol which is http
getUrl() give name domain name
getPort() Since we have not explicitly set the port, default value that is -1 is printed.
1. import java.net.*;
2. class networking
3. {
5. {
6. InetAddress obj1 = InetAddress.getByName("cisco.com");
7. System.out.print(obj1.getHostName());
8. }
9. }
a) cisco
b) cisco.com
c) www.cisco.com
d) none of the mentioned
View Answer
Answer: b
Explanation: None.
Output:
$ javac networking.java
$ java networking
cisco.com
Java Questions & Answers – Networking – Server, Sockets & httpd Class
This set of Basic Java Questions and Answers focuses on “Nnetworking – Server, Sockets & httpd Class”.
Answer: a
Explanation: LogMessage is a simple interface that is used to abstract the output of messages from the httpd.
2. Which of these class is used to create servers that listen for either local or remote client programs?
a) httpServer
b) ServerSockets
c) MimeHeader
d) HttpResponse
View Answer
Answer: b
Explanation: None.
Answer: a
Explanation: None.
5. Which of these class is used for operating on request from the client to the server?
a) http
b) httpDecoder
c) httpConnection
d) httpd
View Answer
Answer: d
Explanation: None.
6. Which of these method of MimeHeader is used to return the string equivalent of the values stores on
MimeHeader?
a) string()
b) toString()
c) convertString()
d) getString()
View Answer
Answer:b
Explanation: toString() does the reverse of parse() method, it is used to return the string equivalent of the values
stores on MimeHeader.
1. import java.net.*;
2. class networking
3. {
5. {
8. System.out.print(obj1.getContentType());
9. }
10. }
Answer: d
Explanation: None.
Output:
$ javac networking.java
$ java networking
text/html
Answer: d
Explanation: There are 5 instance variables : port, docRoot, log, cache and stopFlag. All of them are private.
1. import java.net.*;
2. class networking
3. {
5. {
7. System.out.print(obj.toExternalForm());
8. }
9. }
a) sanfoundry
b) sanfoundry.com
c) www.sanfoundry.com
d) https://www.sanfoundry.com/javamcq
View Answer
Answer: d
Explanation: toExternalForm() is used to know the full URL of an URL object.
Output:
$ javac networking.java
$ java networking
https://www.sanfoundry.com/javamcq
This section of our 1000+ Java MCQs focuses on httpd.java of Java Programming Language.
1. Which of these methods of httpd class is used to read data from the stream?
a) getDta()
b) GetResponse()
c) getStream()
d) getRawRequest()
View Answer
Answer: d
Explanation: The getRawRequest() method reads data from a stream until it gets two consecutive newline
characters.
2. Which of these method of httpd class is used to get report on each hit to HTTP server?
a) log()
b) logEntry()
c) logHttpd()
d) logResponse()
View Answer
Answer: b
Explanation: None.
3. Which of these method is used to find a URL from the cache of httpd?
a) findfromCache()
b) findFromCache()
c) serveFromCache()
d) getFromCache()
View Answer
Answer: c
Explanation: serveFromCatche() is a boolean method that attempts to find a particular URL in the cache. If it is
successful then the content of that cache entry are written to the client, otherwise it returns false.
4. Which of these variables stores the number of hits that are successfully served out of cache?
a) hits
b) hitstocache
c) hits_to_cache
d) hits.to.cache
View Answer
Answer: d
Explanation: None.
5. Which of these class is used for operating on request from the client to the server?
a) http
b) httpDecoder
c) httpConnection
d) httpd
View Answer
Answer: d
Explanation: None.
6. Which of these method of httpd class is used to write UrlCacheEntry object into local disk?
a) writeDiskCache()
b) writetoDisk()
c) writeCache()
d) writeDiskEntry()
View Answer
Answer: a
Explanation: The writeDiskCache() method takes an UrlCacheEntry object and writes it persistently into the local
disk. It constructs directory names out of URL, making sure to replace the slash(/) characters with system dependent
seperatorChar.
1. import java.net.*;
2. class networking
3. {
5. {
9. System.out.print(len);
10. }
11. }
Answer: b
Explanation: None.
Output:
$ javac networking.java
$ java networking
127
Answer: a
Explanation: run() method is caleed when the server thread is started.
9. Which of these method is called when http daemon is acting like a normal web server?
a) Handle()
b) HandleGet()
c) handleGet()
d) Handleget()
View Answer
Answer: c
Explanation: None.
1. import java.net.*;
2. class networking
3. {
5. {
7. System.out.print(obj1.getHostName());
8. }
9. }
a) cisco
b) cisco.com
c) www.cisco.com
d) none of the mentioned
View Answer
Answer: b
Explanation: None.
Output:
$ javac networking.java
$ java networking
cisco.com
Java Questions & Answers – URL Class
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “URL Class”.
Answer: a
Explanation: URL is Uniform Resource Locator.
Answer: c
Explanation: None.
Answer: b
Explanation: None.
4. Which of these methods is used to know the full URL of an URL object?
a) fullHost()
b) getHost()
c) ExternalForm()
d) toExternalForm()
View Answer
Answer: d
Explanation: None.
5. Which of these class is used to access actual bits or content information of a URL?
a) URL
b) URLDecoder
c) URLConnection
d) All of the mentioned
View Answer
Answer: d
Explanation: URL, URLDecoder and URLConnection all there are used to access information stored in a URL.
6. Which of these class is used to encapsulate IP address and DNS?
a) DatagramPacket
b) URL
c) InetAddress
d) ContentHandler
View Answer
Answer: c
Explanation: InetAddress class encapsulate both IP address and DNS, we can interact with this class by using name of
an IP host.
1. import java.net.*;
2. class networking
3. {
5. {
7. System.out.print(obj.getProtocol());
8. }
9. }
a) http
b) https
c) www
d) com
View Answer
Answer: a
Explanation: obj.getProtocol() is used to know the protocol used by the host. http stands for hyper text transfer
protocol, usually 2 types of protocols are used http and https, where s in https stands for secured.
Output:
$ javac networking.java
$ java networking
http
1. import java.net.*;
2. class networking
3. {
5. {
6. URL obj = new URL("https://www.sanfoundry.com/javamcq");
7. System.out.print(obj.getPort());
8. }
9. }
a) 1
b) 0
c) -1
d) garbage value
View Answer
Answer: c
Explanation: Since we have not explicitly set the port default value that is -1 is printed.
Output:
$ javac networking.java
$ java networking
-1
1. import java.net.*;
2. class networking
3. {
5. {
7. System.out.print(obj.getHost());
8. }
9. }
a) sanfoundry
b) sanfoundry.com
c) www.sanfoundry.com
d) https://www.sanfoundry.com/javamcq
View Answer
Answer: c
Explanation: None.
Output:
$ javac networking.java
$ java networking
www.sanfoundry.com
2. class networking
3. {
5. {
7. System.out.print(obj.toExternalForm());
8. }
9. }
a) sanfoundry
b) sanfoundry.com
c) www.sanfoundry.com
d) https://www.sanfoundry.com/javamcq
View Answer
Answer: d
Explanation: toExternalForm() is used to know the full URL of an URL object.
Output:
$ javac networking.java
$ java networking
https://www.sanfoundry.com/javamcq
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “HttpResponse & URLConnection Class”.
1. Which of these is wrapper around everything associated with a reply from an http server?
a) HTTP
b) HttpResponse
c) HttpRequest
d) httpserver
View Answer
Answer: b
Explanation: HttpResponse is wrapper around everything associated with a reply from an http server.
2. Which of these tranfer protocol must be used so that URL can be accessed by URLConnection class object?
a) http
b) https
c) Any Protocol can be used
d) None of the mentioned
View Answer
Answer: a
Explanation: for a URL to be accessed from remote location http protocol must be used.
3. Which of these methods is used to know when was the URL last modified?
a) LastModified()
b) getLastModified()
c) GetLastModified()
d) getlastModified()()
View Answer
Answer: b
Explanation: None.
4. Which of these methods is used to know the type of content used in the URL?
a) ContentType()
b) contentType()
c) getContentType()
d) GetContentType()
View Answer
Answer: c
Explanation: None.
5. Which of these class is used to access actual bits or content information of a URL?
a) URL
b) URLDecoder
c) URLConnection
d) All of the mentioned
View Answer
Answer: d
Explanation: URL, URLDecoder and URLConnection all there are used to access information stored in a URL.
6. Which of these data member of HttpResponse class is used to store the response from a http server?
a) status
b) address
c) statusResponse
d) statusCode
View Answer
Answer: d
Explanation: When we send a request to a http server it respond with a status code this status code is stored in
statusCode and a textual equivalent which is stored in reasonPhrase.
1. import java.net.*;
2. class networking
3. {
5. {
8. System.out.print(obj1.getContentType());
9. }
10. }
Answer: d
Explanation: None.
Output:
$ javac networking.java
$ java networking
text/html
1. import java.net.*;
2. class networking
3. {
5. {
9. System.out.print(len);
10. }
11. }
Answer: b
Explanation: None.
Output:
$ javac networking.java
$ java networking
127
1. import java.net.*;
2. class networking
3. {
5. {
8. System.out.print(obj1.getLastModified);
9. }
10. }
Answer: d
Explanation: None.
Output:
$ javac networking.java
$ java networking
Tue Jun 18 2013
1. import java.net.*;
2. class networking
3. {
5. {
7. System.out.print(obj.toExternalForm());
8. }
9. }
a) sanfoundry
b) sanfoundry.com
c) www.sanfoundry.com
d) https://www.sanfoundry.com/javamcq
View Answer
Answer: d
Explanation: toExternalForm() is used to know the full URL of an URL object.
Output:
$ javac networking.java
$ java networking
https://www.sanfoundry.com/javamcq
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Networking – Datagrams”.
Answer: c
Explanation: The Datagrams are the bundle of information passed between machines.
Answer: c
Explanation: None.
Answer: b
Explanation: 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()
View Answer
Answer: a
Explanation: None.
5. Which of these method of DatagramPacket is used to find the length of byte array?
a) getnumber()
b) length()
c) Length()
d) getLength()
View Answer
Answer: d
Explanation: 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 datatgram packets over a connection?
a) InetAdress
b) DatagramPacket
c) DatagramSocket
d) All of the mentioned
View Answer
Answer: d
Explanation: 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()
View Answer
Answer: b
Explanation: None.
Answer: c
Explanation: 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
View Answer
Answer: a
Explanation: getSocketAddress() is used to get the socket address
This section of our 1000+ Java MCQs focuses on ArrayList class of Java Programming Language.
Answer: c
Explanation: ArrayList class implements a dynamic array by extending AbstractList class.
2. Which of these class can generate an array which can increase and decrease in size automatically?
a) ArrayList()
b) DynamicList()
c) LinkedList()
d) MallocList()
View Answer
Answer: a
Explanation: None.
3. Which of these method can be used to increase the capacity of ArrayList object manually?
a) Capacity()
b) increaseCapacity()
c) increasecapacity()
d) ensureCapacity()
View Answer
Answer: d
Explanation: When we add an element, the capacity of ArrayList object increases automatically, but we can increase
it manually to specified length x by using function ensureCapacity(x);
4. Which of these method of ArrayList class is used to obtain present size of an object?
a) size()
b) length()
c) index()
d) capacity()
View Answer
Answer: a
Explanation: None.
5. Which of these methods can be used to obtain a static array from an ArrayList object?
a) Array()
b) covertArray()
c) toArray()
d) covertoArray()
View Answer
Answer: c
Explanation: None.
Answer: d
Explanation: trimTosize() is used to reduce the size of the array that underlines an ArrayList object.
1. import java.util.*;
2. class Arraylist
3. {
5. {
7. obj.add("A");
8. obj.add("B");
9. obj.add("C");
11. System.out.println(obj);
12. }
13. }
a) [A, B, C, D].
b) [A, D, B, C].
c) [A, D, C].
d) [A, B, C].
View Answer
Answer: b
Explanation: obj is an object of class ArrayList hence it is an dynamic array which can increase and decrease its size.
obj.add(“X”) adds to the array element X and obj.add(1,”X”) adds element x at index position 1 in the list, Hence
obj.add(1,”D”) stores D at index position 1 of obj and shifts the previous value stored at that position by 1.
Output:
$ javac Arraylist.java
$ java Arraylist
[A, D, B, C].
1. import java.util.*;
2. class Output
3. {
5. {
7. obj.add("A");
8. obj.add(0, "B");
9. System.out.println(obj.size());
10. }
11. }
a) 0
b) 1
c) 2
d) Any Garbage Value
View Answer
Answer: c
Explanation: None.
Output:
$ javac Output.java
$ java Output
2
1. import java.util.*;
2. class Output
3. {
5. {
7. obj.add("A");
8. obj.ensureCapacity(3);
9. System.out.println(obj.size());
10. }
11. }
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: a
Explanation: Although obj.ensureCapacity(3); has manually increased the capacity of obj to 3 but the value is stored
only at index 0, therefore obj.size() returns the total number of elements stored in the obj i:e 1, it has nothing to do
with ensureCapacity().
Output:
$ javac Output.java
$ java Output
1
1. class Output
2. {
4. {
6. obj.add("A");
7. obj.add("D");
8. obj.ensureCapacity(3);
9. obj.trimToSize();
10. System.out.println(obj.size());
11. }
12. }
a) 1
b) 2
c) 3
d) 4
View Answer
Answer: b
Explanation: trimTosize() is used to reduce the size of the array that underlines an ArrayList object.
Output:
$ javac Output.java
$ java Output
2
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Data Structures-HashMap”.
Answer: b
Explanation: Collection interface provides add, remove, search or iterate while map has clear, get, put, remove, etc.
Answer: d
Explanation: Vector implements AbstractList which internally implements Collection. Others come from
implementing Map interface.
Answer: a
Explanation: IdentityHashMap is rarely used as it violates the basic contract of implementing equals() and hashcode()
method.
Answer: a
Explanation: HashMap always contains unique keys. If same key is inserted again, the new object replaces the
previous object.
5. While finding correct location for saving key value pair, how many times key is hashed?
a) 1
b) 2
c) 3
d) unlimited till bucket is found
View Answer
Answer: b
Explanation: The key is hashed twice; first by hashCode() of Object class and then by internal hashing method of
HashMap class.
Answer: b
Explanation: Hashmap outputs in the order of hashcode of the keys. So it is unordered but will always have same
result for same set of keys.
7. If two threads access the same hashmap at the same time, what would happen?
a) ConcurrentModificationException
b) NullPointerException
c) ClassNotFoundException
d) RuntimeException
View Answer
Answer: a
Explanation: The code will throw ConcurrentModificationException if two threads access the same hashmap at the
same time.
Answer: c
Explanation: Collections.synchronizedMap() synchronizes entire map. ConcurrentHashMap provides thread safety
without synchronizing entire map.
2. {
4. {
6. sampleMap.put(1, null);
7. sampleMap.put(5, null);
8. sampleMap.put(3, null);
9. sampleMap.put(2, null);
11.
12. System.out.println(sampleMap);
13. }
14. }
Answer: a
Explanation: HashMap needs unique keys. TreeMap sorts the keys while storing objects.
10. If large number of items are stored in hash bucket, what happens to the internal structure?
a) The bucket will switch from LinkedList to BalancedTree
b) The bucket will increase its size by a factor of load size defined
c) The LinkedList will be replaced by another hashmap
d) Any further addition throws Overflow exception
View Answer
Answer: a
Explanation: BalancedTree will improve performance from O(n) to O(log n) by reducing hash collisions.
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Data Structures-List”.
Answer: c
Explanation. There are 2 ways to remove an object from ArrayList. We can use overloaded method remove(int index)
or remove(Object obj). We can also use an Iterator to remove the object.
Answer: b
Explanation: Collections provides a method to sort the list. The order of sorting can be defined using Comparator.
4. When two threads access the same ArrayList object what is the outcome of program?
a) Both are able to access the object
b) ConcurrentModificationException is thrown
c) One thread is able to access the object and second thread hets NullPointer exception
d) One thread is able to access the object and second thread will wait till control is passed to second one
View Answer
Answer: b
Explanation: ArrayList is not synchronized. Vector is the synchronized data structure.
Answer: c
Explanation: List returned by Arrays.asList() is a fixed length list which doesn’t allow us to add or remove element
from it.add() and remove() method will throw UnSupportedOperationException if used.
Answer: d
Explanation: length() returns the capacity of ArrayList and size() returns the actual number of elements stored in the
list which is always less than or equal to capacity.
Answer: d
Explanation: SessionList is not an implementation of List interface. The others are concrete classes of List.
Answer: b
Explanation: ArrayList has O(1) complexity for accessing an element in ArrayList. O(n) is the complexity for accessing
an element from LinkedList.
10. When an array is passed to a method, will the content of the array undergo changes with the actions carried
within the function?
a) True
b) False
View Answer
Answer: a
Explanation: If we make a copy of array before any changes to the array the content will not change. Else the content
of the array will undergo changes.
2. {
3. if(myArray == null)
4. {
6. }
7. else
8. {
10. }
11. }
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Data Structures-Set”.
Answer: b
Explanation: Default clone() method uses shallow copy. The internal elements are not cloned. A shallow copy only
copies the reference object.
Answer: b
Explanation: get(Object o) method is useful when we want to compare objects based on comparision of values.
HashSet does not provide any way to compare objects. It just gurantees unique objects stored in the collection.
Answer: a
Explanation: Immutable Set is useful in multithreaded environment. One does not need to declare generic type
collection. It is inferred by the context of method call.
Answer: c
Explanation: We should not set the initial capacity too high and load factor too low if iteration performance is
needed.
Answer: a
Explanation: HashSet is implemented to provide uniqueness feature which is not provided by HashMap. This also
reduces code duplication and provides the memory efficient behavior of HashMap.
2. {
4. {
6. s.add(new Long(10));
7. s.add(new Integer(10));
8. for(Object object : s)
9. {
11. }
12. }
13. }
a) Test – 10
Test – 10
b) Test – 10
c) Runtime Exception
d) Compilation Failure
View Answer
Answer: a
Explanation: Integer and Long are two different datatyoes and different objects. So they will be treated as unique
elements and not overridden.
Answer: a
Explanation: Set has contains(Object o) method instead of get(Object o) method as get is needed for comparing
object and getting corresponding value.
8. What is the difference between TreeSet and SortedSet?
a) TreeSet is more efficient than SortedSet
b) SortedSet is more efficient than TreeSet
c) TreeSet is an interface; SortedSet is a concrete class
d) SortedSet is an interface; TreeSet is a concrete class
View Answer
Answer: d
Explanation: SortedSet is an interface. It maintains an ordered set of elements. TreeSet is an implementation of
SortedSet.
Answer: a
Explanation: TreeSet provides fail-fast iterator. Hence when concurrently modifying TreeSet it throws
ConcurrentModificationException.
Answer: b
Explanation: Set is a collection of unique elements.HashSet has the behavior of Set and stores key value pairs. The
LinkedHashSet stores the key value pairs in the order of insertion.
Java Questions & Answers – Java.util – LinkedList, HashSet & TreeSet Class
This set of Java online quiz focuses on “Java.util – LinkedList, HashSet & TreeSet Class”.
1. Which of these standard collection classes implements a linked list data structure?
a) AbstractList
b) LinkedList
c) HashSet
d) AbstractSet
View Answer
Answer: b
Explanation: None.
3. Which of these method is used to add an element to the start of a LinkedList object?
a) add()
b) first()
c) AddFirst()
d) addFirst()
View Answer
Answer: d
Explanation: None.
4. Which of these method of HashSet class is used to add elements to its object?
a) add()
b) Add()
c) addFirst()
d) insert()
View Answer
Answer: a
Explanation: None.
5. Which of these methods can be used to delete the last element in a LinkedList object?
a) remove()
b) delete()
c) removeLast()
d) deleteLast()
View Answer
Answer: c
Explanation: removeLast() and removeFirst() methods are used to remove elements in end and beginning of a linked
list.
Answer: b
Explanation: An element in a LinkedList object can be changed by first using get() to obtain the index or location of
that object and the passing that location to method set() along with its new value.
1. import java.util.*;
2. class Linkedlist
3. {
4. public static void main(String args[])
5. {
7. obj.add("A");
8. obj.add("B");
9. obj.add("C");
10. obj.addFirst("D");
11. System.out.println(obj);
12. }
13. }
a) [A, B, C].
b) [D, B, C].
c) [A, B, C, D].
d) [D, A, B, C].
View Answer
Answer: d
Explanation: obj.addFirst(“D”) method is used to add ‘D’ to the start of a LinkedList object obj.
Output:
$ javac Linkedlist.java
$ java Linkedlist
[D, A, B, C].
1. import java.util.*;
2. class Linkedlist
3. {
5. {
7. obj.add("A");
8. obj.add("B");
9. obj.add("C");
10. obj.removeFirst();
11. System.out.println(obj);
12. }
13. }
a) [A, B].
b) [B, C].
c) [A, B, C, D].
d) [A, B, C].
View Answer
Answer: b
Explanation: None.
Output:
$ javac Linkedlist.java
$ java Linkedlist
[B, C]
1. import java.util.*;
2. class Output
3. {
5. {
7. obj.add("A");
8. obj.add("B");
9. obj.add("C");
11. }
12. }
a) ABC 3
b) [A, B, C] 3
c) ABC 2
d) [A, B, C] 2
View Answer
Answer: b
Explanation: HashSet obj creates an hash object which implements Set interface, obj.size() gives the number of
elements stored in the object obj which in this case is 3.
Output:
$ javac Output.java
$ java Output
[A, B, C] 3
2. class Output
3. {
5. {
7. t.add("3");
8. t.add("9");
9. t.add("1");
10. t.add("4");
11. t.add("8");
12. System.out.println(t);
13. }
14. }
a) [1, 3, 5, 8, 9].
b) [3, 4, 1, 8, 9].
c) [9, 8, 4, 3, 1].
d) [1, 3, 4, 8, 9].
View Answer
Answer: d
Explanation:TreeSet class uses set to store the values added by function add in ascending order using tree for
storage
Output:
$ javac Output.java
$ java Output
[1, 3, 4, 8, 9].
This section of our 1000+ Java MCQs focuses on Maps of Java Programming Language.
Answer: b
Explanation: None.
2. Which of these classes provide implementation of map interface?
a) ArrayList
b) HashMap
c) LinkedList
d) DynamicList
View Answer
Answer: b
Explanation: AbstractMap, WeakHashMap, HashMap and TreeMap provide implementation of map interface.
3. Which of these method is used to remove all keys/values pair from the invoking map?
a) delete()
b) remove()
c) clear()
d) removeAll()
View Answer
Answer: b
Explanation: None.
4. Which of these method Map class is used to obtain an element in the map having specified key?
a) search()
b) get()
c) set()
d) look()
View Answer
Answer: b
Explanation: None.
5. Which of these methods can be used to obtain set of all keys in a map?
a) getAll()
b) getKeys()
c) keyall()
d) keySet()
View Answer
Answer: d
Explanation: keySet() methods is used to get a set containing all the keys used in a map. This method provides set
view of the keys in the invoking map.
6. Which of these method is used add an element and corresponding key to a map?
a) put()
b) set()
c) redo()
d) add()
View Answer
Answer: a
Explanation: Maps revolve around two basic operations – get() and put(). to put a value into a map, use put(),
specifying the key and the value. To obtain a value, call get() , passing the key as an argument. The value is returned.
2. class Maps
3. {
5. {
10. System.out.println(obj);
11. }
12. }
a) {A 1, B 1, C 1}
b) {A, B, C}
c) {A-1, B-1, C-1}
d) {A=1, B=2, C=3}
View Answer
Answer: d
Explanation: None.
Output:
$ javac Maps.java
$ java Maps
{A=1, B=2, C=3}
1. import java.util.*;
2. class Maps
3. {
5. {
10. System.out.println(obj.keySet());
11. }
12. }
a) [A, B, C].
b) {A, B, C}
c) {1, 2, 3}
d) [1, 2, 3].
View Answer
Answer: a
Explanation: keySet() method returns a set containing all the keys used in the invoking map. Here keys are characters
A, B & C. 1, 2, 3 are the values given to these keys.
Output:
$ javac Maps.java
$ java Maps
[A, B, C].
1. import java.util.*;
2. class Maps
3. {
5. {
10. System.out.println(obj.get("B"));
11. }
12. }
a) 1
b) 2
c) 3
d) null
View Answer
Answer: b
Explanation: obj.get(“B”) method is used to obtain the value associated with key “B”, which is 2.
Output:
$ javac Maps.java
$ java Maps
2
10. What is the output of this program?
1. import java.util.*;
2. class Maps
3. {
5. {
10. System.out.println(obj.entrySet());
11. }
12. }
a) [A, B, C].
b) [1, 2, 3].
c) {A=1, B=2, C=3}
d) [A=1, B=2, C=3].
View Answer
Answer: d
Explanation: obj.entrySet() method is used to obtain a set that contains the entries in the map. This method provides
set view of the invoking map.
Output:
$ javac Maps.java
$ java Maps
[A=1, B=2, C=3].
This section of our 1000+ Java MCQs focuses on Vectors & Stack of Java Programming Language.
Answer: d
Explanation: Vectors are dynamic arrays, it contains many legacy methods that are not part of collection framework,
and hence these methods are not present in ArrayList. But both are used to form dynamic arrays.
2. Which of these are legacy classes?
a) Stack
b) Hashtable
c) Vector
d) All of the mentioned
View Answer
Answer: d
Explanation: Stack, Hashtable, Vector, Properties and Dictionary are legacy classes.
Answer: b
Explanation: None.
4. What is the name of data member of class Vector which is used to store number of elements in the vector?
a) length
b) elements
c) elementCount
d) capacity
View Answer
Answer: c
Explanation: None.
Answer: d
Explanation: addElement() is used to add data in the vector, to obtain the data we use elementAt() and to first and
last element we use firstElement() and lastElement() respectively.
1. import java.util.*;
2. class vector
3. {
5. {
8. obj.addElement(new Integer(2));
9. obj.addElement(new Integer(5));
10. System.out.println(obj.elementAt(1));
11. }
12. }
a) 0
b) 3
c) 2
d) 5
View Answer
Answer: c
Explanation: obj.elementAt(1) returns the value stored at index 1, which is 2.
Output:
$ javac vector.java
$ java vector
2
1. import java.util.*;
2. class vector
3. {
5. {
7. obj.addElement(new Integer(3));
8. obj.addElement(new Integer(2));
9. obj.addElement(new Integer(5));
10. System.out.println(obj.capacity());
11. }
12. }
a) 2
b) 3
c) 4
d) 6
View Answer
Answer: c
Explanation: None.
Output:
$ javac vector.java
$ java vector
4
1. import java.util.*;
2. class vector
3. {
5. {
7. obj.addElement(new Integer(3));
8. obj.addElement(new Integer(2));
9. obj.addElement(new Integer(6));
11. System.out.println(obj);
12. }
13. }
a) [3, 2, 6].
b) [3, 2, 8].
c) [3, 2, 6, 8].
d) [3, 2, 8, 6].
View Answer
Answer: d
Explanation: None.
Output:
$ javac vector.java
$ java vector
[3, 2, 8, 6].
1. import java.util.*;
2. class vector
3. {
7. obj.addElement(new Integer(3));
8. obj.addElement(new Integer(2));
9. obj.addElement(new Integer(5));
10. obj.removeAll(obj);
11. System.out.println(obj.isEmpty());
12. }
13. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: c
Explanation: firstly elements 3, 2, 5 are entered in the vector obj, but when obj.removeAll(obj); is executed all the
elements are deleted and vector is empty, hence obj.isEmpty() returns true.
Output:
$ javac vector.java
$ java vector
true
1. import java.util.*;
2. class stack
3. {
5. {
7. obj.push(new Integer(3));
8. obj.push(new Integer(2));
9. obj.pop();
11. System.out.println(obj);
12. }
13. }
a) [3, 5].
b) [3, 2].
c) [3, 2, 5].
d) [3, 5, 2].
View Answer
Answer: a
Explanation: push() and pop() are standard functions of the class stack, push() inserts in the stack and pop removes
from the stack. 3 & 2 are inserted using push() the pop() is used which removes 2 from the stack then again push is
used to insert 5 hence stack contains elements 3 & 5.
Output:
$ javac stack.java
$ java stack
[3, 5].
This set of Java Problems focuses on “Java.util – Dictionary, Hashtable & Properties”.
Answer: d
Explanation: Dictionary, Map & Hashtable all implement Map interface hence all of them uses keys to store value in
the object.
Answer: a
Explanation: None.
3. Which of these is the interface of legacy is implemented by Hashtable and Dictionary classes?
a) Map
b) Enumeration
c) HashMap
d) Hashtable
View Answer
Answer: a
Explanation: Dictionary, Map & Hashtable all implement Map interface hence all of them uses keys to store value in
the object.
4. Which of these is a class which uses String as a key to store the value in object?
a) Array
b) ArrayList
c) Dictionary
d) Properties
View Answer
Answer: d
Explanation: None.
5. Which of these methods is used to retrieve the elements in properties object at specific location?
a) get()
b) Elementat()
c) ElementAt()
d) getProperty()
View Answer
Answer: d
Explanation: None.
1. import java.util.*;
2. class hashtable
3. {
5. {
11. }
12. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: d
Explanation: Hashtable object obj contains values 3, 2, 8 when obj.contains(new Integer(5)) is executed it searches
for 5 in the hashtable since it is not present false is returned.
Output:
$ javac hashtable.java
$ java hashtable
false
1. import java.util.*;
2. class hashtable
3. {
5. {
10. obj.clear();
11. System.out.print(obj.size());
12. }
13. }
a) 0
b) 1
c) 2
d) 3
View Answer
Answer: a
Explanation: None.
Output:
$ javac hashtable.java
$ java hashtable
0
1. import java.util.*;
2. class hashtable
3. {
5. {
11. System.out.print(obj);
12. }
13. }
a) {C=8, B=2}
b) [C=8, B=2].
c) {A=3, C=8, B=2}
d) [A=3, C=8, B=2].
View Answer
Answer: a
Explanation: None.
Output:
$ javac hashtable.java
$ java hashtable
{C=8, B=2}
1. import java.util.*;
2. class hashtable
3. {
5. {
10. System.out.print(obj.toString());
11. }
12. }
a) {C=8, B=2}
b) [C=8, B=2].
c) {A=3, C=8, B=2}
d) [A=3, C=8, B=2].
View Answer
Answer: c
Explanation: obj.toString returns String equivalent of the hashtable, which can also be obtained by simply writing
System.out.print(obj); as print system automatically coverts the obj to string equivalent.
Output:
$ javac hashtable.java
$ java hashtable
{A=3, C=8, B=2}
1. import java.util.*;
2. class properties
3. {
5. {
10. System.out.print(obj.keySet());
11. }
12. }
Answer: B
Explanation: obj.keySet() returns a set containing all the keys used in properties object, here obj contains keys AB,
BC, CD therefore obj.keySet() returns [AB, BC, CD].
Output:
$ javac properties.java
$ java properties
[AB, BC, CD].
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Java.util – BitSet & Date class”.
1. Which of these class object has architecture similar to that of array?
a) Bitset
b) Map
c) Hashtable
d) All of the mentioned
View Answer
Answer: a
Explanation: Bitset class creates a special type of array that holds bit values. This array can increase in size as
needed.
2. Which of these method is used to make a bit zero specified by the index?
a) put()
b) set()
c) remove()
d) clear()
View Answer
Answer: d
Explanation: None.
3. Which of these method is used to calculate number of bits required to hold the BitSet object?
a) size()
b) length()
c) indexes()
d) numberofBits()
View Answer
Answer: b
Explanation: None.
4. Which of these is a method of class Date which is used to search weather object contains a date before the
specified date?
a) after()
b) contains()
c) before()
d) compareTo()
View Answer
Answer: c
Explanation: before() returns true if the invoking Date object contains a date that is earlier than one specified by
date, otherwise it returns false.
5. Which of these methods is used to retrieve elements in BitSet object at specific location?
a) get()
b) Elementat()
c) ElementAt()
d) getProperty()
View Answer
Answer: a
Explanation: None.
6. What is the output of this program?
1. import java.util.*;
2. class Bitset
3. {
5. {
8. obj.set(i);
9. obj.clear(2);
10. System.out.print(obj);
11. }
12. }
a) {0, 1, 3, 4}
b) {0, 1, 2, 4}
c) {0, 1, 2, 3, 4}
d) {0, 0, 0, 3, 4}
View Answer
Answer: a
Explanation: None.
Output:
$ javac Bitset.java
$ java Bitset
{0, 1, 3, 4}
1. import java.util.*;
2. class Bitset
3. {
5. {
8. obj.set(i);
9. obj.clear(2);
10. System.out.print(obj.length() + " " + obj.size());
11. }
12. }
a) 4 64
b) 5 64
c) 5 128
d) 4 128
View Answer
Answer: b
Explanation: obj.length() returns the length allotted to object obj at time of initialization and obj.size() returns the
size of current object obj, each BitSet element is given 16 bits therefore the size is 4 * 16 = 64, whereas length is still
5.
Output:
$ javac Bitset.java
$ java Bitset
5 64
1. import java.util.*;
2. class Bitset
3. {
5. {
8. obj.set(i);
9. System.out.print(obj.get(3));
10. }
11. }
a) 2
b) 3
c) 4
d) 5
View Answer
Answer: a
Explanation: None.
Output:
$ javac Bitset.java
$ java Bitset
2
1. import java.util.*;
2. class date
3. {
5. {
7. System.out.print(obj);
8. }
9. }
Answer: d
Explanation: None.
Output:
$ javac date.java
$ java date
Tue Jun 11 11:29:57 PDT 2013
1. import java.util.*;
2. class Bitset
3. {
5. {
9. obj1.set(i);
12. obj1.and(obj2);
13. System.out.print(obj1);
14. }
15. }
a) {0, 1}
b) {2, 4}
c) {3, 4}
d) {3, 4, 5}
View Answer
Answer: c
Explanation: obj1.and(obj2) returns an BitSet object which contains elements common to both the object obj1 and
obj2 and stores this BitSet in invoking object that is obj1. Hence obj1 contains 3 & 4.
Output:
$ javac Bitset.java
$ java Bitset
{3, 4}
This section of our 1000+ Java MCQs focuses on collection framework of Java Programming Language.
Answer: b
Explanation: None.
Answer: a
Explanation: Maps is not a part of collection framework.
4. Which of these methods deletes all the elements from invoking collection?
a) clear()
b) reset()
c) delete()
d) refresh()
View Answer
Answer: a
Explanation: clear() method removes all the elements from invoking collection.
Answer: a
Explanation: A collection is a group of objects, it is similar to String Template Library (STL) of C++ programming
language.
1. import java.util.*;
2. class Array
3. {
5. {
8. array[5-i] = i;
9. Arrays.fill(array, 1, 4, 8);
11. System.out.print(array[i]);
12. }
13. }
a) 12885
b) 12845
c) 58881
d) 54881
View Answer
Answer: c
Explanation: array was containing 5,4,3,2,1 but when method Arrays.fill(array, 1, 4, 8) is called it fills the index
location starting with 1 to 4 by value 8 hence array becomes 5,8,8,8,1.
Output:
$ javac Array.java
$ java Array
58881
1. import java.util.*;
2. class vector
3. {
5. {
7. obj.addElement(new Integer(3));
8. obj.addElement(new Integer(2));
9. obj.addElement(new Integer(5));
10. obj.removeAll(obj);
11. System.out.println(obj.isEmpty());
12. }
13. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: c
Explanation: firstly elements 3, 2, 5 are entered in the vector obj, but when obj.removeAll(obj); is executed all the
elements are deleted and vector is empty, hence obj.isEmpty() returns true.
Output:
$ javac vector.java
$ java vector
true
1. import java.util.*;
2. class stack
3. {
5. {
7. obj.push(new Integer(3));
8. obj.push(new Integer(2));
9. obj.pop();
11. System.out.println(obj);
12. }
13. }
a) [3, 5].
b) [3, 2].
c) [3, 2, 5].
d) [3, 5, 2].
View Answer
Answer: a
Explanation: push() and pop() are standard functions of the class stack, push() inserts in the stack and pop removes
from the stack. 3 & 2 are inserted using push() the pop() is used which removes 2 from the stack then again push is
used to insert 5 hence stack contains elements 3 & 5.
Output:
$ javac stack.java
$ java stack
[3, 5].
1. import java.util.*;
2. class hashtable
3. {
5. {
11. System.out.print(obj);
12. }
13. }
a) {C=8, B=2}
b) [C=8, B=2].
c) {A=3, C=8, B=2}
d) [A=3, C=8, B=2].
View Answer
Answer: b
Explanation: None.
Output:
$ javac hashtable.java
$ java hashtable
{C=8, B=2}
1. import java.util.*;
2. class Bitset
3. {
5. {
8. obj.set(i);
9. obj.clear(2);
10. System.out.print(obj);
11. }
12. }
a) {0, 1, 3, 4}
b) {0, 1, 2, 4}
c) {0, 1, 2, 3, 4}
d) {0, 0, 0, 3, 4}
View Answer
Answer: a
Explanation: None.
Output:
$ javac Bitset.java
$ java Bitset
{0, 1, 3, 4}
This section of our 1000+ Java MCQs focuses on iterators of Java Programming Language.
Answer: c
Explanation: hasNext() returns boolean values true or false.
Answer: d
Explanation: To obtain an iterator to the start of the start of the collection we use iterator() method.
Answer: a
Explanation: None.
Answer: b
Explanation: None.
Answer: d
Explanation: None.
1. import java.util.*;
2. class Collection_iterators
3. {
5. {
6. ListIterator a = list.listIterator();
7. if(a.previousIndex()! = -1)
8. while(a.hasNext())
10. else
11. System.out.print("EMPTY");
12. }
13. }
a) 0
b) 1
c) -1
d) EMPTY
View Answer
Answer: d
Explanation: None.
Output:
$ javac Collection_iterators.java
$ java Collection_iterators
EMPTY
1. import java.util.*;
2. class Collection_iterators
3. {
5. {
7. list.add(new Integer(2));
8. list.add(new Integer(8));
9. list.add(new Integer(5));
12. Collections.reverse(list);
13. while(i.hasNext())
15. }
16. }
a) 2 8 5 1
b) 1 5 8 2
c) 2
d) 2 1 8 5
View Answer
Answer: b
Explanation: Collections.reverse(list) reverses the given list, the list was 2->8->5->1 after reversing it became 1->5-
>8->2.
Output:
$ javac Collection_iterators.java
$ java Collection_iterators
1582
1. import java.util.*;
2. class Collection_iterators
3. {
5. {
8. list.add(new Integer(8));
9. list.add(new Integer(5));
12. Collections.reverse(list);
13. Collections.sort(list);
14. while(i.hasNext())
16. }
17. }
a) 2 8 5 1
b) 1 5 8 2
c) 1 2 5 8
d) 2 1 8 5
View Answer
Answer: c
Explanation: Collections.sort(list) sorts the given list, the list was 2->8->5->1 after sorting it became 1->2->5->8.
Output:
$ javac Collection_iterators.java
$ java Collection_iterators
1582
1. import java.util.*;
2. class Collection_iterators
3. {
5. {
7. list.add(new Integer(2));
8. list.add(new Integer(8));
9. list.add(new Integer(5));
13. Collections.shuffle(list);
14. i.next();
15. i.remove();
16. while(i.hasNext())
18. }
19. }
a) 2 8 5
b) 2 1 8
c) 2 5 8
d) 8 5 1
View Answer
Answer: b
Explanation: i.next() returns the next element in the iteration. i.remove() removes from the underlying collection the
last element returned by this iterator (optional operation). This method can be called only once per call to next().
The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in
any way other than by calling this method.
Output:
$ javac Collection_iterators.java
$ java Collection_iterators
218
(output will be different on your system)
This set of Java Multiple Choice Questions & Answers focuses on “Data Structures-Queue”.
Answer: b
Explanation: BlockingQueue, TransferQueue and BlockingQueue are subinterfaces of Queue.
2. What is the remaining capacity of BlockingQueue whose intrinsic capacity is not defined?
a) Integer.MAX_VALUE
b) BigDecimal.MAX_VALUE
c) 99999999
d) Integer.INFINITY
View Answer
Answer: a
Explanation: A BlockingQueue without any intrinsic capacity constraints always reports a remaining capacity of
Integer.MAX_VALUE.
3. PriorityQueue is threadsafe?
a) True
b) False
View Answer
Answer: a
Explanation: PriorityQueue is not synchronized. BlockingPriorityQueue is the threadsafe implementation.
Answer: c
Explanation: dequeue() removes the item next in line. peek() returns the item without removing it from the queue.
Answer: a
Explanation: Stack is Last in First out (LIFO) and Queue is First in First out(FIFO).
Answer: c
Explanation: CircularQueue implementation is an abstract class where first and rear pointer point to the same
object.
7. What is the correct method used to insert and delete items from queue?
a) push and pop
b) enqueue and dequeue
c) enqueue and peek
d) add and remove
View Answer
Answer: b
Explanation: enqueue is pushing item into queue; dequeue is removing item from queue; peek returns object
without removing it from queue.
Stack uses push and pop methods. add and remove are used in list.
Answer: b
Explanation: In Breadth First Traversal of graph the nodes at the same level are accessed in the order of retrieval (i.e
FIFO).
Answer: b
Explanation: To maintain FIFO, newer elements are inserted to the tail of the list.
10. If the size of the array used to implement circular queue is MAX_SIZE. How rear moves to traverse inorder to
insert an element in the queue?
a) rear=(rear%1)+MAX_SIZE
b) rear=(rear+1)%MAX_SIZE
c) rear=rear+(1%MAX_SIZE)
d) rear=rear%(MAX_SIZE+1)
View Answer
Answer: b
Explanation: The front and rear pointer od circular queue point to the first element.
This section of our 1000+ Java MCQs focuses on Array class under java.util library of Java Programming Language.
1. Which of these standard collection classes implements all the standard functions on list data structure?
a) Array
b) LinkedList
c) HashSet
d) AbstractSet
View Answer
Answer: a
Explanation: None.
Answer: b
Explanation: HashSet and TreeSet implements Set interface where as LinkedList and ArrayList implements List
interface.
3. Which of these method is used to make all elements of an equal to specified value?
a) add()
b) fill()
c) all()
d) set()
View Answer
Answer: b
Explanation: fill() method assigns a value to all the elements in an array, in other words it fills the array with specified
value.
4. Which of these method of Array class is used sort an array or its subset?
a) binarysort()
b) bubblesort()
c) sort()
d) insert()
View Answer
Answer: c
Explanation: None.
Answer: d
Explanation: binaryserach() method uses binary search to find a specified value. This method must be applied to
sorted arrays.
Answer: b
Explanation: An element in a LinkedList object can be changed by first using get() to obtain the index or location of
that object and the passing that location to method set() along with its new value.
1. import java.util.*;
2. class Arraylist
3. {
5. {
8. obj1.add("A");
9. obj1.add("B");
10. obj2.add("A");
12. System.out.println(obj1.equals(obj2));
13. }
14. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: c
Explanation: obj1 and obj2 are an object of class ArrayList hence it is a dynamic array which can increase and
decrease its size. obj.add(“X”) adds to the array element X and obj.add(1,”X”) adds element x at index position 1 in
the list, Both the objects obj1 and obj2 contain same elements i:e A & B thus obj1.equals(obj2) method returns true.
Output:
$ javac Arraylist.java
$ java Arraylist
true
1. import java.util.*;
2. class Array
3. {
5. {
8. array[5 - i] = i;
9. Arrays.sort(array);
11. System.out.print(array[i]);;
12. }
13. }
a) 12345
b) 54321
c) 1234
d) 5432
View Answer
Answer: a
Explanation: Arrays.sort(array) method sorts the array into 1,2,3,4,5.
Output:
$ javac Array.java
$ java Array
12345
1. import java.util.*;
2. class Array
3. {
5. {
8. array[5-i] = i;
9. Arrays.fill(array, 1, 4, 8);
11. System.out.print(array[i]);
12. }
13. }
a) 12885
b) 12845
c) 58881
d) 54881
View Answer
Answer: c
Explanation: array was containing 5,4,3,2,1 but when method Arrays.fill(array, 1, 4, 8) is called it fills the index
location starting with 1 to 4 by value 8 hence array becomes 5,8,8,8,1.
Output:
$ javac Array.java
$ java Array
58881
1. import java.util.*;
2. class Array
3. {
5. {
8. array[5 - i] = i;
9. Arrays.sort(array);
11. }
12. }
a) 2
b) 3
c) 4
d) 5
View Answer
Answer: b
Explanation: None.
Output:
$ javac Array.java
$ java Array
3
This section of our 1000+ Java MCQs focuses on collection framework of Java Programming Language.
1. Which of these interface declares core method that all collections will have?
a) set
b) EventListner
c) Comparator
d) Collection
View Answer
Answer: d
Explanation: Collection interfaces defines core methods that all the collections like set, map, arrays etc will have.
Answer: b
Explanation: None.
Answer: d
Explanation: SortedList is not a part of collection framework.
Answer: a
Explanation: Set interface extends collection interface to handle sets, which must contain unique elements.
Answer: d
Explanation: Collection interface is inherited by all other interfaces like Set, Array, Map etc. It defines core methods
that all the collections like set, map, arrays etc will have
1. import java.util.*;
2. class Maps
3. {
4. public static void main(String args[])
5. {
10. System.out.println(obj.entrySet());
11. }
12. }
a) [A, B, C].
b) [1, 2, 3].
c) {A=1, B=2, C=3}
d) [A=1, B=2, C=3].
View Answer
Answer: d
Explanation: obj.entrySet() method is used to obtain a set that contains the entries in the map. This method provides
set view of the invoking map.
Output:
$ javac Maps.java
$ java Maps
[A=1, B=2, C=3].
1. import java.util.*;
2. class vector
3. {
5. {
7. obj.addElement(new Integer(3));
8. obj.addElement(new Integer(2));
9. obj.addElement(new Integer(5));
10. obj.removeAll(obj);
11. System.out.println(obj.isEmpty());
12. }
13. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: c
Explanation: firstly elements 3, 2, 5 are entered in the vector obj, but when obj.removeAll(obj); is executed all the
elements are deleted and vector is empty, hence obj.isEmpty() returns true.
Output:
$ javac vector.java
$ java vector
true
1. import java.util.*;
2. class Array
3. {
5. {
8. array[5 - i] = i;
9. Arrays.sort(array);
11. System.out.print(array[i]);;
12. }
13. }
a) 12345
b) 54321
c) 1234
d) 5432
View Answer
Answer: a
Explanation: Arrays.sort(array) method sorts the array into 1,2,3,4,5.
Output:
$ javac Array.java
$ java Array
12345
9. What is the output of this program?
1. import java.util.*;
2. class vector
3. {
5. {
7. obj.addElement(new Integer(3));
8. obj.addElement(new Integer(2));
9. obj.addElement(new Integer(5));
10. obj.removeAll(obj);
11. System.out.println(obj.isEmpty());
12. }
13. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: c
Explanation: firstly elements 3, 2, 5 are entered in the vector obj, but when obj.removeAll(obj); is executed all the
elements are deleted and vector is empty, hence obj.isEmpty() returns true.
Output:
$ javac vector.java
$ java vector
true
1. import java.util.*;
2. class Bitset
3. {
5. {
9. obj.clear(2);
10. System.out.print(obj);
11. }
12. }
a) {0, 1, 3, 4}
b) {0, 1, 2, 4}
c) {0, 1, 2, 3, 4}
d) {0, 0, 0, 3, 4}
View Answer
Answer: a
Explanation: None.
Output:
$ javac Bitset.java
$ java Bitset
{0, 1, 3, 4}
This section of our 1000+ Java MCQs focuses on collection algorithms of Java Programming Language.
1. Which of these is an incorrect form of using method max() to obtain maximum element?
a) max(Collection c)
b) max(Collection c, Comparator comp)
c) max(Comparator comp)
d) max(List c)
View Answer
Answer: c
Explanation: Its illegal to call max() only with comparator, we need to give the collection to be serched into.
Answer: b
Explanation: None.
Answer: c
Explanation: singletonList() returns the object as an immutable List. This is a easy way to convert a single object into
a list. This was added by Java 2.0.
Answer: b
Explanation: unmodifiableCollection() is available for al collections, Set, Map, List etc.
Answer: d
Explanation: None.
1. import java.util.*;
2. class Collection_Algos
3. {
5. {
7. list.add(new Integer(2));
8. list.add(new Integer(8));
9. list.add(new Integer(5));
12. while(i.hasNext())
14. }
15. }
a) 2 8 5 1
b) 1 5 8 2
c) 2
d) 2 1 8 5
View Answer
Answer: a
Explanation: None.
Output:
$ javac Collection_Algos.java
$ java Collection_Algos
2851
1. import java.util.*;
2. class Collection_Algos
3. {
5. {
7. list.add(new Integer(2));
8. list.add(new Integer(8));
9. list.add(new Integer(5));
12. Collections.reverse(list);
13. while(i.hasNext())
15. }
16. }
a) 2 8 5 1
b) 1 5 8 2
c) 2
d) 2 1 8 5
View Answer
Answer: b
Explanation: Collections.reverse(list) reverses the given list, the list was 2->8->5->1 after reversing it became 1->5-
>8->2.
Output:
$ javac Collection_Algos.java
$ java Collection_Algos
1582
1. import java.util.*;
2. class Collection_Algos
3. {
5. {
7. list.add(new Integer(2));
8. list.add(new Integer(8));
9. list.add(new Integer(5));
12. Collections.reverse(list);
13. Collections.sort(list);
14. while(i.hasNext())
16. }
17. }
a) 2 8 5 1
b) 1 5 8 2
c) 1 2 5 8
d) 2 1 8 5
View Answer
Answer: c
Explanation: Collections.sort(list) sorts the given list, the list was 2->8->5->1 after sorting it became 1->2->5->8.
Output:
$ javac Collection_Algos.java
$ java Collection_Algos
1582
1. import java.util.*;
2. class Collection_Algos
3. {
5. {
7. list.add(new Integer(2));
8. list.add(new Integer(8));
9. list.add(new Integer(5));
12. Collections.reverse(list);
13. Collections.shuffle(list);
14. while(i.hasNext())
16. }
17. }
a) 2 8 5 1
b) 1 5 8 2
c) 1 2 5 8
d) Any random order
View Answer
Answer: d
Explanation: shuffle – randomizes all the elements in a list.
Output:
$ javac Collection_Algos.java
$ java Collection_Algos
1528
(output will be different on your system)
Java Questions & Answers – Exceptional Handling Basics
This section of our 1000+ Java MCQs focuses on exception handling of Java Programming Language.
Answer: a
Explanation: Exceptions in java are run-time errors.
Answer: c
Explanation: Exceptional handling is managed via 5 keywords – try, catch, throws, throw and finally.
Answer: a
Explanation: None.
4. Which of these keywords must be used to handle the exception thrown by try block in some rational manner?
a) try
b) finally
c) throw
d) catch
View Answer
Answer: d
Explanation: If an exception occurs within the try block, it is thrown and cached by catch block for processing.
Answer: c
Explanation: None.
6. What is the output of this program?
1. class exception_handling
2. {
4. {
5. try
6. {
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.print("World");
12. }
13. }
14. }
a) Hello
b) World
c) HelloWorld
d) Hello World
View Answer
Answer: b
Explanation: System.ou.print() function fist converts the whole parameters into string and then prints, before “Hello”
goes to output stream 1 / 0 error is encountered which is cached by catch block printing just “World” .
Output:
$ javac exception_handling.java
$ java exception_handling
World
1. class exception_handling
2. {
4. {
5. try
6. {
7. int a, b;
8. b = 0;
9. a = 5 / b;
10. System.out.print("A");
11. }
12. catch(ArithmeticException e)
13. {
14. System.out.print("B");
15. }
16. }
17. }
a) A
b) B
c) Compilation Error
d) Runtime Error
View Answer
Answer: b
Explanation: None.
Output:
$ javac exception_handling.java
$ java exception_handling
B
1. class exception_handling
2. {
4. {
5. try
6. {
7. int a, b;
8. b = 0;
9. a = 5 / b;
10. System.out.print("A");
11. }
12. catch(ArithmeticException e)
13. {
14. System.out.print("B");
15. }
16. finally
17. {
18. System.out.print("C");
19. }
20. }
21. }
a) A
b) B
c) AC
d) BC
View Answer
Answer: d
Explanation: finally keyword is used to execute the code before try and catch block end.
Output:
$ javac exception_handling.java
$ java exception_handling
BC
1. class exception_handling
2. {
4. {
5. try
6. {
7. int i, sum;
8. sum = 10;
11. }
12. catch(ArithmeticException e)
13. {
14. System.out.print("0");
15. }
16. System.out.print(sum);
17. }
18. }
a) 0
b) 05
c) Compilation Error
d) Runtime Error
View Answer
Answer: c
Explanation: Value of variable sum is printed outside of try block, sum is declared only in try block, outside try block
it is undefined.
Output:
$ javac exception_handling.java
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
sum cannot be resolved to a variable
1. class exception_handling
2. {
4. {
5. try
6. {
7. int i, sum;
8. sum = 10;
10. {
12. System.out.print(i);
13. }
14. }
15. catch(ArithmeticException e)
16. {
17. System.out.print("0");
18. }
19. }
20. }
a) -1
b) 0
c) -10
d) -101
View Answer
Answer: c
Explanation: For the 1st iteration -1 is displayed. The 2nd exception is caught in catch block and 0 is displayed.
Output:
$ javac exception_handling.java
$ java exception_handling
-10
This set of Java Questions and Answers for Experienced people focuses on “Exception Handling”.
Answer: c
Explanation: “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
View Answer
Answer: b
Explanation: Runtime errors cannot be caught generally. Error class is used to catch such errors/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
View Answer
Answer: d
Explanation: new operator is used to create instance of an exception. Exceptions may have prameter 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
View Answer
Answer: a
Explanation: A method sepcifies 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 catch is not used?
a) finally
b) throw handler
c) default handler
d) java run time system
View Answer
Answer: c
Explanation: Default handler is used to handle all the exceptions if catch is not used to handle exception. Finally is
called in any case.
Answer: a
Exception: 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
View Answer
Answer: c
Explanation: The throw statement should be assignable to the throwable type. Throwable is the super class of all
exceptions.
Answer: d
Explanation: parseInt() method parses input into integer. The exception thrown by this method is
NumberFormatException.
Answer: b
Explanation: Error is not recoverable at run time. The control is lost from the application.
This section of our 1000+ Java MCQs focuses on Exceptions types in Java Programming Language.
Answer: c
Explanation: All the exception types are subclasses of the built in class Throwable.
2. Which of these class is related to all the exceptions that can be caught by using catch?
a) Error
b) Exception
c) RuntimeExecption
d) All of the mentioned
View Answer
Answer: b
Explanation: Error class is related to java run time error that can’t be caught usually, RuntimeExecption is subclass of
Exception class which contains all the exceptions that can be caught.
3. Which of these class is related to all the exceptions that cannot be caught?
a) Error
b) Exception
c) RuntimeExecption
d) All of the mentioned
View Answer
Answer: a
Explanation: Error class is related to java run time error that can’t be caught usually, RuntimeExecption is subclass of
Exception class which contains all the exceptions that can be caught.
Answer: a
Explanation: None.
Answer: c
Explanation: None.
1. class exception_handling
2. {
4. {
5. try
6. {
8. }
9. finally
10. {
11. System.out.print("World");
12. }
13. }
14. }
a) Hello
b) World
c) Compilation Error
d) First Exception then World
View Answer
Answer: d
Explanation: None.
Output:
$ javac exception_handling.java
$ java exception_handling
Exception in thread “main” java.lang.ArithmeticException: / by zero
World
1. class exception_handling
2. {
4. {
5. try
6. {
7. int a, b;
8. b = 0;
9. a = 5 / b;
10. System.out.print("A");
11. }
12. catch(ArithmeticException e)
13. {
14. System.out.print("B");
15. }
16. }
17. }
a) A
b) B
c) Compilation Error
d) Runtime Error
View Answer
Answer: b
Explanation: None.
Output:
$ javac exception_handling.java
$ java exception_handling
B
1. class exception_handling
2. {
4. {
5. try
6. {
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
View Answer
Answer: b
Explanation: When array index goes out of bound then ArrayIndexOutOfBoundsException exceptio is thrown by the
system.
Output:
$ javac exception_handling.java
$ java exception_handling
123450
2. {
4. {
5. try
6. {
7. int i, sum;
8. sum = 10;
11. }
12. catch(ArithmeticException e)
13. {
14. System.out.print("0");
15. }
16. System.out.print(sum);
17. }
18. }
a) 0
b) 05
c) Compilation Error
d) Runtime Error
View Answer
Answer: c
Explanation: Since sum is declared inside try block and we are trying to access it outside the try block it results in
error.
Output:
$ javac exception_handling.java
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
sum cannot be resolved to a variable
1. class exception_handling
2. {
5. try
6. {
9. System.out.print(a[i]);
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) Comiplation Error
View Answer
Answer: c
Explanation: There can be more than one catch for a single try block. Here Arithmetic exception(/ by 0) occurs
instead of Array index out of bound exception, so 2nd catch block is executed.
Output:
$ javac exception_handling.java
$ java exception_handling
12345B
This section of our 1000+ Java MCQs focuses on throw, throws & nested try of Java Programming Language.
Answer: c
Explanation: None.
2. Which of these class is related to all the exceptions that are explicitly thrown?
a) Error
b) Exception
c) Throwable
d) Throw
View Answer
Answer: c
Explanation: None.
3. Which of these operator is used to generate an instance of an exception than can be thrown by using throw?
a) new
b) malloc
c) alloc
d) thrown
View Answer
Answer: a
Explanation: new is used to create instance of an exception. All of java’s built in run-time exceptions have two
constructors : one with no parameters and one that takes a string parameter.
Answer: a
Explanation: None.
5. Which of these keywords is used to by the calling function to guard against the exception that is thrown by called
function?
a) try
b) throw
c) throws
d) catch
View Answer
Answer: c
Explanation: If a method is capable of causing an exception that it does not handle. It must specify this behaviour the
behaviour so that callers of the method can guard themselves against that exception. This is done by using throws
clause in methods declaration.
2. {
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. {
17. c[8] = 9;
18. }
19. }
21. {
22. System.out.println("TypeA");
23. }
25. {
26. System.out.println("TypeB");
27. }
28. }
29. }
30. }
a) TypeA
b) TypeB
c) Compiler Time Error
d) 0TypeB
View Answer
Answer: c
Explanation: Because we can’t go beyond array limit
1. class exception_handling
2. {
4. {
5. try
6. {
7. System.out.print("A");
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.print("B");
13. }
14. }
15. }
a) A
b) B
c) Hello
d) Runtime Exception
View Answer
Answer: d
Explanation: None.
Output:
$ javac exception_handling.java
$ java exception_handling
Exception in thread “main” java.lang.NullPointerException: Hello
at exception_handling.main
2. {
4. {
5. System.out.print("0");
7. }
9. {
10. try
11. {
12. throwexception();
13. }
15. {
16. System.out.println("A");
17. }
18. }
19. }
a) A
b) 0
c) 0A
d) Exception
View Answer
Answer: c
Explanation: None.
Output:
$ javac exception_handling.java
$ java exception_handling
0A
2. {
5. try
6. {
7. return;
8. }
9. finally
10. {
12. }
13. }
14. }
a) Finally
b) Compilation fails
c) The code runs with no output
d) An exception is thrown at runtime
View Answer
Answer: a
Explanation: Because finally will execute always.
2. {
4. {
5. try
6. {
8. }
9. finally
10. {
12. }
13. }
14. }
Answer: d
Explanation: None
This section of our 1000+ Java MCQs focuses on keyword finally and built in exceptions of Java Programming
Language.
Answer: b
Explanation: finally keyword is used to define a set of instructions that will be executed irrespective of the exception
found or not.
Answer: c
Explanation: try block can be followed by any of finally or catch block, try block checks for exceptions and work is
performed by finally and catch block as per the exception.
Answer: c
Explanation: None.
Answer: a
Explanation: None.
5. Which of these exceptions will occur if we try to access the index of an array beyond its length?
a) ArithmeticException
b) ArrayException
c) ArrayIndexException
d) ArrayIndexOutOfBoundsException
View Answer
Answer: d
Explanation: ArrayIndexOutOfBoundsException is a built in exception that is caused when we try to access an index
location which is beyond the length of an array.
1. class exception_handling
2. {
4. {
5. try
6. {
7. int a = args.length;
8. int b = 10 / a;
9. System.out.print(a);
10. }
12. {
13. System.out.println("1");
14. }
15. }
16. }
a) 0
b) 1
c) Compilation Error
d) Runtime Error
Note : Execution command line : $ java exception_handling
View Answer
Answer: b
Explanation: None.
Output:
$ javac exception_handling.java
$ java exception_handling
1
1. class exception_handling
2. {
4. {
5. try
6. {
8. }
9. catch(ArithmeticException e)
10. {
11. System.out.print("B");
12. }
13. }
14. }
a) A
b) B
c) Compilation Error
d) Runtime Error
View Answer
Answer: d
Explanation: Try block is throwing NullPointerException but the catch block is used to counter Arithmetic Exception.
Hence NullPointerException occurs since no catch is there which can handle it, runtime error occurs.
Output:
$ javac exception_handling.java
$ java exception_handling
Exception in thread “main” java.lang.NullPointerException: Hello
1. class exception_handling
2. {
3. static void throwexception() throws ArithmeticException
4. {
5. System.out.print("0");
7. }
9. {
10. try
11. {
12. throwexception();
13. }
15. {
16. System.out.println("A");
17. }
18. }
19. }
a) A
b) 0
c) 0A
d) Exception
View Answer
Answer: c
Explanation: None.
Output:
$ javac exception_handling.java
$ java exception_handling
0A
1. class exception_handling
2. {
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. {
16. c[8] = 9;
17. }
18. }
19. finally
20. {
21. System.out.print("A");
22. }
23. }
25. {
26. System.out.println("B");
27. }
28. }
29. }
a) A
b) B
c) AB
d) BA
View Answer
Answer:a
Explanation: 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 ArrayIndexOutOfBoundException
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
1. class exception_handling
2. {
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. {
17. c[8] = 9;
18. }
19. }
21. {
22. System.out.println("TypeA");
23. }
25. {
26. System.out.println("TypeB");
27. }
28. }
29. }
a) TypeA
b) TypeB
c) Compilation Error
d) Runtime Error
Note: Execution command line: $ java exception_handling one two
View Answer
Answer: c
Explanation: try without catch or finally
Output:
$ javac exception_handling.java
$ java exception_handling
Main.java:9: error: ‘try’ without ‘catch’, ‘finally’ or resource declarations
This section of our 1000+ Java MCQs focuses on try and catch in Java Programming Language.
Answer: d
Explanation: None.
2. Which of these keywords are used for the block to be examined for exceptions?
a) try
b) catch
c) throw
d) check
View Answer
Answer: a
Explanation: try is used for the block that needs to checked for exception.
3. Which of these keywords are used for the block to handle the exceptions generated by try block?
a) try
b) catch
c) throw
d) check
View Answer
Answer: b
Explanation: None.
4. Which of these keywords are used for generating an exception manually?
a) try
b) catch
c) throw
d) check
View Answer
Answer: c
Explanation: None.
Answer: d
Explanation: try must be followed by either catch or finally block.
1. class Output
2. {
4. {
5. try
6. {
7. int a = 0;
8. int b = 5;
9. int c = b / a;
10. System.out.print("Hello");
11. }
12. catch(Exception e)
13. {
14. System.out.print("World");
15. }
16. }
17. }
a) Hello
b) World
c) HelloWOrld
d) Compilation Error
View Answer
Answer: b
Explanation: None.
Output:
$ javac Output.javac
java Output
World
1. class Output
2. {
4. {
5. try
6. {
7. int a = 0;
8. int b = 5;
9. int c = a / b;
10. System.out.print("Hello");
11. }
12. catch(Exception e)
13. {
14. System.out.print("World");
15. }
16. }
17. }
a) Hello
b) World
c) HelloWOrld
d) Compilation Error
View Answer
Answer: a
Explanation: None.
Output:
$ javac Output.javac
java Output
Hello
1. class Output
2. {
4. {
5. try
6. {
7. int a = 0;
8. int b = 5;
9. int c = b / a;
10. System.out.print("Hello");
11. }
12. }
13. }
a) Hello
b) World
c) HelloWOrld
d) Compilation Error
View Answer
Answer: d
Explanation: try must be followed by either catch or finally
Output:
$ javac Output.javac
Exception in thread “main” java.lang.Error: Unresolved compilation problem:
Syntax error, insert “Finally” to complete BlockStatements
1. class Output
2. {
4. {
5. try
6. {
7. int a = 0;
8. int b = 5;
9. int c = a / b;
10. System.out.print("Hello");
11. }
12. finally
13. {
14. System.out.print("World");
15. }
16. }
17. }
a) Hello
b) World
c) HelloWOrld
d) Compilation Error
View Answer
Answer: c
Explanation: finally block is always executed after try block, no matter exception is found or not.
Output:
$ javac Output.javac
java Output
HelloWorld
1. class Output
2. {
4. {
5. try
6. {
7. int a = 0;
8. int b = 5;
9. int c = b / a;
10. System.out.print("Hello");
11. }
12. catch(Exception e)
13. {
14. System.out.print("World");
15. }
16. finally
17. {
18. System.out.print("World");
19. }
20. }
21. }
a) Hello
b) World
c) HelloWOrld
d) WorldWorld
View Answer
Answer: d
Explanation: finally block is always executed after tryblock, no matter exception is found or not. catch block is
executed only when exception is found. Here divide by zero exception is found hence both catch and finally are
executed.
Output:
$ javac Output.javac
java Output
WorldWorld
This section of our 1000+ Java MCQs focuses on creating exceptions in Java Programming Language.
Answer: a
Explanation: None.
Answer: b
Explanation: getMessage() returns a description of the exception.
Answer: b
Explanation: None.
Answer: a
Explanation: None.
Answer: a
Explanation: None.
2. {
3. int detail;
4. Myexception(int a)
5. {
6. detail = a;
7. }
9. {
10. return "detail";
11. }
12. }
14. {
16. {
18. }
20. {
21. try
22. {
23. compute(3);
24. }
25. catch(Myexception e)
26. {
27. System.out.print("Exception");
28. }
29. }
30. }
a) 3
b) Exception
c) Runtime Error
d) Compilation Error
View Answer
Answer: b
Explanation: Myexception is self defined exception.
Output:
$ javac Output.java
java Output
Exception
3. int detail;
4. Myexception(int a)
5. {
6. detail = a;
7. }
9. {
11. }
12. }
14. {
16. {
18. }
20. {
21. try
22. {
23. compute(3);
24. }
25. catch(DevideByZeroException e)
26. {
27. System.out.print("Exception");
28. }
29. }
30. }
a) 3
b) Exception
c) Runtime Error
d) Compilation Error
View Answer
Answer: c
Explanation: Mexception is self defined exception, we are generating Myexception but catching
DevideByZeroException which causes error.
Output:
$ javac Output.javac
1. class exception_handling
2. {
4. {
5. try
6. {
8. System.out.print("A");
9. }
10. catch(ArithmeticException e)
11. {
12. System.out.print("B");
13. }
14. }
15. }
a) A
b) B
c) Compilation Error
d) Runtime Error
View Answer
Answer: d
Explanation: try block is throwing NullPointerException but the catch block is used to counter Arithmetic Exception.
Hence NullPointerException occurs since no catch is there which can handle it, runtime error occurs.
Output:
$ javac exception_handling.java
$ java exception_handling
Exception in thread “main” java.lang.NullPointerException: Hello
2. {
3. int detail;
4. Myexception(int a)
5. {
6. detail = a;
7. }
9. {
11. }
12. }
14. {
16. {
18. }
20. {
21. try
22. {
23. compute(3);
24. }
25. catch(Exception e)
26. {
27. System.out.print("Exception");
28. }
29. }
30. }
a) 3
b) Exception
c) Runtime Error
d) Compilation Error
View Answer
Answer: b
Explanation: Myexception is self defined exception.
Output:
$ javac Output.javac
java Output
Exception
1. class exception_handling
2. {
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. {
17. c[8] = 9;
18. }
19. }
21. {
22. System.out.println("TypeA");
23. }
25. {
26. System.out.println("TypeB");
27. }
28. }
29. }
30. }
a) TypeA
b) TypeB
c) Compilation Error
d) Runtime Error
Note : Execution commandline : $ java exception_handling one
View Answer
Answer: c
Explanation: try without catch or finally
Output:
$ javac exception_handling.java
$ java exception_handling
error: ‘try’ without ‘catch’, ‘finally’ or resource declarations
This set of Java Assessment Questions and Answers focuses on “isAlive(), Join() & Thread Synchronization”.
1. Which of these method can be used to make the main thread to be executed last among all the threads?
a) stop()
b) sleep()
c) join()
d) call()
View Answer
Answer: b
Explanation: By calling sleep() within main(), with long enough delay to ensure that all child threads terminate prior
to the main thread.
2. Which of these method is used to find out that a thread is still running or not?
a) run()
b) Alive()
c) isAlive()
d) checkRun()
View Answer
Answer: c
Explanation: The isAlive( ) method returns true if the thread upon which it is called is still running. It returns false
otherwise.
3. What is the default value of priority variable MIN_PRIORITY AND MAX_PRIORITY?
a) 0 & 256
b) 0 & 1
c) 1 & 10
d) 1 & 256
View Answer
Answer: c
Explanation: None.
Answer: c
Explanation: None.
Answer: c
Explanation: The default value of priority given to a thread is 5 but we can explicitly change that value between the
permitted values 1 & 10, this is done by using the method setPriority().
Answer: a
Explanation: When two or more threads need to access the same shared resource, they need some way to ensure
that the resource will be used by only one thread at a time, the process by which this is achieved is called
synchronization
2. {
3. newthread()
4. {
5. super("My Thread");
6. start();
7. }
9. {
10. System.out.println(this);
11. }
12. }
14. {
16. {
18. }
19. }
a) My Thread
b) Thread[My Thread,5,main].
c) Compilation Error
d) Runtime Error
View Answer
Answer: b
Explanation: Although we have not created any object of thread class still we can make a thread pointing to main
method, we can refer it by using this.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Thread[My Thread,5,main].
2. {
3. Thread t;
4. newthread()
5. {
7. t.start();
8. }
10. {
11. try
12. {
13. t.join()
14. System.out.println(t.getName());
15. }
16. catch(Exception e)
17. {
18. System.out.print("Exception");
19. }
20. }
21. }
23. {
25. {
27. }
28. }
a) My Thread
b) Thread[My Thread,5,main].
c) Exception
d) Runtime Error
View Answer
Answer: d
Explanation: join() method of Thread class waits for thread being called to finish or terminate, but here we have no
condition which can terminate the thread, hence code ‘t.join()’ leads to runtime error and nothing will be printed on
the screen.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
2. {
3. Thread t;
4. newthread()
5. {
7. t.start();
8. }
10. {
11. System.out.println(t.isAlive());
12. }
13. }
15. {
17. {
19. }
20. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: c
Explanation: isAlive() method is used to check whether the thread being called is running or not, here thread is the
main() method which is running till the program is terminated hence it returns true.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
true
3. Thread t1,t2;
4. newthread()
5. {
6. t1 = new Thread(this,"Thread_1");
7. t2 = new Thread(this,"Thread_2");
8. t1.start();
9. t2.start();
10. }
12. {
13. t2.setPriority(Thread.MAX_PRIORITY);
14. System.out.print(t1.equals(t2));
15. }
16. }
18. {
20. {
22. }
23. }
a) true
b) false
c) truetrue
d) falsefalse
View Answer
Answer: d
Explanation: This program was previously done by using Runnable interface, here we have used Thread class. This
shows both the method are equivalent, we can use any of them to create a thread.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
falsefalse
Java Questions & Answers – Implementing Runnable interface for Threads
This set of Java MCQs focuses on “Implementing Runnable interface for Threads”.
Answer: b
Explanation: To implement Runnable interface, a class needs only to implement a single method called run().
Answer: a
Explanation: None.
Answer: b
Explanation: None.
Answer: c
Explanation: None.
Answer: d
Explanation: run() method is used to define the code that constitutes the new thread, it contains the code to be
executed. start() method is used to begin execution of the thread that is execution of run(). run() itself is never used
for starting execution of the thread.
2. {
3. Thread t;
4. newthread()
5. {
7. t.start();
8. }
10. {
11. System.out.println(t.getName());
12. }
13. }
15. {
17. {
19. }
20. }
a) My Thread
b) Thread[My Thread,5,main].
c) Compilation Error
d) Runtime Error
View Answer
Answer: a
Explanation: None.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
My Thread
7. What is the output of this program?
2. {
3. Thread t;
4. newthread()
5. {
7. t.start();
8. }
10. {
11. System.out.println(t);
12. }
13. }
15. {
17. {
19. }
20. }
a) My Thread
b) Thread[My Thread,5,main].
c) Compilation Error
d) Runtime Error
View Answer
Answer: b
Explanation: None.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Thread[My Thread,5,main]
3. Thread t;
4. newthread()
5. {
7. t.start();
8. }
9. }
11. {
13. {
15. }
16. }
a) My Thread
b) Thread[My Thread,5,main].
c) Compilation Error
d) Runtime Error
View Answer
Answer: c
Explanation: Thread t has been made by using Runnable interface, hence it is necessary to use inherited abstract
method run() method to specify instructions to be implemented on the thread, since no run() method is used it gives
a compilation error.
Output:
$ javac multithreaded_programing.java
The type newthread must implement the inherited abstract method Runnable.run()
2. {
3. Thread t;
4. newthread()
5. {
8. }
10. {
11. t.setPriority(Thread.MAX_PRIORITY);
12. System.out.println(t);
13. }
14. }
16. {
18. {
20. }
21. }
a) Thread[New Thread,0,main].
b) Thread[New Thread,1,main].
c) Thread[New Thread,5,main].
d) Thread[New Thread,10,main].
View Answer
Answer: d
Explanation: Thread t has been made with default priority value 5 but in run method the priority has been explicitly
changed to MAX_PRIORITY of class thread, that is 10 by code ‘t.setPriority(Thread.MAX_PRIORITY);’ using the
setPriority function of thread t.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Thread[New Thread,10,main]
2. {
3. Thread t;
4. newthread()
5. {
6. t1 = new Thread(this,"Thread_1");
7. t2 = new Thread(this,"Thread_2");
8. t1.start();
9. t2.start();
10. }
12. {
13. t2.setPriority(Thread.MAX_PRIORITY);
14. System.out.print(t1.equals(t2));
15. }
16. }
18. {
20. {
22. }
23. }
a) true
b) false
c) truetrue
d) falsefalse
View Answer
Answer: d
Explanation: Threads t1 & t2 are created by class newthread that is implementing runnable interface, hence both the
threads are provided their own run() method specifying the actions to be taken. When constructor of newthread
class is called first the run() method of t1 executes than the run method of t2 printing 2 times “false” as both the
threads are not equal one is having different priority than other, hence falsefalse is printed.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
falsefalse
This section of our 1000+ Java MCQs focuses on Thread class of Java Programming Language.
Answer: c
Explanation: Thread class is used to make threads in java, Thread encapsulates a thread of execution. To create a
new thread the program will either extend Thread or implement the Runnable interface.
Answer: a
Explanation: None.
3. Which of these method of Thread class is used to find out the priority given to a thread?
a) get()
b) ThreadPriority()
c) getPriority()
d) getThreadPriority()
View Answer
Answer: c
Explanation: None.
4. Which of these method of Thread class is used to Suspend a thread for a period of time?
a) sleep()
b) terminate()
c) suspend()
d) stop()
View Answer
Answer: a
Explanation: None.
5. Which function of pre defined class Thread is used to check weather current thread being checked is still running?
a) isAlive()
b) Join()
c) isRunning()
d) Alive()
View Answer
Answer:a
Explanation:isAlive() function is defined in class Thread, it is used for implementing multithreading and to check
whether the thread called
upon is still running or not.
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. t.setName("New Thread");
7. System.out.println(t);
8. }
9. }
a) Thread[5,main].
b) Thread[New Thread,5].
c) Thread[main,5,main].
d) Thread[New Thread,5,main].
View Answer
Answer: d
Explanation: None.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Thread[New Thread,5,main]
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. t.setName("New Thread");
7. System.out.println(t.getName());
8. }
9. }
a) main
b) Thread
c) New Thread
d) Thread[New Thread,5,main].
View Answer
Answer: c
Explanation: The getName() function is used to obtain the name of the thread, in this code the name given to thread
is ‘New Thread’.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
New Thread
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. System.out.println(t.getPriority());
7. }
8. }
a) 0
b) 1
c) 4
d) 5
View Answer
Answer: d
Explanation: The default priority given to a thread is 5.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
5
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. System.out.println(t.isAlive());
7. }
8. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: c
Explanation: Thread t is seeded to currently program, hence when you run the program the thread becomes active &
code ‘t.isAlive’ returns true.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
true
This section of our 1000+ Java MCQs focuses on Basics of multithreading of Java Programming Language.
Answer: b
Explanation: Multithreaded programming a process in which two or more parts of same process run simultaneously.
Answer: c
Explanation: There are two types of multitasking: Process based multitasking and Thread based multitasking.
Answer: c
Explanation: None.
5. What will happen if two thread of same priority are called to be processed simultaneously?
a) Any one will be executed first lexographically
b) Both of them will be executed simultaneously
c) None of them will be executed
d) It is dependent on the operating system
View Answer
Answer: d
Explanation: In cases where two or more thread with same priority are competing for CPU cycles, different operating
system handle this situation differently. Some execute them in time sliced manner some depending on the thread
they call.
Answer: d
Explanation: Thread exist in several states, a thread can be running, suspended, blocked, terminated & ready to run.
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. System.out.println(t);
7. }
8. }
a) Thread[5,main].
b) Thread[main,5].
c) Thread[main,0].
d) Thread[main,5,main].
View Answer
Answer: d
Explanation: None.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Thread[main,5,main]
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. System.out.println(t);
7. }
8. }
a) 4
b) 5
c) 0
d) 1
View Answer
Answer: b
Explanation: The output of program is Thread[main,5,main], in this priority assigned to the thread is 5. Its the default
value. Since we have not named the thread they are named by the group to they belong i:e main method.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Thread[main,5,main]
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. System.out.println(t);
7. }
8. }
a) main
b) Thread
c) System
d) None of the mentioned
View Answer
Answer: a
Explanation: The output of program is Thread[main,5,main], Since we have not explicitly named the thread they are
named by the group to they belong i:e main method. Hence they are named ‘main’.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Thread[main,5,main]
1. class multithreaded_programing
2. {
4. {
5. Thread t = Thread.currentThread();
6. System.out.println(t.isAlive());
7. }
8. }
a) 0
b) 1
c) true
d) false
View Answer
Answer: c
Explanation: Thread t is seeded to currently program, hence when you run the program the thread becomes active &
code ‘t.isAlive’ returns true.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
true
Answer: b
Explanation: Daemon thread runs in the background and does not prevent JVM from terminating. Child of daemon
thread is also daemon thread.
Answer: d
Explation: Thread scheduler decides the priority of the thread execution. This cannot guarantee that higher priority
thread will be executed first, it depends on thread scheduler implementation that is OS dependent.
5. Deadlock is a situation when thread is waiting for other thread to release acquired object?
a) True
b) False
View Answer
Answer: a
Explanation: Deadlock is java programming situation where one thread waits for an object lock that is acquired by
other thread and vice-versa.
Answer: c
Explanation: To avoid deadlock situation in Java programming do not execute foreign code while holding a lock.
7. What is true about threading?
a) run() method calls start() method and runs the code
b) run() method creates new thread
c) run() method can be called directly without start() method being called
d) start() method creates new thread and calls code written in run() metho
View Answer
Answer: d
Explanation: start() eventually calls run() method. Start() method creates thread and calls the code written inside run
method.
Answer: a
Explanation: Thread(Runnable a, String str) is a valid constructor for thread. Thread() is also a valid constructor.
Answer: b
Explanation: notify() wakes up a single thread which is waiting for this object.
10. Which of the following will ensure the thread will be in running state?
a) yield()
b) notify()
c) wait()
d) Thread.killThread()
View Answer
Answer: c
Explanation: wait() always causes the current thread to go into the object’s wait pool. Hence, using this in a thread
will keep it in running state.
This section of our 1000+ Java MCQs focuses on creating threads in Java Programming Language.
Answer: d
Explanation: Polling is a usually implemented by looping in CPU is wastes CPU’s time, one thread being executed
depends on other thread output and the other thread depends on the response on the data given to the first thread.
In such situation CPU’s time is wasted, in Java this is avoided by using methods wait(), notify() and notifyAll().
3. Which of these method is used to tell the calling thread to give up monitor and go to sleep until some other
thread enters the same monitor?
a) wait()
b) notify()
c) notifyAll()
d) sleep()
View Answer
Answer: a
Explanation: wait() method is used to tell the calling thread to give up monitor and go to sleep until some other
thread enters the same monitor. This helps in avoiding polling and minimizes CPU’s idle time.
4. Which of these method wakes up the first thread that called wait()?
a) wake()
b) notify()
c) start()
d) notifyAll()
View Answer
Answer: b
Explanation: None.
Answer: d
Explanation: notifyAll() wakes up all the threads that called wait() on the same object. The highest priority thread will
run first.
Answer: a
Explanation: When two or more threads need to access the same shared resource, they need some way to ensure
that the resource will be used by only one thread at a time, the process by which this is achieved is called
synchronization
2. {
3. Thread t;
4. String name;
5. newthread(String threadname)
6. {
7. name = threadname;
8. t = new Thread(this,name);
9. t.start();
10. }
12. {
13. }
14.
15. }
17. {
19. {
22. try
23. {
24. obj1.t.wait();
25. System.out.print(obj1.t.isAlive());
26. }
27. catch(Exception e)
28. {
30. }
31. }
32. }
a) true
b) false
c) Main thread interrupted
d) None of the mentioned
View Answer
Answer: c
Explanation: obj1.t.wait() causes main thread to go out of processing in sleep state hence causes exception and
“Main thread interrupted” is printed.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Main thread interrupted
2. {
3. Thread t;
4. String name;
5. newthread(String threadname)
6. {
7. name = threadname;
8. t = new Thread(this,name);
9. t.start();
10. }
12. {
13. }
14.
15. }
17. {
19. {
22. try
23. {
24. Thread.sleep(1000);
25. System.out.print(obj1.t.isAlive());
26. }
27. catch(InterruptedException e)
28. {
30. }
31. }
32. }
a) true
b) false
c) Main thread interrupted
d) None of the mentioned
View Answer
Answer: b
Explanation: Thread.sleep(1000) has caused all the threads to be suspended for some time, hence onj1.t.isAlive()
returns false.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
false
2. {
3. Thread t;
4. String name;
5. newthread(String threadname)
6. {
7. name = threadname;
8. t = new Thread(this,name);
9. t.start();
10. }
12. {
13. }
14.
15. }
17. {
19. {
22. try
23. {
24. System.out.print(obj1.t.equals(obj2.t));
25. }
26. catch(Exception e)
27. {
29. }
30. }
31. }
a) true
b) false
c) Main thread interrupted
d) None of the mentioned
View Answer
Answer: b
Explanation: Both obj1 and obj2 have threads with different name that is “one” and “two” hence
obj1.t.equals(obj2.t) returns false.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
false
2. {
3. Thread t;
4. newthread()
5. {
6. t1 = new Thread(this,"Thread_1");
7. t2 = new Thread(this,"Thread_2");
8. t1.start();
9. t2.start();
10. }
12. {
13. t2.setPriority(Thread.MAX_PRIORITY);
14. System.out.print(t1.equals(t2));
15. }
16. }
18. {
20. {
22. }
23. }
a) true
b) false
c) truetrue
d) falsefalse
View Answer
Answer: d
Explanation: This program was previously done by using Runnable interface, here we have used Thread class. This
shows both the method are equivalent, we can use any of them to create a thread.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
falsefalse
This section of our 1000+ Java MCQs focuses on creating threads in Java Programming Language.
Answer: c
Explanation: AWT stands for Abstract Window Toolkit, it is used by applets to interact with the user.
2. Which of these is used to perform all input & output operations in Java?
a) streams
b) Variables
c) classes
d) Methods
View Answer
Answer: a
Explanation: Like in any other language, streams are used for input and output operations.
Answer: c
Explanation: Java defines only two types of streams – Byte stream and character stream.
4. Which of these classes are used by Byte streams for input and output operation?
a) InputStream
b) InputOutputStream
c) Reader
d) All of the mentioned
View Answer
Answer: a
Explanation: Byte stream uses InputStream and OutputStream classes for input and output operation.
5. Which of these classes are used by character streams for input and output operations?
a) InputStream
b) Writer
c) ReadStream
d) InputOutputStream
View Answer
Answer: b
Explanation: Character streams uses Writer and Reader classes for input & output operations.
Answer: d
Explanation: None.
1. class Input_Output
2. {
4. {
5. char c;
7. do
8. {
9. c = (char) obj.read();
10. System.out.print(c);
12. }
13. }
a) abcqfgh
b) abc
c) abcq
d) abcqfghq
View Answer
Answer: c
Explanation: None.
Output:
$ javac Input_Output.java
$ java Input_Output
abcq
1. class Input_Output
2. {
4. {
5. char c;
7. do
8. {
9. c = (char) obj.read();
10. System.out.print(c);
11. } while(c!='\'');
12. }
13. }
a) abc’
b) abcdef/’
c) abc’def/’egh
d) abcqfghq
View Answer
Answer: a
Explanation: \’ is used for single quotes that is for representing ‘ .
Output:
$ javac Input_Output.java
$ java Input_Output
abc’
1. class output
2. {
3. public static void main(String args[])
4. {
6. System.out.println(c.length());
7. }
8. }
a) 4
b) 5
c) 6
d) 7
View Answer
Answer: b
Explanation: length() method is used to obtain length of StringBuffer object, length of “Hello” is 5.
Output:
$ javac output.java
$ java output
5
1. class output
2. {
4. {
6. StringBuffer s2 = s1.reverse();
7. System.out.println(s2);
8. }
9. }
a) Hello
b) olleH
c) HelloolleH
d) olleHHello
View Answer
Answer: b
Explanation: reverse() method reverses all characters. It returns the reversed object on which it was called.
Output:
$ javac output.java
$ java output
olleH
This section of our 1000+ Java MCQs focuses on reading console inputs in Java Programming Language.
Answer: a
Explanation: read method throws IOException.
Answer: c
Explanation: None.
3. Which of these class is used to read characters and strings in Java from console?
a) BufferedReader
b) StringReader
c) BufferedStreamReader
d) InputStreamReader
View Answer
Answer: a
Explanation: None.
4. Which of these classes are used by Byte streams for input and output operation?
a) InputStream
b) InputOutputStream
c) Reader
d) All of the mentioned
View Answer
Answer: a
Explanation: Byte stream uses InputStream and OutputStream classes for input and output operation.
Answer: c
Explanation: None.
7. What is the output of this program if input given is “Hello stop World”?
1. class Input_Output
2. {
4. {
5. string str;
7. do
8. {
10. System.out.print(str);
11. } while(!str.equals("strong"));
12. }
13. }
a) Hello
b) Hello stop
c) World
d) Hello stop World
View Answer
Answer: d
Explanation: “stop” will be able to terminate the do-while loop only when it occurs singly in a line. “Hello stop
World” does not terminate the loop.
Output:
$ javac Input_Output.java
$ java Input_Output
Hello stop World
2. {
4. {
7. c.append(c1);
8. System.out.println(c);
9. }
10. }
a) Hello
b) World
c) Helloworld
d) Hello World
View Answer
Answer: d
Explanation: append() method of class StringBuffer is used to concatenate the string representation to the end of
invoking string.
Output:
$ javac output.java
$ java output
Hello World
1. class output
2. {
4. {
6. s1.setCharAt(1,x);
7. System.out.println(s1);
8. }
9. }
a) xello
b) xxxxx
c) Hxllo
d) Hexlo
View Answer
Answer: c
Explanation: None.
Output:
$ javac output.java
$ java output
Hxllo
1. class Input_Output
2. {
4. {
5. char c;
7. do
8. {
9. c = (char) obj.read();
10. System.out.print(c);
12. }
13. }
a) abc’
b) abcdef/’
c) abc’def/’egh
d) abcqfghq
View Answer
Answer: a
Explanation: \’ is used for single quotes that is for representing ‘ .
Output:
$ javac Input_Output.java
$ java Input_Output
abc’
This section of our 1000+ Java MCQs focuses on writing console outputs in Java Programming Language.
Answer: d
Explanation: print() and println() are defined under the class PrintStream, System.out is the byte stream used by
these methods .
Answer: d
Explanation: None.
3. Which of these class is used to create an object whose character sequence is mutable?
a) String()
b) StringBuffer()
c) Both of the mentioned
d) None of the mentioned
View Answer
Answer: b
Explanation: StringBuffer represents growable and writeable character sequence.
Answer: a
Explanation: reverse() method reverses all characters. It returns the reversed object on which it was called.
Answer: b
Explanation: Character streams uses Writer and Reader classes for input & output operations.
Answer: a
Explanation: reverse() method reverses all characters. It returns the reversed object on which it was called.
1. class output
2. {
4. {
7. }
8. }
a) 6 4 6 9
b) 5 4 5 9
c) 7 8 8 9
d) 4 3 6 9
View Answer
Answer: a
Explantion: indexof(‘c’) and lastIndexof(‘c’) are pre defined function which are used to get the index of first and last
occurrence of
the character pointed by c in the given array.
Output:
$ javac output.java
$ java output
6469
1. class output
2. {
4. {
6. StringBuffer s2 = s1.reverse();
7. System.out.println(s2);
8. }
9. }
a) Hello
b) olleH
c) HelloolleH
d) olleHHello
View Answer
Answer: b
Explanation: reverse() method reverses all characters. It returns the reversed object on which it was called.
Output:
$ javac output.java
$ java output
olleH
1. class output
2. {
4. {
7. System.out.println(s1);
8. }
9. }
a) HelloGoodWorld
b) HellGoodoWorld
c) HellGood oWorld
d) Hello Good World
View Answer
Answer: d
Explanation: The insert() method inserts one string into another. It is overloaded to accept values of all simple types,
plus String and Objects. Sting is inserted into invoking object at specified position. “Good ” is inserted in “Hello
World” T index 6 giving “Hello Good World”.
output:
$ javac output.java
$ java output
Hello Good World
1. class output
2. {
3. public static void main(String args[])
4. {
7. {
8. if(Character.isDigit(c[i]))
9. System.out.println(c[i]" is a digit");
10. if(Character.isWhitespace(c[i]))
12. if(Character.isUpperCase(c[i]))
14. if(Character.isUpperCase(c[i]))
16. i = i + 3;
17. }
18. }
19. }
Answer: a
Explanation: Character.isDigit(c[i]),Character.isUpperCase(c[i]),Character.isWhitespace(c[i]) are the function of
library java.lang
they are used to find weather the given character is of specified type or not. They return true or false i:e Boolean
variable.
Output:
$ javac output.java
$ java output
a is a lower case Letter
is White space character
Java Questions & Answers – Reading & Writing Files
This section of our 1000+ Java MCQs focuses on reading & writing files in Java Programming Language.
Answer: b
Explanation: None.
2. Which of these exception is thrown in cases when the file specified for writing it not found?
a) IOException
b) FileException
c) FileNotFoundException
d) FileInputException
View Answer
Answer: c
Explanation: In cases when the file specified is not found, then FileNotFoundException is thrown by java run-time
system, earlier versions of java used to throw IOException but after Java 2.0 they throw FileNotFoundException.
Answer: b
Explanation: Each time read() is called, it reads a single byte from the file and returns the byte as an integer value.
read() returns -1 when the end of the file is encountered.
4. Which of these values is returned by read() method is end of file (EOF) is encountered?
a) 0
b) 1
c) -1
d) Null
View Answer
Answer: c
Explanation: Each time read() is called, it reads a single byte from the file and returns the byte as an integer value.
read() returns -1 when the end of the file is encountered.
Answer: c
Explanation: None.
1. import java.io.*;
2. class filesinputoutput
3. {
5. {
7. System.out.print(obj.available());
8. }
9. }
Answer: c
Explanation: obj.available() returns the number of bytes.
Output:
$ javac filesinputoutput.java
$ java filesinputoutput
1422
(Output will be different in your case)
1. import java.io.*;
3. {
4. public static void main(String[] args)
5. {
10. {
11. int c;
13. {
14. if(i == 0)
15. {
16. System.out.print(Character.toUpperCase((char)c));
17. obj2.write(1);
18. }
19. }
20. System.out.print(obj2);
21. }
22. }
23. }
a) AaBaCa
b) ABCaaa
c) AaaBaaCaa
d) AaBaaCaaa
View Answer
Answer: d
Explanation: None.
Output:
$ javac filesinputoutput.java
$ java filesinputoutput
AaBaaCaaa
1. import java.io.*;
2. class Chararrayinput
3. {
5. {
12. int i;
13. try
14. {
16. {
17. System.out.print((char)i);
18. }
19. }
21. {
22. e.printStackTrace();
23. }
24. }
25. }
a) abc
b) abcd
c) abcde
d) abcdef
View Answer
Answer: a
Explanation: None.
Output:
$ javac Chararrayinput.java
$ java Chararrayinput
abc
10. What is the output of this program?
1. import java.io.*;
2. class Chararrayinput
3. {
5. {
12. int i;
13. int j;
14. try
15. {
17. {
18. System.out.print((char)i);
19. }
20. }
22. {
23. e.printStackTrace();
24. }
25. }
26. }
a) abc
b) abcd
c) abcde
d) none of the mentioned
View Answer
Answer: d
Explanation: No output is printed. CharArrayReader object input1 contains string “abcdefgh” whereas object input2
contains string “bcde”, when while((i=input1.read())==(j=input2.read())) is executed the starting character of each
object is compared since they are unequal control comes out of loop and nothing is printed on the screen.
Output:
$ javac Chararrayinput.java
$ java Chararrayinput
This section of our 1000+ Java MCQs focuses on Applets fundamentals in Java Programming Language.
Answer: b
Explanation: Whenever the applet requires to redraw its output, it is done by using method paint().
Answer: c
Explanation: drawString() method is defined in Graphics class, it is used to output a string in an applet.
Answer: c
Explanation: AWT stands for Abstract Window Toolkit, it is used by applets to interact with the user.
Answer: b
Explanation: paint() is an abstract method defined in AWT.
5. Which of these modifiers can be used for a variable so that it can be accessed from any thread or parts of a
program?
a) transient
b) volatile
c) global
d) No modifier is needed
View Answer
Answer: b
Explanation: The volatile modifier tells the compiler that the variable modified by volatile can be changed
unexpectedly by other part of the program. Specially used in situations involving multithreading.
6. Which of these operators can be used to get run time information about an object?
a) getInfo
b) Info
c) instanceof
d) getinfoof
View Answer
Answer: c
Explanation: None.
1. import java.awt.*;
2. import java.applet.*;
4. {
6. {
8. }
9. }
a) A Simple Applet
b) A Simple Applet 20 20
c) Compilation Error
d) Runtime Error
View Answer
Answer: a
Explanation: None.
Output:
A Simple Applet
(Output comes in a new java application)
2. import java.applet.*;
4. {
6. {
8. }
9. }
a) 20
b) 50
c) 100
d) System dependent
View Answer
Answer: a
Explanation: the code in pain() method – g.drawString(“A Simple Applet”,20,20); draws a applet box of length 20 and
width 20.
1. import java.awt.*;
2. import java.applet.*;
4. {
5. Graphic g;
7. }
a) 20
b) Default value
c) Compilation Error
d) Runtime Error
View Answer
Answer: c
Explanation: To implement the method drawString we need first need to define abstract method of AWT that is
paint() method. Without paint() method we can not define and use drawString or any Graphic class methods.
1. import java.io.*;
2. class Chararrayinput
3. {
5. {
12. int i;
13. int j;
14. try
15. {
17. {
18. System.out.print((char)i);
19. }
20. }
22. {
23. e.printStackTrace();
24. }
25. }
26. }
a) abc
b) abcd
c) abcde
d) none of the mentioned
View Answer
Answer: d
Explanation: No output is printed. CharArrayReader object input1 contains string “abcdefgh” whereas object input2
contains string “bcde”, when while((i=input1.read())==(j=input2.read())) is executed the starting character of each
object is compared since they are unequal control comes out of loop and nothing is printed on the screen.
Output:
$ javac Chararrayinput.java
$ java Chararrayinput
This section of our 1000+ Java MCQs focuses 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
View Answer
Answer: a
Explanation: java.text allows formatting, searching and manipulating text.
Answer: c
Explanation: 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()
View Answer
Answer: b
Explanation: 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
View Answer
Answer: b
Explanation: 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.
Answer: a
Explanation: 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
View Answer
Answer: a
Explanation: By using format string “w” we can print week in a year whereas by using ‘W’ we can print week of
month.
1. import java.text.*;
2. import java.util.*;
3. class Date_formatting
4. {
6. {
8. SimpleDateFormat sdf;
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
View Answer
Answer: c
Explanation: None.
Output:
$ javac Date_formatting.java
$ java Date_formatting
55:03:04
1. import java.text.*;
2. import java.util.*;
3. class Date_formatting
4. {
6. {
8. SimpleDateFormat sdf;
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
View Answer
Answer: d
Explanation: 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
55:03:04
1. import java.text.*;
2. import java.util.*;
3. class Date_formatting
4. {
6. {
7. Date date = new Date();
8. SimpleDateFormat sdf;
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
View Answer
Answer: a
Explanation: None.
Output:
$ javac Date_formatting.java
$ java Date_formatting
Mon Jul 15 2013
1. import java.text.*;
2. import java.util.*;
3. class Date_formatting
4. {
6. {
8. SimpleDateFormat sdf;
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
View Answer
Answer: d
Explanation: format string “z” is used to print time zone.
Output:
$ javac Date_formatting.java
$ java Date_formatting
PDT
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Regular Expression”.
Answer: d
Explanation: java.util.regex consists 3 classes. PatternSyntaxException indicates syntax error in regex.
Answer: c
Explanation: macther() method is invoked using matcher object which interpretes pattern and performs match
operations in the input string.
Answer: a
Explanation: object of Pattern class can represent compiled regular expression.
Answer: a
Explanation: 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
View Answer
Answer: b
Explanation: \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
View Answer
Answer: a
Explanation: \z is used to match end of the entire string in regular expression in java.
Answer: a
Explanation: public int end(int group) returns offset from last character of the subsequent group.
Answer: d
Explanation: 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
View Answer
Answer: c
Explanation: public int start() returns index of the previous match in the input string.
This section of our 1000+ Java MCQs focuses on basics of event handling in Java Programming Language.
1. Which of these packages contains all the classes and methods required for even handling in Java?
a) java.applet
b) java.awt
c) java.event
d) java.awt.event
View Answer
Answer: d
Explanation: Most of the event to which an applet responds is generated by user. Hence they are in Abstract
Window Kit package, java.awt.event.
Answer: a
Explanation: An event is an object that describes a state change in a source.
Answer: c
Explanation: None.
Answer: b
Explanation: A listener is a object that is notified when an event occurs. It has two major requirements first, it must
have been registered with one or more sources to receive notification about specific event types, and secondly it
must implement methods to receive and process these notifications.
Answer: d
Explanation: None.
Answer: a
Explanation: getID() can be used to determine the type of an event.
Answer: a
Explanation: EventObject class is a super class of all the events and is defined in java.util package.
Answer: d
Explanation: WindowEvent is generated when a window is activated, closed, deactivated, deiconfied, iconfied,
opened or quit.
This section of our 1000+ Java MCQs focuses on packages of Java Programming Language.
Answer: c
Explanation: None.
2. Which of these is a mechanism for naming and visibility control of a class and its content?
a) Object
b) Packages
c) Interfaces
d) None of the Mentioned.
View Answer
Answer: b
Explanation: Packages are both naming and visibility control mechanism. We can define a class inside a package
which is not accessible by code outside the package.
3. Which of this access specifies can be used for a class so that its members can be accessed by a different class in
the same package?
a) Public
b) Protected
c) No Modifier
d) All of the mentioned
View Answer
Answer: d
Explanation: Either we can use public, protected or we can name the class without any specifier.
4. Which of these access specifiers can be used for a class so that it’s members can be accessed by a different class in
the different package?
a) Public
b) Protected
c) Private
d) No Modifier
View Answer
Answer: a
Explanation: None.
Answer: c
Explanation: Operator * is used to import the entire package.
Answer: d
Explanation: A package can be renamed only after renaming the directory in which the classes are stored.
7. Which of the following package stores all the standard java classes?
a) lang
b) java
c) util
d) java.packages
View Answer
Answer: b
Explanation: None.
1. package pkg;
2. class display
3. {
4. int x;
5. void show()
6. {
7. if (x > 1)
10. }
12. {
14. {
18. arr[0].x = 0;
19. arr[1].x = 1;
20. arr[2].x = 2;
22. arr[i].show();
23. }
24. }
Answer: c
Explanation: None.
Output:
$ javac packages.java
$ java packages
2
1. package pkg;
2. class output
3. {
5. {
6. StringBuffer s1 = new StringBuffer("Hello");
7. s1.setCharAt(1, x);
8. System.out.println(s1);
9. }
10. }
a) xello
b) xxxxx
c) Hxllo
d) Hexlo
View Answer
Answer: c
Explanation: None.
Output:
$ javac output.java
$ java output
Hxllo
1. package pkg;
2. class output
3. {
5. {
8. System.out.println(s1);
9. }
10. }
Answer: d
Explanation: Since output.class file is not in the directory pkg in which class output is defined, program will not be
able to run.
output:
$ javac output.java
$ java output
can not find file output.class
This section of our 1000+ Java MCQs focuses on interfaces of Java Programming Language.
Answer: a
Explanation: None.
2. Which of these can be used to fully abstract a class from its implementation?
a) Objects
b) Packages
c) Interfaces
d) None of the Mentioned
View Answer
Answer: c
Explanation: None.
Answer: a
Explanation: Access specifier of interface is either public or no specifier. When no access specifier is used then
default access specifier is used due to which interface is available only to other members of the package in which it is
declared, when declared public it can be used by any code.
Answer: c
Explanation: interface is inherited by a class using implements.
5. Which of the following is correct way of implementing an interface salary by class manager?
a) class manager extends salary {}
b) class manager implements salary {}
c) class manager imports salary {}
d) none of the mentioned
View Answer
Answer: b
Explanation: None.
Answer: d
Explanation: All methods and variables are implicitly public if interface is declared public.
7. Which of the following package stores all the standard java classes?
a) lang
b) java
c) util
d) java.packages
View Answer
Answer: b
Explanation: None.
1. interface calculate
2. {
4. }
6. {
7. int x;
9. {
11. }
12. }
14. {
15. public static void main(String args[])
16. {
18. arr.x = 0;
19. arr.cal(2);
20. System.out.print(arr.x);
21. }
22. }
a) 0
b) 2
c) 4
d) None of the mentioned
View Answer
Answer: c
Explanation: None.
Output:
$ javac interfaces.java
$ java interfaces
4
1. interface calculate
2. {
4. }
6. {
7. int x;
9. {
11. }
12. }
14. {
15. int x;
17. {
19. }
20. }
22. {
24. {
27. arr1.x = 0;
28. arr2.x = 0;
29. arr1.cal(2);
30. arr2.cal(2);
32. }
33. }
a) 0 0
b) 2 2
c) 4 1
d) 1 4
View Answer
Answer: c
Explanation: class displayA implements the interface calculate by doubling the value of item, where as class displayB
implements the interface by dividing item by item, therefore variable x of class displayA stores 4 and variable x of
class displayB stores 1.
Output:
$ javac interfaces.java
$ java interfaces
41
1. interface calculate
2. {
3. int VAR = 0;
5. }
7. {
8. int x;
10. {
11. if (item<2)
12. x = VAR;
13. else
15. }
16. }
18. {
19.
21. {
23.
26. arr[0].cal(0);
27. arr[1].cal(1);
28. arr[2].cal(2);
30. }
31. }
a) 0 1 2
b) 0 2 4
c) 0 0 4
d) 0 1 4
View Answer
Answer: c
Explanation: None.
output:
$ javac interfaces.java
$ java interfaces
004
This set of Java Interview Questions and Answers for Experienced people focuses on “Interfaces – 2”.
Answer: a
Explanation: Interface can have either public access specifier or no specifier.The reason is they need to be
implemented by other classes.
Answer: b
Explanation: Concrete class implements interface. They can be instantiated.
Answer: a
Explanation: Concrete classes must implement all methods in an interface.Through interface multiple inheritance is
possible.
Answer: b
Explanation: Interface contains only declaration of the method.
Answer: a
Explanation: By default, interface contains abstract methods.The abstract methods need to be implemented by
concrete classes.
Answer: c
Explanation: The methods of interfaces are always abstract. They provide only method definition.
Answer: a
Explanation: Constructor is not provided by interface as objects cannot be instantiated.
9. What happens when we access the same variable defined in two interfaces implemented by the same class?
a) Compilation failure
b) Runtime Exception
c) The JVM is not able to identify the correct variable
d) The interfaceName.variableName needs to be defined
View Answer
Answer: d
Explanation: The JVM needs to distinctly know which value of variable it needs to use. To avoid confusion to the JVM
interfaceName.variableName is mandatory.
10. Can “abstract” keyword be used with constructor,Initialization Block, Instance Initialization and Static
Initialization Block?
a) True
b) False
View Answer
Answer: b
Explanation: No, Constructor, Static Initialization Block, Instance Initialization Block and variables can not be abstract.
This section of our 1000+ Java MCQs focuses core Java API packages in Java Programming Language.
Answer: b
Explanation: java.awt provides capabilities for graphical user interface.
Answer: d
Explanation: Reflection is the ability of a software to analyze itself. This is provided by java.lang.reflevt package.
3. Which of these package is used for handling security related issues in a program?
a) java.security
b) java.lang.security
c) java.awt.image
d) java.io.security
View Answer
Answer: a
Explanation: java.security handles certificates, keys, digests, signatures, and other security functions.
4. Which of these class allows us to get real time data about private and protected member of a class?
a) java.io
b) GetInformation
c) ReflectPermission
d) MembersPermission
View Answer
Answer: c
Explanation: The ReflectPermission class allows reflection of a private or protected members of a class. This was
added after java 2.0 .
Answer: a
Explanation: java.rmi provides capabilities for remote method invocation.
6. Which of these package is used for all the text related modifications?
a) java.text
b) java.awt
c) java.lang.text
d) java.text.mofify
View Answer
Answer: a
Explanation: java.text provides capabilities for formatting, searching and manipulating text.
1. import java.lang.reflect.*;
2. class Additional_packages
3. {
5. {
6. try
7. {
8. Class c = Class.forName("java.awt.Dimension");
11. System.out.println(constructors[i]);
12. }
14. {
15. System.out.print("Exception");
16. }
17. }
18. }
Answer: a
Explanation: None.
Output:
$ javac Additional_packages.java
$ java Additional_packages
public java.awt.Dimension(java.awt.Dimension)
public java.awt.Dimension()
public java.awt.Dimension(int,int)
1. import java.lang.reflect.*;
2. class Additional_packages
3. {
5. {
6. try
7. {
8. Class c = Class.forName("java.awt.Dimension");
11. System.out.println(fields[i]);
12. }
14. {
15. System.out.print("Exception");
16. }
17. }
18. }
a) Program prints all the constructors of ‘java.awt.Dimension’ package
b) Program prints all the methods of ‘java.awt.Dimension’ package
c) Program prints all the data members of ‘java.awt.Dimension’ package
d) program prints all the methods and data member of ‘java.awt.Dimension’ package
View Answer
Answer: c
Explanation: None.
Output:
$ javac Additional_packages.java
$ java Additional_packages
public int java.awt.Dimension.width
public int java.awt.Dimension.height
1. import java.awt.*;
2. import java.applet.*;
4. {
5. Graphic g;
7. }
a) 20
b) Default value
c) Compilation Error
d) Runtime Error
View Answer
Answer: c
Explanation: To implement the method drawString we need first need to define abstract method of AWT that is
paint() method. Without paint() method we cannot define and use drawString or any Graphic class methods.
1. import java.lang.reflect.*;
2. class Additional_packages
3. {
5. {
6. try
7. {
8. Class c = Class.forName("java.awt.Dimension");
9. Method methods[] = c.getMethods();
11. System.out.println(methods[i]);
12. }
14. {
15. System.out.print("Exception");
16. }
17. }
18. }
Answer: b
Explanation: None.
Output:
$ javac Additional_packages.java
$ java Additional_packages
public int java.awt.Dimension.hashCode()
public boolean java.awt.Dimension.equals(java.lang.Object)
public java.lang.String java.awt.Dimension.toString()
public java.awt.Dimension java.awt.Dimension.getSize()
public void java.awt.Dimension.setSize(double,double)
public void java.awt.Dimension.setSize(int,int)
public void java.awt.Dimension.setSize(java.awt.Dimension)
public double java.awt.Dimension.getHeight()
public double java.awt.Dimension.getWidth()
public java.lang.Object java.awt.geom.Dimension2D.clone()
public void java.awt.geom.Dimension2D.setSize(java.awt.geom.Dimension2D)
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
public final native void java.lang.Object.wait(long)
public final void java.lang.Object.wait(long,int)
public final void java.lang.Object.wait()
This section of our 1000+ Java MCQs focuses on Type interface in Java Programming Language.
1. Why are generics used?
a) Generics make code more fast
b) Generics make code more optimised and readable
c) Generics add stability to your code by making more of your bugs detectable at compile time
d) Generics add stability to your code by making more of your bugs detectable at run time
View Answer
Answer: c
Explanation: Generics add stability to your code by making more of your bugs detectable at compile time.
2. Which of these type parameters is used for a generic class to return and accept any type of object?
a) K
b) N
c) T
d) V
View Answer
Answer: c
Explanation: T is used for type, A type variable can be any non-primitive type you specify: any class type, any
interface type, any array type, or even another type variable.
3. Which of these type parameters is used for a generic class to return and accept a number?
a) K
b) N
c) T
d) V
View Answer
Answer: b
Explanation: N is used for Number.
Answer: b
Explanation: The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the
type parameters (also called type variables) T1, T2, …, and Tn.
5. Which of the following is incorrect statement regarding the use of generics and parameterized types in Java?
a) Generics provide type safety by shifting more type checking responsibilities to the compiler
b) Generics and parameterized types eliminate the need for down casts when using Java Collections
c) When designing your own collections class (say, a linked list), generics and parameterized types allow you to
achieve type safety with just a single class definition as opposed to defining multiple classes
d) All of the mentioned
View Answer
Answer: c
Explanation: None.
6. Which of the following reference types cannot be generic?
a) Anonymous inner class
b) Interface
c) Inner class
d) All of the mentioned
View Answer
Answer: a
Explanation: None.
2. {
4. {
6. box.set(u);
7. boxes.add(box);
8. }
10. {
13. {
16. counter++;
17. }
18. }
20. {
23. BoxDemo.outputBoxes(listOfIntegerBoxes);
24. }
25. }
a) 10
b) Box #0 [10].
c) Box contains [10].
d) Box #0 contains [10].
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.javac
$ java Output
Box #0 contains [10].
2. {
4. java.util.List<Box<U>> boxes)
5. {
7. box.set(u);
8. boxes.add(box);
9. }
11. {
14. {
17. counter++;
18. }
19. }
21. {
22. java.util.ArrayList<Box<Integer>> listOfIntegerBoxes = new java.util.ArrayList<>();
24. BoxDemo.outputBoxes(listOfIntegerBoxes);
25. }
26. }
a) 0
b) 1
c) [1].
d) [0].
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.javac
$ java Output
[0]
1. import java.util.*;
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
16. {
20. gs.push("Hello");
23. gs.push(36);
24. System.out.println(gs.pop());
25. }
26. }
a) Error
b) Hello
c) 36
d) Hello 36
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.javac
$ java Output
Hello 36
2. {
4. java.util.List<Box<U>> boxes)
5. {
7. box.set(u);
8. boxes.add(box);
9. }
11. {
17. counter++;
18. }
19. }
21. {
24. BoxDemo.outputBoxes(listOfIntegerBoxes);
25. }
26. }
a) 10
b) Box #0 [10].
c) Box contains [10].
d) Box #0 contains [10].
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.javac
$ java Output
Box #0 contains [10].
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “JUnits”.
Answer: a
Explanation: JUnit is a testing framework for unit testing.It uses java as a programming platform. It is managed by
junit.org community.
Answer: d
Explanation: JUnits test can be run automatically and they check their own results and provide immediate feedback.
Answer: c
Explanation: @Test is used to annotate method under test, @BeforeEach and @AfterEach are called before and
after each method respectively. @BeforeClass and @AfterClass are called only once for each class.
Answer: d
Explanation: EasyMock, jMock, Mockito, Unitils Mock, PowerMock and JMockit are various mocking framework.
5. Which method is used to verify the actual and expected results in Junits?
a) assert()
b) equals()
c) ==
d) isEqual()
View Answer
Answer: a
Explanation: assert method is used to compare actual and expected results in Junit. It has various implementation
like assertEquals, assertArrayEquals, assertFalse, assertNotNull, etc.
Answer: c
Explanation: == is used to compare the objects not the content. assertSame() method compares to check if actual
and expected are the same objects. It does not compare their content.
7. How to let junits know that they need to be run using PowerMock?
a) @PowerMock
b) @RunWith(PowerMock)
c) @RunWith(Junits)
d) @RunWith(PowerMockRunner.class)
View Answer
Answer: d
Explanation: @RunWith(PowerMockRunner.class) signifies to use PowerMock JUnit runner. Along with that
@PrepareForTest(User.class) is used to declare the class being tested. mockStatic(Resource.class) is used to mock
the static methods.
Answer: c
Explanation: Mockito.when(mockList.size()).thenReturn(100); assertEquals(100, mockList.size()); is the usage to
implement if and then behavior.
9. What is used to inject mock fields into the tested object automatically?
a) @InjectMocks
b) @Inject
c) @InjectMockObject
d) @Mock
View Answer
Answer: a
Explanation: @InjectMocks annotation is used to inject mock fields into the tested object automatically.
@InjectMocks
MyDictionary dic = new MyDictionary();
1. <dependency>
2. <groupId>junit</groupId>
3. <artifactId>junit</artifactId>
4. <version>4.8.1</version>
5. </dependency>
b)
1. <dependency>
2. <groupId>org.junit</groupId>
3. <artifactId>junit</artifactId>
4. <version>4.8.1</version>
5. </dependency>
c)
1. <dependency>
2. <groupId>mock.junit</groupId>
3. <artifactId>junit</artifactId>
4. <version>4.8.1</version>
5. </dependency>
d)
1. <dependency>
2. <groupId>junits</groupId>
3. <artifactId>junit</artifactId>
4. <version>4.8.1</version>
5. </dependency>
View Answer
Answer: a
Explanation: JUnits can be used using dependency tag in maven in pom.xml. The version as desired and available in
repository can be used.
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Java 8 features”.
Answer: b
Explanation: Serialization is not introduced with Java 8. It was introduced with earlier version of Java.
Answer: a
Explanation: BooleanSupplier function interface represents supplier of Boolean-valued results.
3. What is the return type of lambda expression?
a) String
b) Object
c) void
d) Function
View Answer
Answer: d
Explanation: Lambda expression enables us to pass functionality as an argument to another method, such as what
action should be taken when someone clicks a button.
Answer: c
Explanation: Traversing through forEach method of Iterable with anonymous class.
1. StringList.forEach(new Consumer<Integer>()
2. {
4. {
5. }
6. });
9. StringList.forEach(action);
10. }
11. }
Answer: a
Explanation: Sequential stream and parallel stream are two types of stream provided by java.
Answer: b
Explanation: Executors newWorkStealingPool() method to create a work-stealing thread pool using all available
processors as its target parallelism level.
Answer: b
Explanation: Files.lines(Path path) that reads all lines from a file as a Stream.
Answer: c
Explanation: Optional object is used to represent null with absent value. This class has various utility methods to
facilitate code to handle values as ‘available’ or ‘not available’ instead of checking null values.
Answer: a
Explanation: Nashorn provides 2 to 10 times faster in terms of performance, as it directly compiles the code in
memory and passes the bytecode to JVM. Nashorn uses invokedynamics feature.
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “File and Directory”.
Answer: c
Explanation: New directory can be created using Files.createDirectory(path, fileAttribute).
Answer: d
Explanation: File accessibilty can be checked using isReadable(Path), isWritable(Path), and isExecutable(Path).
Answer: a
Explanation: The delete(Path) method deletes the file or throws an exception if the deletion fails. If file does not
exist a NoSuchFileException is thrown.
Answer: a
Explanation: Files.copy(source, target) is used to copy a file from one location to another. There are various options
available like REPLACE_EXISTING, COPY_ATTRIBUTES and NOFOLLOW_LINKS.
Answer: b
Explanation: size(Path) returns the size of the specified file in bytes.
Answer: a
Explanation: Java 8 provides Files.readAllLines() which allows us to read entire file in one task. We do not need to
worry about readers and writers.
Answer: c
Explanation: createSymbolicLink() creates a symbolic link to a target.
Answer: a
Explanation: lines.filter(line -> line.contains(“===—> Loaded package”)) can be used to filter out.
9. Which jar provides FileUtils which contains methods for file operations?
a) file
b) apache commons
c) file commons
d) dir
View Answer
Answer: b
Explanation: FileUtils is a part of apache commons which provides various methods for file operations like
writeStringToFile.
Answer: c
Explanation: Any class that has implemented Autocloseable releases the I/O resources.
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Generics”.
Answer: c
Explanation: Generics add stability to your code by making more of your bugs detectable at compile time.
2. Which of these type parameters is used for a generic class to return and accept any type of object?
a) K
b) N
c) T
d) V
View Answer
Answer: c
Explanation: T is used for type, A type variable can be any non-primitive type you specify: any class type, any
interface type, any array type, or even another type variable..
3. Which of these type parameters is used for a generic class to return and accept a number?
a) K
b) N
c) T
d) V
View Answer
Answer: b
Explanation: N is used for Number.
Answer: b
Explanation: The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the
type parameters (also called type variables) T1, T2, …, and Tn.
5. Which of the following is incorrect statement regarding the use of generics and parameterized types in Java?
a) Generics provide type safety by shifting more type checking responsibilities to the compiler
b) Generics and parameterized types eliminate the need for down casts when using Java Collections
c) When designing your own collections class (say, a linked list), generics and parameterized types allow you to
achieve type safety with just a single class definition as opposed to defining multiple classes
d) All of the mentioned
View Answer
Answer: c
Explanation: None.
Answer: a
Explanation: None.
1. import java.util.*;
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
16. {
18. {
21. System.out.println(gs.pop());
22. }
23. }
a) H
b) Hello
c) Runtime Error
d) Compilation Error
View Answer
Answer: b
Explanation: None.
Output:
$ javac Output.javac
$ java Output
Hello
1. import java.util.*;
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
16. {
18. {
19. genericstack <Integer> gs = new genericstack<Integer>();
20. gs.push(36);
21. System.out.println(gs.pop());
22. }
23. }
a) 0
b) 36
c) Runtime Error
d) Compilation Error
View Answer
Answer: b
Explanation: None.
Output:
$ javac Output.javac
$ java Output
36
1. import java.util.*;
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
16. {
20. gs.push("Hello");
23. gs.push(36);
24. System.out.println(gs.pop());
25. }
26. }
a) Error
b) Hello
c) 36
d) Hello 36
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.javac
$ java Output
Hello 36
1. import java.util.*;
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
16. {
18. {
20. gs.push(36);
21. System.out.println(gs.pop());
22. }
23. }
a) H
b) Hello
c) Runtime Error
d) Compilation Error
View Answer
Answer: d
Explanation: genericstack’s object gs is defined to contain a string parameter but we are sending an integer
parameter, which results in compilation error.
Output:
$ javac Output.javac
$ java Output
Hello
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Generic Methods”.
Answer: c
Explanation: Generic methods are methods that introduce their own type parameters. This is similar to declaring a
generic type, but the type parameter’s scope is limited to the method where it is declared. Static and non-static
generic methods are allowed, as well as generic class constructors.
2. Which of these type parameters is used for a generic methods to return and accept any type of object?
a) K
b) N
c) T
d) V
View Answer
Answer: c
Explanation: T is used for type, A type variable can be any non-primitive type you specify: any class type, any
interface type, any array type, or even another type variable..
3. Which of these type parameters is used for a generic methods to return and accept a number?
a) K
b) N
c) T
d) V
View Answer
Answer: b
Explanation: N is used for Number.
Answer: b
Explanation: The syntax for a generic method includes a type parameter, inside angle brackets, and appears before
the method’s return type. For static generic methods, the type parameter section must appear before the method’s
return type.
5. Which of the following is incorrect statement regarding the use of generics and parameterized types in Java?
a) Generics provide type safety by shifting more type checking responsibilities to the compiler
b) Generics and parameterized types eliminate the need for down casts when using Java Collections
c) When designing your own collections class (say, a linked list), generics and parameterized types allow you to
achieve type safety with just a single class definition as opposed to defining multiple classes
d) All of the mentioned
View Answer
Answer: c
Explanation: None.
Answer: a
Explanation: Type inference, allows you to invoke a generic method as an ordinary method, without specifying a type
between angle brackets.
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
16. {
18. {
20. gs.push("Hello");
21. System.out.println(gs.pop());
22. }
23. }
a) H
b) Hello
c) Runtime Error
d) Compilation Error
View Answer
Answer: b
Explanation: None.
Output:
$ javac Output.javac
$ java Output
Hello
8. What is the output of this program?
1. import java.util.*;
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
16. {
18. {
20. gs.push(36);
21. System.out.println(gs.pop());
22. }
23. }
a) 0
b) 36
c) Runtime Error
d) Compilation Error
View Answer
Answer: b
Explanation: None.
Output:
$ javac Output.javac
$ java Output
36
1. import java.util.*;
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
16. {
18. {
20. gs.push("Hello");
23. gs.push(36);
24. System.out.println(gs.pop());
25. }
26. }
a) Error
b) Hello
c) 36
d) Hello 36
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.javac
$ java Output
Hello 36
1. import java.util.*;
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
16. {
18. {
20. gs.push(36);
21. System.out.println(gs.pop());
22. }
23. }
a) H
b) Hello
c) Runtime Error
d) Compilation Error
View Answer
Answer: d
Explanation: genericstack’s object gs is defined to contain a string parameter but we are sending an integer
parameter, which results in compilation error.
Output:
$ javac Output.javac
$ java Output
Hello
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Restrictions on Generics”.
Answer: c
Explanation: None.
Answer: c
Explanation: It is not possible to create generic type instances. Example – “E obj = new E()” will give a compilation
error.
Answer: a
Explanation: None.
Answer: d
Explanation: we cannot Create, Catch, or Throw Objects of Parameterized Types as generic class cannot extend the
Throwable class directly or indirectly.
Answer: a
Explanation: Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same
Raw Type.
2. {
4. java.util.List<Box<U>> boxes)
5. {
7. box.set(u);
8. boxes.add(box);
9. }
11. {
14. {
17. counter++;
18. }
19. }
20. public static void main(String[] args)
21. {
24. BoxDemo.outputBoxes(listOfIntegerBoxes);
25. }
26. }
a) 10
b) Box #0 [10].
c) Box contains [10].
d) Box #0 contains [10].
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.java
$ java Output
Box #0 contains [10]
1. import java.util.*;
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
18. {
20. gs.push("Hello");
23. gs.push(36);
24. System.out.println(gs.pop());
25. }
26. }
a) Error
b) Hello
c) 36
d) Hello 36
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.java
$ java Output
Hello 36
1. import java.util.*;
2. class Output
3. {
5. {
6. double s = 0.0;
8. s += n.doubleValue();
9. return s;
10. }
14. System.out.println(sumOfList(ld));
15. }
16. }
a) 5.0
b) 7.0
c) 8.0
d) 6.0
View Answer
Answer: b
Explanation: None.
Output:
$ javac Output.java
$ java Output
7.0
1. import java.util.*;
2. class Output
3. {
5. {
7. {
8. list.add(i);
9. }
10. }
12. {
14. addnumbers(10.4);
15. System.out.println("getList(2)");
16. }
17. }
a) 1
b) 2
c) 3
d) 6
View Answer
Answer: a
Explanation: None.
Output:
$ javac Output.java
$ java Output
1
1. import java.util.*;
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
16. {
18. {
20. gs.push(36);
21. System.out.println(gs.pop());
22. }
23. }
a) H
b) Hello
c) Runtime Error
d) Compilation Error
View Answer
Answer: d
Explanation: genericstack’s object gs is defined to contain a string parameter but we are sending an integer
parameter, which results in compilation error.
Output:
$ javac Output.java
$ java Output
Hello
This set of Advanced Java Multiple Choice Questions & Answers (MCQs) focuses on “JDBC”.
Answer: d
Explanation: java.util.date contains both date and time. Whereas, java.sql.date contains only date.
Answer: d
Explanation: Since the JDBC connection takes time to establish. Creating connection at the application start-up and
reusing at the time of requirement, helps performance of the application.
Answer: c
Explanation: PreparedStatement in Java improves performance and also prevents from SQL injection.
Answer: a
Explanation: java.sql.Time contains only time. Whereas, java.sql.TimeStamp contains both time and date.
Answer: c
Explanation: setAutoCommit(false) does not commit transaction automatically after each query. That saves lot of
time of the execution and hence improves performance.
Answer: c
Explanation: CallableStatement is used in JDBC to call stored procedure from Java program.
Answer: a
Explanation: setMaxRows(int i) method is used to limit the number of rows that the database returns from the
query.
Answer: d
Explanation: addBatch() is a method of JDBC batch process. It is faster in processing than executing one statement at
a time.
Answer: a
Explanation: rollback() method is used to rollback the transaction. It will rollback all the changes made by the
transaction.
Answer: d
Explanation: TRANSACTION_NONREPEATABLE_READ is not a JDBC connection isolation level.
This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Wildcards”.
Answer: a
Explanation: In generic code, the question mark (?), called the wildcard, represents an unknown type.
Answer: a
Explanation: The wildcard can be used in a variety of situations: as the type of a parameter, field, or local variable;
sometimes as a return type (though it is better programming practice to be more specific). The wildcard is never
used as a type argument for a generic method invocation, a generic class instance creation, or a supertype.
4. Which of these is an correct way making a list that is upper bounded by class Number?
a) List<? extends Number>
b) List<extends ? Number>
c) List(? extends Number)
d) List(? UpperBounds Number)
View Answer
Answer: a
Explanation: None.
5. Which of the following is incorrect statement regarding the use of generics and parameterized types in Java?
a) Generics provide type safety by shifting more type checking responsibilities to the compiler
b) Generics and parameterized types eliminate the need for down casts when using Java Collections
c) When designing your own collections class (say, a linked list), generics and parameterized types allow you to
achieve type safety with just a single class definition as opposed to defining multiple classes
d) All of the mentioned
View Answer
Answer: c
Explanation: None.
6. Which of the following keywords are used for lower bounding a wild card?
a) extends
b) super
c) class
d) lower
View Answer
Answer: b
Explanation: A lower bounded wildcard is expressed using the wildcard character (‘?’), following by the super
keyword, followed by its lower bound: .
1. import java.util.*;
2. class Output
3. {
5. {
6. double s = 0.0;
8. s += n.doubleValue();
9. return s;
10. }
12. {
14. System.out.println(sumOfList(li));
15. }
16. }
a) 0
b) 4
c) 5.0
d) 6.0
View Answer
Answer: d
Explanation: None.
Output:
$ javac Output.javac
$ java Output
6.0
1. import java.util.*;
2. class Output
3. {
5. {
6. double s = 0.0;
8. s += n.doubleValue();
9. return s;
10. }
12. {
14. System.out.println(sumOfList(ld));
15. }
16. }
a) 5.0
b) 7.0
c) 8.0
d) 6.0
View Answer
Answer: b
Explanation: None.
Output:
$ javac Output.javac
$ java Output
7.0
1. import java.util.*;
2. class Output
3. {
5. {
7. {
8. list.add(i);
9. }
10. }
12. {
14. addnumbers(10.4);
15. System.out.println("getList(2)");
16. }
17. }
a) 1
b) 2
c) 3
d) 6
View Answer
Answer: a
Explanation: None.
Output:
$ javac Output.javac
$ java Output
1
1. import java.util.*;
3. {
6. {
7. stk.push(obj);
8. }
9. public E pop()
10. {
13. }
14. }
16. {
18. {
20. gs.push(36);
21. System.out.println(gs.pop());
22. }
23. }
a) H
b) Hello
c) Runtime Error
d) Compilation Error
View Answer
Answer: d
Explanation: genericstack’s object gs is defined to contain a string parameter but we are sending an integer
parameter, which results in compilation error.
Output:
$ javac Output.javac
$ java Output
Hello