0% found this document useful (0 votes)
50 views443 pages

Java Questions

The document contains multiple choice questions about Java concepts including OOPs concepts like inheritance, encapsulation and polymorphism. It also contains questions about Java components like JDK, JRE, JVM and class fundamentals.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
50 views443 pages

Java Questions

The document contains multiple choice questions about Java concepts including OOPs concepts like inheritance, encapsulation and polymorphism. It also contains questions about Java components like JDK, JRE, JVM and class fundamentals.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 443

Java Questions & Answers – Concepts of OOPs

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Concepts of OOPs”.

1. Which of the following is not OOPS concept in Java?


a) Inheritance
b) Encapsulation
c) Polymorphism
d) Compilation
View Answer

Answer: d
Explanation: There are 4 OOPS concepts in Java. Inheritance, Encapsulation, Polymorphism and Abstraction.

2. Which of the following is a type of polymorphism in Java?


a) Compile time polymorphism
b) Execution time polymorphism
c) Multiple polymorphism
d) Multilevel polymorphism
View Answer

Answer: a
Explanation: There are two type of polymorphism in Java. Compile time polymorphism (overloading) and runtime
polymorphism (overriding).

3. When does method overloading is determined?


a) At run time
b) At compile time
c) At coding time
d) At execution time
View Answer

Answer: b
Explanation: Overloading is determined at compile time. Hence, it is also known as compile time polymorphism.

4. When Overloading does not occur?


a) More than one method with same name but different method signature and different number or type of
parameters
b) More than one method with same name, same signature but different number of signature
c) More than one method with same name, same signature, same number of parameters but different type
d) More than one method with same name, same number of parameters and type but different signature
View Answer

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.

10. Method overriding is combination of inheritance and polymorphism?


a) True
b) false
View Answer
Answer: a
Explanation: In order for method overriding, method with same signation in both superclass and subclass is required
with same signature. That satisfies both concepts inheritance and polymorphism.

Java Questions & Answers – JDK-JRE-JIT-JVM

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “JDK-JRE-JIT-JVM”.

1. Which component is used to compile, debug and execute java program?


a) JVM
b) JDK
c) JIT
d) JRE
View Answer

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.

3. Which component is responsible to run java program?


a) JVM
b) JDK
c) JIT
d) JRE
View Answer

Answer: d
Explanation: JRE is the implementation of JVM, it provides platform to execute java programs.

4. Which component is responsible to optimise byte code to machine code?


a) JVM
b) JDK
c) JIT
d) JRE
View Answer

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.

5. Which statement is true about java?


a) Platform independent programming language
b) Platform dependent programming language
c) Code dependent programming language
d) Sequence dependent programming language
View Answer

Answer: a
Explanation: Java is called ‘Platform Independent Language’ as it primarily works on the principle of ‘compile once,
run everywhere’.

6. Which of the below is invalid indentifier with main method?


a) public
b) static
c) private
d) final
View Answer

Answer: c
Explanation: main method cannot be private as it is invoked by external method. Other identifier are valid with main
method.

7. What is the extension of java code files?


a) .class
b) .java
c) .txt
d) .js
View Answer

Answer: b
Explanation: Java files have .java extension.

8. What is the extension of compiled java classes?


a) .class
b) .java
c) .txt
d) .js
View Answer

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.

10. What is use of interpreter?


a) They convert byte code to machine language code
b) They read high level code and execute them
c) They are intermediated between JIT and JVM
d) It is a synonym for JIT
View Answer

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.

Java Questions & Answers – Class Fundamentals & Declaring objects

1. What is the stored in the object obj in following lines of code?


box obj;
a) Memory address of allocated memory of object
b) NULL
c) Any arbitrary pointer
d) Garbage
View Answer

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.

2. Which of these keywords is used to make a class?


a) class
b) struct
c) int
d) none of the mentioned
View Answer

Answer: a
Explanation: None.

3. Which of the following is a valid declaration of an object of class Box?


a) Box obj = new Box();
b) Box obj = new Box;
c) obj = new Box();
d) new Box obj;
View Answer

Answer: a
Explanation: None.

4. Which of these operators is used to allocate memory for an object?


a) malloc
b) alloc
c) new
d) give
View Answer
Answer: c
Explanation: Operator new dynamically allocates memory for an object and returns a reference to it. This reference
is address in memory of the object allocated by new.

5. Which of these statement is incorrect?


a) Every class must contain a main() method
b) Applets do not require a main() method at all
c) There can be only one main() method in a program
d) main() method must be made public
View Answer

Answer: a
Explanation: Every class does not need to have a main() method, there can be only one main() method which is
made public.

6. What is the output of this program?

1. class main_class

2. {

3. public static void main(String args[])

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

7. Which of the following statements is correct?


a) Public method is accessible to all other classes in the hierarchy
b) Public method is accessible only to subclasses of its parent class
c) Public method can only be called by object of its class
d) Public method can be accessed by calling object of the public class
View Answer

Answer: a
Explanation: None.

8. What is the output of this program?

1. class box

2. {

3. int width;

4. int height;

5. int length;

6. }

7. class mainclass

8. {

9. public static void main(String args[])

10. {

11. box obj = new box();

12. obj.width = 10;

13. obj.height = 2;

14. obj.length = 10;

15. int y = obj.width * obj.height * obj.length;

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

9. What is the output of this program?

1. class box

2. {

3. int width;

4. int height;

5. int length;

6. }

7. class mainclass

8. {

9. public static void main(String args[])

10. {

11. box obj1 = new box();

12. box obj2 = new box();

13. obj1.height = 1;

14. obj1.length = 2;

15. obj1.width = 1;

16. obj2 = obj1;

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

10. What is the output of this program?


1. class box

2. {

3. int width;

4. int height;

5. int length;

6. }

7. class mainclass

8. {

9. public static void main(String args[])

10. {

11. box obj = new box();

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

Java Questions & Answers – Introduction To Methods

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.

4. Which method can be defined only once in a program?


a) main method
b) finalize method
c) static method
d) private method
View Answer

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.

5. Which of these statement is incorrect?


a) All object of a class are allotted memory for the all the variables defined in the class
b) If a function is defined public it can be accessed by object of other class by inheritation
c) main() method must be made public
d) All object of a class are allotted memory for the methods defined in the class
View Answer

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.

6. What is the output of this program?

1. class box

2. {

3. int width;
4. int height;

5. int length;

6. int volume;

7. void volume(int height, int length, int width)

8. {

9. volume = width*height*length;

10. }

11. }

12. class Prameterized_method

13. {

14. public static void main(String args[])

15. {

16. box obj = new box();

17. obj.height = 1;

18. obj.length = 5;

19. obj.width = 5;

20. obj.volume(3,2,1);

21. System.out.println(obj.volume);

22. }

23. }

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

Answer: c
Explanation: None.
output:
$ Prameterized_method.java
$ Prameterized_method
6

7. What is the output of this program?

1. class equality

2. {
3. int x;

4. int y;

5. boolean isequal()

6. {

7. return(x == y);

8. }

9. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. equality obj = new equality();

15. obj.x = 5;

16. obj.y = 5;

17. System.out.println(obj.isequal());

18. }

19. }

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

Answer: b
Explanation: None.
output:
$ javac Output.java
$ java Output
true

8. What is the output of this program?

1. class box

2. {

3. int width;

4. int height;

5. int length;
6. int volume;

7. void volume()

8. {

9. volume = width*height*length;

10. }

11. }

12. class Output

13. {

14. public static void main(String args[])

15. {

16. box obj = new box();

17. obj.height = 1;

18. obj.length = 5;

19. obj.width = 5;

20. obj.volume();

21. System.out.println(obj.volume);

22. }

23. }

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

Answer:c
Explanation: None.
output:
$ javac Output.java
$ java Output
25

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

1. class Output

2. {

3.

4. public static int sum(int ...x)


5. {

6. return;

7. }

8. static void main(String args[])

9. {

10. sum(10);

11. sum(10,20);

12. sum(10,20,30);

13. sum(10,20,30,40);

14. }

15. }

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

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

10. What is the output of this program?

1. class area

2. {

3. int width;

4. int length;

5. int volume;

6. area()

7. {

8. width=5;

9. length=6;

10. }

11. void volume()

12. {

13. volume = width*length*height;


14. }

15. }

16. class cons_method

17. {

18. public static void main(String args[])

19. {

20. area obj = new area();

21. obj.volume();

22. System.out.println(obj.volume);

23. }

24. }

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

Answer: d
Explanation: Variable height is not defined.
output:
$ javac cons_method.java
$ java cons_method
error: cannot find symbol height

Java Questions & Answers – Constructors & Garbage Collection

This section of our 1000+ Java MCQs focuses constructors and garbage collection of Java Programming Language.

1. What is the return type of Constructors?


a) int
b) float
c) void
d) none of the mentioned
View Answer

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.

6. What is the output of this program?

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. }

13. void volume()

14. {

15. volume = width*height*length;

16. }

17. }

18. class constructor_output

19. {

20. public static void main(String args[])

21. {

22. box obj = new box();

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

7. What is the output of this program?

1. class San

2. {

3. San()throws IOException

4. {
5.

6. }

7.

8. }

9. class Foundry extends San

10. {

11. Foundry()

12. {

13.

14. }

15. public static void main(String[]args)

16. {

17.

18. }

19. }

a) compile time error


b) run time error
c) compile and runs fine
d) unreported exception java.io.IOException in default constructor
View Answer

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.

8. What is the output of this program?

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. }

12. protected void volume()

13. {

14. volume = width*height*length;

15. System.out.println(volume);

16. }

17. }

18. class Output

19. {

20. public static void main(String args[])

21. {

22. box obj = new box();

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

9. Which of the following statements are incorrect?


a) default constructor is called at the time of object declaration
b) Constructor can be parameterized
c) finalize() method is called when a object goes out of scope and is no longer needed
d) finalize() method must be declared protected
View Answer
Answer: c
Explanation: finalize() method is called just prior to garbage collection. it is not called when object goes out of scope.

10. What is the output of this program?

1. class area

2. {

3. int width;

4. int length;

5. int area;

6. void area(int width, int length)

7. {

8. this.width = width;

9. this.length = length;

10. }

11.

12. }

13. class Output

14. {

15. public static void main(String args[])

16. {

17. area obj = new area();

18. obj.area(5 , 6);

19. System.out.println(obj.length + " " + obj.width);

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

Java Questions & Answers – Constructor

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Constructor”.

1. What is true about private constructor?


a) Private constructor ensures only one instance of a class exist at any point of time
b) Private constructor ensures multiple instances of a class exist at any point of time
c) Private constructor eases the instantiation of a class
d) Private constructor allows creating objects in other classes
View Answer

Answer: a
Explanation: Object of private constructor can only be createed withing class. Private constructor is used in singleton
pattern.

2. What would be the behaviour if this() and super() used in a method?


a) Runtime error
b) Throws exception
c) compile time error
d) Runs successfully
View Answer

Answer: c
Explanation: this() and super() cannot be used in a method. This throws compile time error.

3. What is false about constructor?


a) Constructors cannot be synchronized in Java
b) Java does not provide default copy constructor
c) Constructor can be overloaded
d) “this” and “super” can be used in a constructor
View Answer

Answer: c
Explanation: Default, parameterised constructors can be defined.

4. What is true about Class.getInstance()?


a) Class.getInstance calls the constructor
b) Class.getInstance is same as new operator
c) Class.getInstance needs to have matching constructor
d) Class.getInstance creates object if class does not have any constructor
View Answer

Answer: d
Explanation: Class class provides list of methods for use like getInstance().

5. What is true about constructor?


a) It can contain return type
b) It can take any number of parameters
c) It can have any non access modifiers
d) Constructor cannot throw exception
View Answer

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.

6. Abstract class cannot have a constructor.


a) True
b) False
View Answer

Answer: b
Explanation: No instance can be created of abstract class. Only pointer can hold instance of object.

7. What is true about protected constructor?


a) Protected constructor can be called directly
b) Protected constructor can only be called using super()
c) Protected constructor can be used outside package
d) protected constructor can be instantiated even if child is in a differnt package
View Answer

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.

8. What is not the use of “this” keyword in Java?


a) Passing itself to another method
b) Calling another constructor in constructor chaining
c) Referring to the instance variable when local variable has the same name
d) Passing itself to method of the same class
View Answer

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.

9. What would be the behaviour if one parameterized constructor is explicitly defined?


a) Compilation error
b) Compilation succeeds
c) Runtime error
d) Compilation succeeds but at the time of creating object using default constructor, it throws compilation error
View Answer

Answer: d
Explanation: The class compiles successfully. But the object creation of that class gives compilation error.

10. What would be behaviour if constructor has a return type?


a) Compilation error
b) Runtime error
c) Compilation and runs successfully
d) Only String return type is allowed
View Answer
Answer: a
Explanation:The constructor cannot have a return type. It should create and return new object. Hence it would give
compilation error.

Java Questions & Answers – Heap and Garbage Collection

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Heap and Garbage Collection”.

1. Which of the following has highest memory requirement?


a) Heap
b) Stack
c) JVM
d) Class
View Answer

Answer: c
Explanation: JVM is the super set which contains heap, stack, objects, pointers, etc.

2. Where is a new object allotted memory?


a) Young space
b) Old space
c) Young or Old space depending on space availability
d) JVM
View Answer

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.

3. Which of the following is a garbage collection technique?


a) Cleanup model
b) Mark and sweep model
c) Space management model
d) Sweep model
View Answer

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.

4. What is -Xms and -Xmx while starting jvm?


a) Initial; Maximum memory
b) Maximum; Initial memory
c) Maximum memory
d) Initial memory
View Answer
Answer: a
Explanation: JVM will be started with Xms amount of memory and will be able to use a maximum of Xmx amount of
memory. java -Xmx2048m -Xms256m.

5. Which exception is thrown when java is out of memory?


a) MemoryFullException
b) MemoryOutOfBoundsException
c) OutOfMemoryError
d) MemoryError
View Answer

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 .

7. What happens to thread when garbage collection kicks off?


a) The thread continues its operation
b) Garbage collection cannot happen until the thread is running
c) The thread is paused while garbage collection runs
d) The thread and garbage collection do not interfere with each other
View Answer

Answer: c
Explanation: The thread is paused when garbage collection runs which slows the application performance.

8. Which of the below is not a Java Profiler?


a) JVM
b) JConsole
c) JProfiler
d) Eclipse Profiler
View Answer

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.

9. Which of the below is not a memory leak solution?


a) Code changes
b) JVM parameter tuning
c) Process restart
d) GC parameter tuning
View Answer
Answer: c
Explanation: Process restart is not a permanent fix to memory leak problem. The problem will resurge again.

10Java Questions & Answers – Overloading Methods & Argument Passing

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.

2. Which of these can be overloaded?


a) Methods
b) Constructors
c) All of the mentioned
d) None of the mentioned
View Answer

Answer: c
Explanation: None.

3. Which of these is correct about passing an argument by call-by-value process?


a) Copy of argument is made into the formal parameter of the subroutine
b) Reference to original argument is passed to formal parameter of the subroutine
c) Copy of argument is made into the formal parameter of the subroutine and changes made on parameters of
subroutine have effect on original argument
d) Reference to original argument is passed to formal parameter of the subroutine and changes made on parameters
of subroutine have effect on original argument
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 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.

5. What is the output of the following code?

1. class San

2. {

3. public void m1 (int i,float f)

4. {

5. System.out.println(" int float method");

6. }

7.

8. public void m1(float f,int i);

9. {

10. System.out.println("float int method");

11. }

12.

13. public static void main(String[]args)

14. {

15. San s=new San();

16. s.m1(20,20);

17. }

18. }

a) int float method


b) float int method
c) compile time error
d) run time error
View Answer

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.

6. What is the output of this program?

1. class overload

2. {

3. int x;
4. int y;

5. void add(int a)

6. {

7. x = a + 1;

8. }

9. void add(int a, int b)

10. {

11. x = a + 2;

12. }

13. }

14. class Overload_methods

15. {

16. public static void main(String args[])

17. {

18. overload obj = new overload();

19. int a = 0;

20. obj.add(6);

21. System.out.println(obj.x);

22. }

23. }

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

Answer: c
Explanation: None.
output:
$ javac Overload_methods.java
$ java Overload_methods
7

7. What is the output of this program?

1. class overload

2. {
3. int x;

4. int y;

5. void add(int a)

6. {

7. x = a + 1;

8. }

9. void add(int a , int b)

10. {

11. x = a + 2;

12. }

13. }

14. class Overload_methods

15. {

16. public static void main(String args[])

17. {

18. overload obj = new overload();

19. int a = 0;

20. obj.add(6, 7);

21. System.out.println(obj.x);

22. }

23. }

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

Answer: c
Explanation: None.
output:
$ javac Overload_methods.java
$ java Overload_methods
8

8. What is the output of this program?

1. class overload
2. {

3. int x;

4. double y;

5. void add(int a , int b)

6. {

7. x = a + b;

8. }

9. void add(double c , double d)

10. {

11. y = c + d;

12. }

13. overload()

14. {

15. this.x = 0;

16. this.y = 0;

17. }

18. }

19. class Overload_methods

20. {

21. public static void main(String args[])

22. {

23. overload obj = new overload();

24. int a = 2;

25. double b = 3.2;

26. obj.add(a, a);

27. obj.add(b, b);

28. System.out.println(obj.x + " " + obj.y);

29. }

30. }

a) 6 6
b) 6.4 6.4
c) 6.4 6
d) 4 6.4
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

9. What is the output of this program?

1. class test

2. {

3. int a;

4. int b;

5. void meth(int i , int j)

6. {

7. i *= 2;

8. j /= 2;

9. }

10. }

11. class Output

12. {

13. public static void main(String args[])

14. {

15. test obj = new test();

16. int a = 10;

17. int b = 20;

18. obj.meth(a , b);

19. System.out.println(a + " " + b);

20. }

21. }

a) 10 20
b) 20 10
c) 20 40
d) 40 20
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

10. What is the output of this program?

1. class test

2. {

3. int a;

4. int b;

5. test(int i, int j)

6. {

7. a = i;

8. b = j;

9. }

10. void meth(test o)

11. {

12. o.a *= 2;

13. O.b /= 2;

14. }

15. }

16. class Output

17. {

18. public static void main(String args[])

19. {

20. test obj = new test(10 , 20);

21. obj.meth(obj);

22. System.out.println(obj.a + " " + obj.b);


23. }

24. }

a) 10 20
b) 20 10
c) 20 40
d) 40 20
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

. Garbage Collection can be controlled by program?


a) True
b) False
View Answer

Answer: b
Explanation: Garbage Collection cannot be controlled by program.

Java Questions & Answers – Access Control – 1

This section of our 1000+ Java MCQs focuses on access control of Java Programming Language.

1. Which of these access specifiers must be used for main() method?


a) private
b) public
c) protected
d) none of the mentioned
View Answer

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.

5. Which of the following statements are incorrect?


a) public members of class can be accessed by any code in the program
b) private members of class can only be accessed by other members of the class
c) private members of class can be inherited by a sub class, and become protected members in sub class
d) protected members of a class can be inherited by a sub class, and become private members of the sub class
View Answer

Answer: c
Explanation: private members of a class can not be inherited by a sub class.

6. What is the output of this program?

1. class access

2. {

3. public int x;

4. private int y;

5. void cal(int a, int b)

6. {

7. x = a + 1;

8. y = b;

9. }

10. }

11. class access_specifier


12. {

13. public static void main(String args[])

14. {

15. access obj = new access();

16. obj.cal(2, 3);

17. System.out.println(obj.x + " " + obj.y);

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

7. What is the output of this program?

1. class access

2. {

3. public int x;

4. private int y;

5. void cal(int a, int b)

6. {

7. x = a + 1;

8. y = b;

9. }

10. void print()

11. {

12. system.out.println(" " + y);

13. }

14. }
15. class access_specifier

16. {

17. public static void main(String args[])

18. {

19. access obj = new access();

20. obj.cal(2, 3);

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

8. What is the output of this program?

1. class static_out

2. {

3. static int x;

4. static int y;

5. void add(int a, int b)

6. {

7. x = a + b;

8. y = x + b;

9. }

10. }

11. class static_use

12. {
13. public static void main(String args[])

14. {

15. static_out obj1 = new static_out();

16. static_out obj2 = new static_out();

17. int a = 2;

18. obj1.add(a, a + 1);

19. obj2.add(5, a);

20. System.out.println(obj1.x + " " + obj2.y);

21. }

22. }

a) 7 7
b) 6 6
c) 7 9
d) 9 7
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.

10. What is the output of this program?

1. class test

2. {

3. int a;

4. int b;

5. test(int i, int j)

6. {
7. a = i;

8. b = j;

9. }

10. void meth(test o)

11. {

12. o.a *= 2;

13. O.b /= 2;

14. }

15. }

16. class Output

17. {

18. public static void main(String args[])

19. {

20. test obj = new test(10 , 20);

21. obj.meth(obj);

22. System.out.println(obj.a + " " + obj.b);

23. }

24. }

a) 10 20
b) 20 10
c) 20 40
d) 40 20
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

Java Questions & Answers – Access Control – 2

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.

2. All the variables of class should be ideally declared as ?


a) private
b) public
c) protected
d) default
View Answer

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.

4. How can a protected modifier be accessed?


a) accessible only within the class
b) accessible only within package
c) accessible within package and outside the package but through inheritance only
d) accessible by all
View Answer

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.

5. What happens if constructor of class A is made private?


a) Any class can instantiate objects of class A
b) Objects of class A can be instantiated only within the class where it is declared
c) Inherited class can instantiate objects of class A
d) classes within the same package as class A can instantiate objects of class A
View Answer

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.

7. What is true of final class?


a) Final class cause compilation failure
b) Final class cannot be instantiated
c) Final class cause runtime failure
d) Final class cannot be inherited
View Answer

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.

9. Can a class be declared with protected modifier?


a) True
b) False
View Answer

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.

10. Which is the modifier when there is none mentioned explicitly?


a) protected
b) private
c) public
d) default
View Answer
Answer: d
Explanation: Default is the access modifier when none is defined explicitly. It means the member (method or
variable) can be accessed within the same package

Java Questions & Answers – Arrays Revisited & Keyword static

This set of Java Question Bank focuses on “Arrays Revisited & Keyword static”.

1. Arrays in Java are implemented as?


a) class
b) object
c) variable
d) none of the mentioned
View Answer

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.

3. Which of these cannot be declared static?


a) class
b) object
c) variable
d) method
View Answer

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

4. Which of the following statements are incorrect?


a) static methods can call other static methods only
b) static methods must only access static data
c) static methods can not refer to this or super in any way
d) when object of class is declared, each object contains its own copy of static variables
View Answer

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.

5. Which of the following statements are incorrect?


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

Answer: a
Explanation: None.

6. Which of these methods must be made static?


a) main()
b) delete()
c) run()
d) finalize()
View Answer

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.

7. What is the output of this program?

1. class access

2. {

3. public int x;

4. static int y;

5. void cal(int a, int b)

6. {

7. x += a ;

8. y += b;

9. }

10. }

11. class static_specifier

12. {

13. public static void main(String args[])

14. {

15. access obj1 = new access();

16. access obj2 = new access();

17. obj1.x = 0;

18. obj1.y = 0;

19. obj1.cal(1, 2);


20. obj2.x = 0;

21. obj2.cal(2, 3);

22. System.out.println(obj1.x + " " + obj2.y);

23. }

24. }

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

Answer: d
Explanation: None.
output:
$ javac static_specifier.java
$ java static_specifier
15

8. What is the output of this program?

1. class access

2. {

3. static int x;

4. void increment()

5. {

6. x++;

7. }

8. }

9. class static_use

10. {

11. public static void main(String args[])

12. {

13. access obj1 = new access();

14. access obj2 = new access();

15. obj1.x = 0;

16. obj1.increment();

17. obj2.increment();
18. System.out.println(obj1.x + " " + obj2.x);

19. }

20. }

a) 1 2
b) 1 1
c) 2 2
d) Compilation Error
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

9. What is the output of this program?

1. class static_out

2. {

3. static int x;

4. static int y;

5. void add(int a , int b)

6. {

7. x = a + b;

8. y = x + b;

9. }

10. }

11. class static_use

12. {

13. public static void main(String args[])

14. {

15. static_out obj1 = new static_out();

16. static_out obj2 = new static_out();

17. int a = 2;

18. obj1.add(a, a + 1);


19. obj2.add(5, a);

20. System.out.println(obj1.x + " " + obj2.y);

21. }

22. }

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

Answer: c
Explanation: None.
output:
$ javac static_use.java
$ java static_use
79

10. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. int arr[] = {1, 2, 3, 4, 5};

6. for ( int i = 0; i < arr.length - 2; ++i)

7. System.out.println(arr[i] + " ");

8. }

9. }

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

Answer: b
Explanation: arr.length() is 5, so the loop is executed for three times.
output:
$ javac Output.java
$ java Output
123

11. What is the output of this program?


1. class Output

2. {

3. public static void main(String args[])

4. {

5. int a1[] = new int[10];

6. int a2[] = {1, 2, 3, 4, 5};

7. System.out.println(a1.length + " " + a2.length);

8. }

9. }

a) 10 5
b) 5 10
c) 0 10
d) 0 5
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

Java Questions & Answers – String Class

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.

5. Which of the following statements are incorrect?


a) String is a class
b) Strings in java are mutable
c) Every string is an object of class String
d) Java defines a peer class of String, called StringBuffer, which allows string to be altered
View Answer

Answer: b
Explanation: Strings in Java are immutable that is they can not be modified.

6. What is the output of this program?

1. class string_demo

2. {

3. public static void main(String args[])

4. {

5. String obj = "I" + "like" + "Java";

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

7. What is the output of this program?

1. class string_class

2. {

3. public static void main(String args[])

4. {

5. String obj = "I LIKE JAVA";

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

8. What is the output of this program?

1. class string_class

2. {

3. public static void main(String args[])

4. {

5. String obj = "I LIKE JAVA";

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

9. What is the output of this program?

1. class string_class

2. {

3. public static void main(String args[])

4. {

5. String obj = "hello";

6. String obj1 = "world";

7. String obj2 = obj;

8. obj2 = " world";

9. System.out.println(obj + " " + obj2);

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

10. What is the output of this program?

1. class string_class
2. {

3. public static void main(String args[])

4. {

5. String obj = "hello";

6. String obj1 = "world";

7. String obj2 = "hello";

8. System.out.println(obj.equals(obj1) + " " + obj.equals(obj2));

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

Java Questions & Answers – Methods Taking Parameters

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.

5. Which of these statement is incorrect?


a) Two or more methods with same name can be differentiated on the basis of their parameters data type
b) Two or more method having same name can be differentiated on basis of number of parameters
c) Any already defined method in java’s library can be defined again in the program with different data type of
parameters
d) If a method is returning a value the calling statement must have a variable to store that value
View Answer

Answer: d
Explanation: Even if a method is returning a value, it is not necessary to store that value.

6. What is the output of this program?

1. class box

2. {

3. int width;

4. int height;

5. int length;

6. int volume;

7. void volume(int height, int length, int width)

8. {

9. volume = width * height * length;

10. }
11. }

12. class Prameterized_method{

13. public static void main(String args[])

14. {

15. box obj = new box();

16. obj.height = 1;

17. obj.length = 5;

18. obj.width = 5;

19. obj.volume(3, 2, 1);

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

7. What is the output of this program?

1. class equality

2. {

3. int x;

4. int y;

5. boolean isequal()

6. {

7. return(x == y);

8. }

9. }

10. class Output


11. {

12. public static void main(String args[])

13. {

14. equality obj = new equality();

15. obj.x = 5;

16. obj.y = 5;

17. System.out.println(obj.isequal);

18. }

19. }

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

Answer: b
Explanation: None
output:
$ javac Output.java
$ java Output
true

8. What is the output of this program?

1. class box

2. {

3. int width;

4. int height;

5. int length;

6. int volume;

7. void volume()

8. {

9. volume = width * height * length;

10. }

11. void volume(int x)

12. {

13. volume = x;
14. }

15. }

16. class Output

17. {

18. public static void main(String args[])

19. {

20. box obj = new box();

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

9. What is the output of this program?

1. class Output

2. {

3. static void main(String args[])

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)

10. What is the output of this program?

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. }

12. void volume()

13. {

14. volume = width * height * length;

15. }

16. }

17. class cons_method


18. {

19. public static void main(String args[])

20. {

21. area obj = new area();

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

Java Questions & Answers – Command Line Arguments – 1

This section of our 1000+ Java MCQs focuses on Command Line Arguments in Java Programming Language.

1. Which of these method is given parameter via command line arguments?


a) main()
b) recursive() method
c) Any method
d) System defined methods
View Answer

Answer: a
Explanation: Only main() method can be given parameters via using command line arguments.

2. Which of these data types is used to store command line arguments?


a) Array
b) Stack
c) String
d) Integer
View Answer

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.

4. Which of these is a correct statement about args in this line of code?


public static viod main(String args[])
a) args is a String
b) args is a Character
c) args is an array of String
d) args in an array of Character
View Answer

Answer: c
Explanation: args in an array of String.

5. Can command line arguments be converted into int automatically if required?


a) Yes
b) No
c) Compiler Dependent
d) Only ASCII characters can be converted
View Answer

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. {

3. public static void main(String args[])

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. {

3. public static void main(String args[])

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. {

3. public static void main(String args[])

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. {

3. public static void main(String args[])

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. {

3. public static void main(String args[])

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

Java Questions & Answers – Command Line Arguments – 2

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”?

1. public class abc

2. {

3. int a=2000;

4. public static void main(String argv[])

5. {

6. System.out.println(argv[1]+" :-Please pay Rs."+a);

7. }

8. }

a) Compile time error


b) Compilation but runtime error
c) Compilation and output Rakesh :-Please pay Rs.2000
d) Compilation and output Sharma :-Please pay Rs.2000
View Answer

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. {

3. public static void main(String args[])

4. {

5. if(args.length>0)
6. System.out.println(args.length);

7. }

8. }

a) The snippet compiles, runs and prints 0


b) The snippet compiles, runs and prints 1
c) The snippet does not compile
d) The snippet compiles and runs but does not print anything
View Answer

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”?

1. public class abc

2. {

3. static public void main(String [] xyz)

4. {

5. for(int n=1;n<xyz.length; n++)

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”?

1. public class demo

2. {

3. public static void main(String args[])

4. {

5. System.out.println(args[0]+""+args[args.length-1]);
6. }

7. }

a) The snippet compiles, runs and prints “java demo”


b) The snippet compiles, runs and prints “java code”
c) The snippet compiles, runs and prints “demo code”
d) The snippet compiles, runs and prints “I code”
View Answer

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”?

1. public class abc

2. {

3. String[] xyz;

4.

5. public static void main(String argv[])

6. {

7. xyz=argv;

8. }

9.

10. public void runMethod()

11. {

12. System.out.println(argv[1]);

13. }

14. }

a) Compile time error


b) Output would be “hello”
c) Output would be “there”
d) Output would be “hello there”
View Answer

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.

6. How do we pass command line argument in Eclipse?


a) Arguments tab
b) Variable tab
c) Cannot pass command line argument in eclipse
d) Environment variable tab
View Answer

Answer: a
Explanation: Arguments tab is used to pass command line argument in eclipse.

7. Which class allows parsing of command line arguments?


a) Args
b) JCommander
c) CommandLine
d) Input
View Answer

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.

11. public static void main(String args[])

12. {

13. Demo demo = new Demo();

14. new JCommander(demo, args);


15. demo.run();

16. }

17.

18. public void run()

19. {

20. System.out.println(length+" "+ breadth+" "+height);

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.

10. What is the use of @syntax?


a) Allows multiple parameters to be passed
b) Allows one to put all your options into a file and pass this file as parameter
c) Allows one to pass only one parameter
d) Allows one to pass one file containing only one parameter
View Answer

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

Java Questions & Answers – Recursion

This section of our 1000+ Java MCQs focuses on recursion of Java Programming Language.

1. What is Recursion in Java?


a) Recursion is a class
b) Recursion is a process of defining a method that calls other methods repeatedly
c) Recursion is a process of defining a method that calls itself repeatedly
d) Recursion is a process of defining a method that calls other methods which in turn call again this method
View Answer
Answer: b
Explanation: Recursion is the process of defining something in terms of itself. It allows us to define method that calls
itself.

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.

4. Which of these is not a correct statement?


a) A recursive method must have a base case
b) Recursion always uses stack
c) Recursive methods are faster that programmers written loop to call the function repeatedly using a stack
d) Recursion is managed by Java’s Run – Time environment
View Answer

Answer: d
Explanation: Recursion is always managed by operating system.

5. Which of these packages contains the exception Stackoverflow in Java?


a) java.lang
b) java.util
c) java.io
d) java.system
View Answer

Answer: a
Explanation: None.

6. What is the output of this program?

1. class recursion

2. {

3. int func (int n)

4. {
5. int result;

6. result = func (n - 1);

7. return result;

8. }

9. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. recursion obj = new recursion() ;

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

7. What is the output of this program?

1. class recursion

2. {

3. int func (int n)

4. {

5. int result;

6. if (n == 1)

7. return 1;

8. result = func (n - 1);


9. return result;

10. }

11. }

12. class Output

13. {

14. public static void main(String args[])

15. {

16. recursion obj = new recursion() ;

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

8. What is the output of this program?

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. {

14. public static void main(String args[])

15. {

16. recursion obj = new recursion() ;

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

9. What is the output of this program?

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. {
14. public static void main(String args[])

15. {

16. recursion obj = new recursion() ;

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

10. What is the output of this program?

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. {

14. public static void main(String args[])

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

Java Questions & Answers – Method overriding

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.

3. Which of these keywords can be used to prevent Method overriding?


a) static
b) constant
c) protected
d) final
View Answer
Answer: d
Explanation: To disallow a method from being overridden, specify final as a modifier at the start of its declaration.
Methods declared as final cannot be overridden.

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”

1. public interface Status

2. {

3. /* insert qualifier here */ int MY_VALUE = 10;

4. }

a) final, native, private


b) final, static, protected
c) final, private, abstract
d) final, static, public
View Answer

Answer: d
Explanation: Every interface variable is implicitly public static and final.

6. Which of these is supported by method overriding in Java?


a) Abstraction
b) Encapsulation
c) Polymorphism
d) None of the mentioned
View Answer

Answer: c
Explanation: None.

7. What is the output of this program?

1. class Alligator

2. {

3. public static void main(String[] args)

4. {

5. int []x[] = {{1,2}, {3,4,5}, {6,7,8,9}};


6. int [][]y = x;

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.

8. What is the output of this program?

1. final class A

2. {

3. int i;

4. }

5. class B extends A

6. {

7. int j;

8. System.out.println(j + " " + i);

9. }

10. class inheritance

11. {

12. public static void main(String args[])

13. {

14. B obj = new B();

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

9. What is the output of this program?

1. class Abc

2. {

3. public static void main(String[]args)

4. {

5. String[] elements = { "for", "tea", "too" };

6. String first = (elements.length > 0) ? elements[0]: null;

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.

10. What is the output of this program?

1. class A

2. {

3. int i;

4. public void display()

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. }

17. class Dynamic_dispatch

18. {

19. public static void main(String args[])

20. {

21. B obj2 = new B();

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

Java Questions & Answers – The Object Class

This section of our 1000+ Java MCQs focuses on Object class of Java Programming Language.

1. Which of these class is superclass of every class in Java?


a) String class
b) Object class
c) Abstract class
d) ArrayList class
View Answer

Answer: b
Explanation: Object class is superclass of every class in Java.

2. Which of these method of Object class can clone an object?


a) Objectcopy()
b) copy()
c) Object clone()
d) clone()
View Answer

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.

4. Which of these keywords can be used to prevent inheritance of a class?


a) super
b) constant
c) class
d) final
View Answer

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.

7. What is the output of this program?

1. abstract class A

2. {

3. int i;

4. abstract void display();

5. }

6. class B extends A

7. {

8. int j;

9. void display()

10. {

11. System.out.println(j);

12. }

13. }

14. class Abstract_demo

15. {

16. public static void main(String args[])

17. {

18. B obj = new B();

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

8. What is the output of this program?

1. class A

2. {

3. int i;

4. int j;

5. A()

6. {

7. i = 1;

8. j = 2;

9. }

10. }

11. class Output

12. {

13. public static void main(String args[])

14. {

15. A obj1 = new A();

16. A obj2 = new A();

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

9. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. Object obj = new Object();

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

10. What is the output of this program?

1. class A

2. {

3. int i;

4. int j;

5. A()

6. {

7. i = 1;

8. j = 2;

9. }
10. }

11. class Output

12. {

13. public static void main(String args[])

14. {

15. A obj1 = new A();

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

Java Questions & Answers – Inheritance – Abstract Class and Super

This section of our 1000+ Java MCQs focuses on Abstract class in Java Programming Language.

1. Which of these keywords are used to define an abstract class?


a) abst
b) abstract
c) Abstract
d) abstract class
View Answer

Answer: b
Explanation: None.

2. Which of these is not abstract?


a) Thread
b) AbstractList
c) List
d) None of the Mentioned
View Answer

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.

4. Which of these is not a correct statement?


a) Every class containing abstract method must be declared abstract
b) Abstract class defines only the structure of the class not its implementation
c) Abstract class can be initiated by new operator
d) Abstract class can be inherited
View Answer

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.

5. Which of these packages contains abstract keyword?


a) java.lang
b) java.util
c) java.io
d) java.system
View Answer

Answer: a
Explanation: None.

6. What is the output of this program?

1. class A

2. {

3. public int i;

4. private int j;

5. }

6. class B extends A

7. {

8. void display()

9. {

10. super.j = super.i + 1;

11. System.out.println(super.i + " " + super.j);


12. }

13. }

14. class inheritance

15. {

16. public static void main(String args[])

17. {

18. B obj = new B();

19. obj.i=1;

20. obj.j=2;

21. obj.display();

22. }

23. }

a) 2 2
b) 3 3
c) 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

7. What is the output of this program?

1. class A

2. {

3. public int i;

4. public int j;

5. A()

6. {

7. i = 1;

8. j = 2;

9. }
10. }

11. class B extends A

12. {

13. int a;

14. B()

15. {

16. super();

17. }

18. }

19. class super_use

20. {

21. public static void main(String args[])

22. {

23. B obj = new B();

24. System.out.println(obj.i + " " + obj.j)

25. }

26. }

a) 1 2
b) 2 1
c) Runtime Error
d) Compilation Error
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

8. What is the output of this program?

1. abstract class A

2. {

3. int i;

4. abstract void display();


5. }

6. class B extends A

7. {

8. int j;

9. void display()

10. {

11. System.out.println(j);

12. }

13. }

14. class Abstract_demo

15. {

16. public static void main(String args[])

17. {

18. B obj = new B();

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

9. What is the output of this program?

1. class A

2. {

3. int i;
4. void display()

5. {

6. System.out.println(i);

7. }

8. }

9. class B extends A

10. {

11. int j;

12. void display()

13. {

14. System.out.println(j);

15. }

16. }

17. class method_overriding

18. {

19. public static void main(String args[])

20. {

21. B obj = new B();

22. obj.i=1;

23. obj.j=2;

24. obj.display();

25. }

26. }

a) 0
b) 1
c) 2
d) Compilation Error
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

10. What is the output of this program?

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;

12. System.out.println(i + " " + j);

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])

18. {

19. B obj = new B();

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

Java Questions & Answers – Inheritance – 1

This section of our 1000+ Java MCQs focuses on Inheritance of Java Programming Language.

1. Which of these keyword must be used to inherit a class?


a) super
b) this
c) extent
d) extends
View Answer

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.

3. A class member declared protected becomes member of subclass of which type?


a) public member
b) private member
c) protected member
d) static member
View Answer

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

4. Which of these is correct way of inheriting class A by class B?


a) class B + class A {}
b) class B inherits class A {}
c) class B extends A {}
d) class B extends class A {}
View Answer

Answer: c
Explanation: None.
5. Which two classes use the Shape class correctly?

A. public class Circle implements Shape

private int radius;

B. public abstract class Circle extends Shape

private int radius;

C. public class Circle extends Shape

private int radius;

public void draw();

D. public abstract class Circle implements Shape

private int radius;

public void draw();

E. public class Circle extends Shape

private int radius;

public void draw()

/* code here */

F. public abstract class Circle implements Shape

private int radius;


public void draw()

/* code here */

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

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

6. What is the output of this program?

1. class A

2. {

3. int i;

4. void display()

5. {

6. System.out.println(i);

7. }

8. }

9. class B extends A

10. {

11. int j;

12. void display()

13. {

14. System.out.println(j);

15. }

16. }

17. class inheritance_demo

18. {

19. public static void main(String args[])


20. {

21. B obj = new B();

22. obj.i=1;

23. obj.j=2;

24. obj.display();

25. }

26. }

a) 0
b) 1
c) 2
d) Compilation Error
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

7. What is the output of this program?

1. class A

2. {

3. int i;

4. }

5. class B extends A

6. {

7. int j;

8. void display()

9. {

10. super.i = j + 1;

11. System.out.println(j + " " + i);

12. }

13. }

14. class inheritance


15. {

16. public static void main(String args[])

17. {

18. B obj = new B();

19. obj.i=1;

20. obj.j=2;

21. obj.display();

22. }

23. }

a) 2 2
b) 3 3
c) 2 3
d) 3 2
View Answer

Answer: c
Explanation: None
output:
$ javac inheritance.java
$ java inheritance
23

8. What is the output of this program?

1. class A

2. {

3. public int i;

4. private int j;

5. }

6. class B extends A

7. {

8. void display()

9. {

10. super.j = super.i + 1;

11. System.out.println(super.i + " " + super.j);

12. }

13. }
14. class inheritance

15. {

16. public static void main(String args[])

17. {

18. B obj = new B();

19. obj.i=1;

20. obj.j=2;

21. obj.display();

22. }

23. }

a) 2 2
b) 3 3
c) 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

9. What is the output of this program?

1. class A

2. {

3. public int i;

4. public int j;

5. A()

6. {

7. i = 1;

8. j = 2;

9. }

10. }

11. class B extends A


12. {

13. int a;

14. B()

15. {

16. super();

17. }

18. }

19. class super_use

20. {

21. public static void main(String args[])

22. {

23. B obj = new B();

24. System.out.println(obj.i + " " + obj.j)

25. }

26. }

a) 1 2
b) 2 1
c) Runtime Error
d) Compilation Error
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

10. What is the output of this program?

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;

12. System.out.println(i + " " + j);

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])

18. {

19. B obj = new B();

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

Java Questions & Answers – Inheritance – 2

This set of Java Interview Questions and Answers for freshers focuses on “Inheritance – 2”.

1. What is not type of inheritance?


a) Single inheritance
b) Double inheritance
c) Hierarchical inheritance
d) Multiple inheritance
View Answer

Answer: b
Explanation: Inheritance is way of acquiring attributes and methods of parent class. Java supports hierarchical
inheritance directly.

2. Using which of the following, multiple inheritance in Java can be implemented?


a) Interfaces
b) Multithreading
c) Protected methods
d) Private methods
View Answer

Answer: a
Explanation: Multiple inheritance in java is implemented using interfaces. Multiple interfaces can be implemented by
a class.

3. All classes in Java are inherited from which class?


a) java.lang.class
b) java.class.inherited
c) java.class.object
d) java.lang.Object
View Answer

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.

6. Static members are not inherited to sub class.


a) True
b) False
View Answer
Answer: b
Explanation: Static members are also inherited to sub classes.

7. Which of the following is used for implementing inheritance through interface?


a) inherited
b) using
c) extends
d) implements
View Answer

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.

8. Which of the following is used for implementing inheritance through class?


a) inherited
b) using
c) extends
d) implements
View Answer

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.

10. Does Java support multiple level inheritance?


a) True
b) False
View Answer

Answer: a
Explanation: Java supports multiple level inheritance through implementing multiple interfaces.

Java Questions & Answers – String Handling Basics

This section of our 1000+ Java MCQs focuses on string handling in Java Programming Language.

1. Which of these class is superclass of String and StringBuffer class?


a) java.util
b) java.lang
c) ArrayList
d) None of the mentioned
View Answer

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.

5. Which of these constructors is used to create an empty String object?


a) String()
b) String(void)
c) String(0)
d) None of the mentioned
View Answer

Answer: a
Explanation: None.

6. Which of these is an oncorrect statement?


a) String objects are immutable, they cannot be changed
b) String object can point to some other reference of String variable
c) StringBuffer class is used to store string in a buffer for later use
d) None of the mentioned
View Answer
Answer: c
Explanation: StringBuffer class is used to create strings that can be modified after they are created.

7. What is the output of this program?

1. class String_demo

2. {

3. public static void main(String args[])

4. {

5. char chars[] = {'a', 'b', 'c'};

6. String s = new String(chars);

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

8. What is the output of this program?

1. class String_demo

2. {

3. public static void main(String args[])

4. {

5. int ascii[] = { 65, 66, 67, 68};

6. String s = new String(ascii, 1, 3);

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

9. What is the output of this program?

1. class String_demo

2. {

3. public static void main(String args[])

4. {

5. char chars[] = {'a', 'b', 'c'};

6. String s = new String(chars);

7. String s1 = "abcd";

8. int len1 = s1.length();

9. int len2 = s.length();

10. System.out.println(len1 + " " + len2);

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

10. What is the output of this program?


1. class A

2. {

3. int i;

4. int j;

5. A()

6. {

7. i = 1;

8. j = 2;

9. }

10. }

11. class Output

12. {

13. public static void main(String args[])

14. {

15. A obj1 = new A();

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

Java Questions & Answers – Character Extraction

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. {

4. public String name = "hello";

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.

4. What will be output of the following code?

1. public class Boxer1

2. {

3. Integer i;

4. int x;

5. public Boxer1(int y)

6. {

7. x = i+y;

8. System.out.println(x);
9. }

10. public static void main(String[] args)

11. {

12. new Boxer1 (new Integer(4));

13. }

14. }

a) The value “4” is printed at the command line


b) Compilation fails because of an error in line
c) A NullPointerException occurs at runtime
d) An IllegalStateException occurs at runtime
View Answer

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.

6. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. String c = "Hello i love java";

6. int start = 2;

7. int end = 9;

8. char s[]=new char[end-start];

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

7. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. String a = "hello i love java";

6. System.out.println(a.indexOf('i')+" "+a.indexOf('o') +" "+a.lastIndexOf('i')+" "+a.lastIndexOf('o'));

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

8. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])


4. {

5. char c[]={'a', '1', 'b' ,' ' ,'A' , '0'};

6. for (int i = 0; i < 5; ++i)

7. {

8. if(Character.isDigit(c[i]))

9. System.out.println(c[i]+" is a digit");

10. if(Character.isWhitespace(c[i]))

11. System.out.println(c[i]+" is a Whitespace character");

12. if(Character.isUpperCase(c[i]))

13. System.out.println(c[i]+" is an Upper case Letter");

14. if(Character.isLowerCase(c[i]))

15. System.out.println(c[i]+" is a lower case Letter");

16. i=i+3;

17. }

18. }

19. }

a) a is a lower case Letter


is White space character
b) b is a lower case Letter
is White space character
c) a is a lower case Letter
A is a upper case Letter
d) a is a lower case Letter
0 is a digit
View Answer

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

9. What is the output of this program?

1. class String_demo

2. {
3. public static void main(String args[])

4. {

5. char chars[] = {'a', 'b', 'c'};

6. String s = new String(chars);

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

10. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

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

Java Questions & Answers – String Comparison

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.

6. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. String c = "Hello i love java";

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

7. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {
5. String s1 = "Hello i love java";

6. String s2 = new String(s1);

7. System.out.println((s1 == s2) + " " + s1.equals(s2));

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

8. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. String s1 = "Hello";

6. String s2 = new String(s1);

7. String s3 = "HELLO";

8. System.out.println(s1.equals(s2) + " " + s2.equals(s3));

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”?

1 StringBuilder sb1 = new StringBuilder("123");

2 String s1 = "123";

3 // insert code here

4 System.out.println(sb1 + " " + s1);

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.

10. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. String chars[] = {"a", "b", "c", "a", "c"};

6. for (int i = 0; i < chars.length; ++i)

7. for (int j = i + 1; j < chars.length; ++j)

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

Java Questions & Answers – Searching & Modifying a String

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.

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

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.

6. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. String c = " Hello World ";

6. String s = c.trim();

7. System.out.println("\""+s+"\"");

8. }

9. }

a) “”Hello World””
b) “”Hello World”
c) “Hello World”
d) Hello world
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”

7. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. String s1 = "one";

6. String s2 = s1 + " two";


7. System.out.println(s2);

8. }

9. }

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

Answer: c
Explanation: None.
Output:
$ javac output.java
$ java output
one two

8. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. String s1 = "Hello";

6. String s2 = s1.replace('l','w');

7. System.out.println(s2);

8. }

9. }

a) hello
b) helwo
c) hewlo
d) hewwo
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

9. What is the output of this program?

1. class output
2. {

3. public static void main(String args[])

4. {

5. String s1 = "Hello World";

6. String s2 = s1.substring(0 , 4);

7. System.out.println(s2);

8. }

9. }

a) Hell
b) Hello
c) Worl
d) World
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

10. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. { String s = "Hello World";

5. int i = s.indexOf('o');

6. int j = s.lastIndexOf('l');

7. System.out.print(i + " " + j);

8.

9. }

10. }

a) 4 8
b) 5 9
c) 4 9
d) 5 8
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

Java Questions & Answers – StringBuffer Class

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.

4. What is the string contained in s after following lines of code?


StringBuffer s new StringBuffer(“Hello”);
s.deleteCharAt(0);
a) Hell
b) ello
c) Hel
d) llo
View Answer
Answer: b
Explanation: deleteCharAt() method deletes the character at the specified index location and returns the resulting
StringBuffer object.

5. Which of the following statement is correct?


a) reverse() method reverses all characters
b) reverseall() method reverses all characters
c) replace() method replaces first occurrence of a character in invoking string with another character
d) replace() method replaces last occurrence of a character in invoking string with another character
View Answer

Answer: a
Explanation: reverse() method reverses all characters. It returns the reversed object on which it was called.

6. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. String a = "hello i love java";

6. System.out.println(a.indexOf('e')+" "+a.indexOf('a')+" "+a.lastIndexOf('l')+" "+a.lastIndexOf('v'));

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

7. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

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

8. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. StringBuffer c = new StringBuffer("Hello");

6. StringBuffer c1 = new StringBuffer(" World");

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

9. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. StringBuffer s1 = new StringBuffer("Hello");

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

10. What is the output of this program?

1. class output

2. {

3. class output

4. {

5. public static void main(String args[])

6. {

7. char c[]={'A', '1', 'b' ,' ' ,'a' , '0'};

8. for (int i = 0; i < 5; ++i)

9. {

10. i++;
11. if(Character.isDigit(c[i]))

12. System.out.println(c[i]+" is a digit");

13. if(Character.isWhitespace(c[i]))

14. System.out.println(c[i]+" is a Whitespace character");

15. if(Character.isUpperCase(c[i]))

16. System.out.println(c[i]+" is an Upper case Letter");

17. if(Character.isLowerCase(c[i]))

18. System.out.println(c[i]+" is a lower case Letter");

19. i++;

20. }

21. }

22. }

a) a is a lower case Letter


is White space character
b) b is a lower case Letter
is White space character
c) 1 is a digit
a is a lower case Letter
d) a is a lower case Letter
0 is a digit
View Answer

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

Java Questions & Answers – StringBuffer Methods

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.

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

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.

3. Which of these method of class StringBuffer is used to reverse sequence of characters?


a) reverse()
b) reverseall()
c) Reverse()
d) reverseAll()
View Answer

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.

5. Which of the following are incorrect form of StringBuffer class constructor?


a) StringBuffer()
b) StringBuffer(int size)
c) StringBuffer(String str)
d) StringBuffer(int size , String str)
View Answer

Answer: d
Explanation: None.

6. What is the output of this program?

1. class output

2. {
3. public static void main(String args[])

4. {

5. StringBuffer c = new StringBuffer("Hello");

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

7. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. StringBuffer sb=new StringBuffer("Hello");

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. {

3. public static void main(String args[])

4. {

5. StringBuffer s1 = new StringBuffer("Hello");

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

9. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. StringBuffer s1 = new StringBuffer("Hello World");

6. s1.insert(6 , "Good ");

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

10. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. StringBuffer s1 = new StringBuffer("Hello");

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

Java Questions & Answers – Java.lang Introduction

This section of our 1000+ Java MCQs focuses on java.lang library of Java Programming Language.

1. Which of these classes is not included in java.lang?


a) Byte
b) Integer
c) Array
d) Class
View Answer
Answer: c
Explanation: Array class is a member of java.util.

2. Which of these is a process of converting a simple data type into a class?


a) type wrapping
b) type conversion
c) type casting
d) none of the Mentioned.
View Answer

Answer: a
Explanation: None.

3. Which of these is a super class of wrappers Double & Integer?


a) Long
b) Digits
c) Float
d) Number
View Answer

Answer: d
Explanation: Number is an abstract class containing subclasses Double, Float, Byte, Short, Integer and Long.

4. Which of these is wrapper for simple data type float?


a) float
b) double
c) Float
d) Double
View Answer

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.

8. What is the output of this program?

1. class isinfinite_output

2. {

3. public static void main(String args[])

4. {

5. Double d = new Double(1 / 0.);

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

9. What is the output of this program?

1. class isNaN_output

2. {

3. public static void main(String args[])

4. {

5. Double d = new Double(1 / 0.);

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

10. What is the output of this program?

1. class binary

2. {

3. public static void main(String args[])

4. {

5. int num = 17;

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.

3. Which of these is a super class of wrappers Long, Character & Integer?


a) Long
b) Digits
c) Float
d) Number
View Answer

Answer: d
Explanation: Number is an abstract class containing subclasses Double, Float, Byte, Short, Integer and Long.

4. Which of these is wrapper for simple data type char?


a) Float
b) Character
c) String
d) Integer
View Answer

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.

6. Which of these methods is used to obtain value of invoking object as a long?


a) long value()
b) long longValue()
c) Long longvalue()
d) Long Longvalue()
View Answer

Answer: b
Explanation: long longValue() is used to obtain value of invoking object as a long.

7. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. char a[] = {'a', '5', 'A', ' '};

6. System.out.print(Character.isDigit(a[0]) + " ");

7. System.out.print(Character.isWhitespace(a[3]) + " ");

8. System.out.print(Character.isUpperCase(a[2]));

9. }

10. }

a) true false true


b) false true true
c) true true false
d) false false false
View Answer

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

8. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. Integer i = new Integer(257);

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

9. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. Integer i = new Integer(257);

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

10. What is the output of this program?

1. class Output
2. {

3. public static void main(String args[])

4. {

5. Long i = new Long(256);

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.

1. Which of these class have only one field ‘TYPE’?


a) Void
b) Process
c) System
d) Runtime
View Answer

Answer: a
Explanation: The Void class has one field, TYPE, which holds a reference to the Class object for the type void.

2. Which of the following method of Process class can terminate a process?


a) void kill()
b) void destroy()
c) void terminate()
d) void exit()
View Answer

Answer: b
Explanation: Kills the subprocess. The subprocess represented by this Process object is forcibly terminated.

3. Standard output variable ‘out’ is defined in which class?


a) Void
b) Process
c) Runtime
d) System
View Answer

Answer: d
Explanation: Standard output variable ‘out’ is defined in System class. out is usually used in print statement i:e
System.out.print().

4. Which of these class can encapsulate an entire executing program?


a) Void
b) Process
c) Runtime
d) System
View Answer

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.

6. Which of these class holds a collection of static methods and variables?


a) Void
b) Process
c) Runtime
d) System
View Answer

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.

7. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. long start, end;

6. start = System.currentTimeMillis();

7. for (int i = 0; i < 10000000; i++);

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

8. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. byte a[] = { 65, 66, 67, 68, 69, 70 };

6. byte b[] = { 71, 72, 73, 74, 75, 76 };

7. System.arraycopy(a , 0, b, 0, a.length);

8. System.out.print(new String(a) + " " + new String(b));

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

9. What is the output of this program?


1. class Output

2. {

3. public static void main(String args[])

4. {

5. byte a[] = { 65, 66, 67, 68, 69, 70 };

6. byte b[] = { 71, 72, 73, 74, 75, 76 };

7. System.arraycopy(a, 2, b, 1, a.length-2);

8. System.out.print(new String(a) + " " + new String(b));

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

10. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. byte a[] = { 65, 66, 67, 68, 69, 70 };

6. byte b[] = { 71, 72, 73, 74, 75, 76 };

7. System.arraycopy(a, 1, b, 3, 0);

8. System.out.print(new String(a) + " " + new String(b));

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

Java Questions & Answers – Java.lang – Object & Math Class

This section of our 1000+ Java MCQs focuses on Object & Math classes of Java Programming Language.

1. Which of these class is superclass of all other classes?


a) Math
b) Process
c) System
d) Object
View Answer

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.

3. What is the value of double constant ‘E’ defined in Math class?


a) approximately 3
b) approximately 3.14
c) approximately 2.72
d) approximately 0
View Answer

Answer: c
Explanation: None.

4. Which of these method is a rounding function of Math class?


a) max()
b) min()
c) abs()
d) all of the mentioned
View Answer
Answer: d
Explanation: max(), min() and abs() are all rounding functions.

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, 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?

double d = Math.round ( 2.5 + Math.random() );

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.

8. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. int x = 3.14;

6. int y = (int) Math.abs(x);

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. {

3. public static void main(String args[])

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

10. What is the output of this program?

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

Java Questions & Answers – Java.lang – System Class Advance

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “System Class Advance”.

1. Which of these exceptions is thrown by methods of System class?


a) IOException
b) SystemException
c) SecurityException
d) InputOutputException
View Answer

Answer: c
Explanation: System class methods throw SecurityException.

2. Which of these methods initiates garbage collection?


a) gc()
b) garbage()
c) garbagecollection()
d) Systemgarbagecollection()
View Answer

Answer: a
Explanation: None.

3. Which of these methods loads the specified dynamic library?


a) load()
b) library()
c) loadlib()
d) loadlibrary()
View Answer

Answer: a
Explanation: load() methods loads the dynamic library whose name is specified.

4. Which of these method can set the out stream to OutputStream?


a) setStream()
b) setosteam()
c) setOut()
d) streamtoOstream()
View Answer

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.

6. What is the output of this program?

1. import java.lang.System;

2. class Output

3. {

4. public static void main(String args[])

5. {

6. long start, end;

7. start = System.currentTimeMillis();

8. for (int i = 0; i < 10000000; i++);

9. end = System.currentTimeMillis();

10. System.out.print(end - start);

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

7. What is the output of this program?

1. import java.lang.System;

2. class Output

3. {

4. public static void main(String args[])

5. {

6. byte a[] = { 65, 66, 67, 68, 69, 70 };

7. byte b[] = { 71, 72, 73, 74, 75, 76 };

8. System.arraycopy(a, 0, b, 0, a.length);

9. System.out.print(new String(a) + " " + new String(b));

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

8. What is the output of this program?

1. import java.lang.System;

2. class Output

3. {

4. public static void main(String args[])


5. {

6. byte a[] = { 65, 66, 67, 68, 69, 70 };

7. byte b[] = { 71, 72, 73, 74, 75, 76 };

8. System.arraycopy(a, 0, b, 3, a.length - 3);

9. System.out.print(new String(a) + " " + new String(b));

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

9. What is the output of this program?

1. import java.lang.System;

2. class Output

3. {

4. public static void main(String args[])

5. {

6. byte a[] = { 65, 66, 67, 68, 69, 70 };

7. byte b[] = { 71, 72, 73, 74, 75, 76 };

8. System.arraycopy(a, 2, b, 3, a.length - 4);

9. System.out.print(new String(a) + " " + new String(b));

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. {

4. public static void main(String args[])

5. {

6. System.exit(5);

7. }

8. }

a) 0
b) 1
c) 4
d) 5
View Answer

Answer: d
Explanation: None.

Java Questions & Answers – Java.lang – Double & Float Wrappers

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Double & Float Wrappers”.

1. Which of these is a super class of wrappers Double and Float?


a) Long
b) Digits
c) Float
d) Number
View Answer

Answer: d
Explanation: Number is an abstract class containing subclasses Double, Float, Byte, Short, Integer and Long.

2. Which of the following methods return the value as a double?


a) doubleValue()
b) converDouble()
c) getDouble()
d) getDoubleValue()
View Answer
Answer: a
Explanation: None.

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.

5. Which of these exceptions is thrown by compareTo() method defined in double wrapper?


a) IOException
b) SystemException
c) CastException
d) ClassCastException
View Answer

Answer: d
Explanation: compareTo() methods compare the specified object to be double, if it is not then ClassCastException is
thrown.

6. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. Double i = new Double(257.5);

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

7. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. Integer i = new Integer(257);

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

8. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])


4. {

5. Double i = new Double(257.578);

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

9. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. Double i = new Double(257.578123456789);

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

10. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. Double y = new Double(257.57812);

6. Double i = new Double(257.578123456789);

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

Java Questions & Answers – Java.io Introduction

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.

2. Which of these class is not a member class of java.io package?


a) String
b) StringReader
c) Writer
d) File
View Answer

Answer: a
Explanation: None.

3. Which of these interface is not a member of java.io package?


a) DataInput
b) ObjectInput
c) ObjectFilter
d) FileFilter
View Answer

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.

5. Which of these is specified by a File object?


a) a file in disk
b) directory path
c) directory in disk
d) none of the mentioned
View Answer

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.

7. What is the output of this program?

1. import java.io.*;

2. class files

3. {

4. public static void main(String args[])

5. {

6. File obj = new File("/java/system");

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

8. What is the output of this program?

1. import java.io.*;

2. class files

3. {

4. public static void main(String args[])

5. {

6. File obj = new File("/java/system");

7. System.out.print(obj.getAbsolutePath());
8. }

9. }

Note: file is made in c drive.


a) java
b) system
c) java/system
d) /java/system
View Answer

Answer: d
Explanation: None.
Output:
$ javac files.java
$ java files
\java\system

9. What is the output of this program?

1. import java.io.*;

2. class files

3. {

4. public static void main(String args[])

5. {

6. File obj = new File("/java/system");

7. System.out.print(obj.canWrite());

8. System.out.print(" " + obj.canRead());

9. }

10. }

Note: file is made in c drive.


a) true false
b) false true
c) true true
d) false false
View Answer

Answer: d
Explanation: None.
Output:
$ javac files.java
$ java files
false false

10. What is the output of this program?


1. import java.io.*;

2. class files

3. {

4. public static void main(String args[])

5. {

6. File obj = new File("/java/system");

7. System.out.print(obj.getParent());

8. System.out.print(" " + obj.isFile());

9. }

10. }

Note: file is made in c drive.


a) java true
b) java false
c) \java false
d) \java true
View Answer

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

Java Questions & Answers – Java.io Byte Streams

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.

2. Which of these class is used to read and write bytes in a file?


a) FileReader
b) FileWriter
c) FileInputStream
d) InputStreamReader
View Answer

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.

4. Which of these data type is returned by every method of OutputStream?


a) int
b) float
c) byte
d) none of the mentioned
View Answer

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.

6. Which of these method(s) is/are used for writing bytes to an outputstream?


a) put()
b) print() and write()
c) printf()
d) write() and read()
View Answer

Answer: b
Explanation: write() and print() are the two methods of OutputStream that are used for printing the byte data.

7. What is the output of this program?

1. import java.io.*;

2. class filesinputoutput

3. {
4. public static void main(String args[])

5. {

6. InputStream obj = new FileInputStream("inputoutput.java");

7. System.out.print(obj.available());

8. }

9. }

Note: inputoutput.java is stored in the disk.


a) true
b) false
c) prints number of bytes in file
d) prints number of characters in the file
View Answer

Answer: c
Explanation: obj.available() returns the number of bytes.
Output:
$ javac filesinputoutput.java
$ java filesinputoutput
1422
(Output will be different in your case)

8. What is the output of this program?

1. import java.io.*;

2. public class filesinputoutput

3. {

4. public static void main(String[] args)

5. {

6. String obj = "abc";

7. byte b[] = obj.getBytes();

8. ByteArrayInputStream obj1 = new ByteArrayInputStream(b);

9. for (int i = 0; i < 2; ++ i)

10. {

11. int c;

12. while ((c = obj1.read()) != -1)

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

9. What is the output of this program?

1. import java.io.*;

2. public class filesinputoutput

3. {

4. public static void main(String[] args)

5. {

6. String obj = "abc";

7. byte b[] = obj.getBytes();

8. ByteArrayInputStream obj1 = new ByteArrayInputStream(b);

9. for (int i = 0; i < 2; ++ i)

10. {

11. int c;

12. while ((c = obj1.read()) != -1)

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

10. What is the output of this program?

1. import java.io.*;

2. public class filesinputoutput

3. {

4. public static void main(String[] args)

5. {

6. String obj = "abc";

7. byte b[] = obj.getBytes();

8. ByteArrayInputStream obj1 = new ByteArrayInputStream(b);

9. for (int i = 0; i < 2; ++ i)

10. {

11. int c;

12. while ((c = obj1.read()) != -1)

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

Java Questions & Answers – Java.io Character Streams

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.

2. Which of these class is used to read characters in a file?


a) FileReader
b) FileWriter
c) FileInputStream
d) InputStreamReader
View Answer

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.

7. What is the output of this program?

1. import java.io.*;

2. class filesinputoutput

3. {

4. public static void main(String args[])

5. {

6. InputStream obj = new FileInputStream("inputoutput.java");

7. System.out.print(obj.available());

8. }
9. }

Note: inputoutput.java is stored in the disk.


a) true
b) false
c) prints number of bytes in file
d) prints number of characters in the file
View Answer

Answer: c
Explanation: obj.available() returns the number of bytes.
Output:
$ javac filesinputoutput.java
$ java filesinputoutput
1422
(Output will be different in your case)

8. What is the output of this program?

1. import java.io.*;

2. class Chararrayinput

3. {

4. public static void main(String[] args)

5. {

6. String obj = "abcdef";

7. int length = obj.length();

8. char c[] = new char[length];

9. obj.getChars(0,length,c,0);

10. CharArrayReader input1 = new CharArrayReader(c);

11. CharArrayReader input2 = new CharArrayReader(c, 0, 3);

12. int i;

13. try

14. {

15. while ((i = input1.read()) != -1)

16. {

17. System.out.print((char)i);

18. }

19. }

20. catch (IOException e)


21. {

22. // TODO Auto-generated catch block

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

9. What is the output of this program?

1. import java.io.*;

2. class Chararrayinput

3. {

4. public static void main(String[] args)

5. {

6. String obj = "abcdef";

7. int length = obj.length();

8. char c[] = new char[length];

9. obj.getChars(0, length, c, 0);

10. CharArrayReader input1 = new CharArrayReader(c);

11. CharArrayReader input2 = new CharArrayReader(c, 0, 3);

12. int i;

13. try

14. {

15. while ((i = input2.read()) != -1)

16. {
17. System.out.print((char)i);

18. }

19. }

20. catch (IOException e)

21. {

22. // TODO Auto-generated catch block

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

10. What is the output of this program?

1. import java.io.*;

2. class Chararrayinput

3. {

4. public static void main(String[] args)

5. {

6. String obj = "abcdefgh";

7. int length = obj.length();

8. char c[] = new char[length];

9. obj.getChars(0, length, c, 0);

10. CharArrayReader input1 = new CharArrayReader(c);

11. CharArrayReader input2 = new CharArrayReader(c, 1, 4);

12. int i;
13. int j;

14. try

15. {

16. while ((i = input1.read()) == (j = input2.read()))

17. {

18. System.out.print((char)i);

19. }

20. }

21. catch (IOException e)

22. {

23. // TODO Auto-generated catch block

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

Java Questions & Answers – Memory Management

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Memory Management”.

1. Which of the following is not a segment of memory in java?


a) Stack Segment
b) Heap Segment
c) Code Segment
d) Register Segment
View Answer

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.

4. Which one of the following is a class loader?


a) Bootstrap
b) Compiler
c) Heap
d) Interpretor
View Answer

Answer: a
Explanation: Bootstrap is a class loader. It loads the classes into memory.

5. Which class loader loads jar files from JDK directory?


a) Bootstrap
b) Extension
c) System
d) Heap
View Answer

Answer: b
Explanation: Extension loads jar files from lib/ext directory of the JRE.This gives the basic functionality available.

6. Which of the following is not a memory classification in java?


a) Young
b) Old
c) Permanent
d) Temporary
View Answer

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.

7. What is the java 8 update of PermGen?


a) Code Cache
b) Tenured Space
c) Metaspace
d) Eden space
View Answer

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.

8. Classes and Methods are stored in which space?


a) Eden space
b) Survivor space
c) Tenured space
d) Permanent space
View Answer

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.

9. Where is String Pool stored?


a) Java Stack
b) Java Heap
c) Permanent Generation
d) Metaspace
View Answer

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.

10. The same import package/class be called twice in java?


a) True
b) False
View Answer

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.

Java Questions & Answers – Java’s Built in Exceptions

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.

3. Which of these packages contain all the Java’s built in exceptions?


a) java.io
b) java.util
c) java.lang
d) java.net
View Answer

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.

5. Which of these class is used to create user defined exception?


a) java.lang
b) Exception
c) RunTime
d) System
View Answer

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

6. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])


4. {

5. try

6. {

7. int a[] = {1, 2,3 , 4, 5};

8. for (int i = 0; i < 7; ++i)

9. System.out.print(a[i]);

10. }

11. catch(ArrayIndexOutOfBoundsException e)

12. {

13. System.out.print("0");

14. }

15. }

16. }

a) 12345
b) 123450
c) 1234500
d) Compilation Error
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

7. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. int a[] = {1, 2,3 , 4, 5};

8. for (int i = 0; i < 5; ++i)


9. System.out.print(a[i]);

10. int x = 1/0;

11. }

12. catch(ArrayIndexOutOfBoundsException e)

13. {

14. System.out.print("A");

15. }

16. catch(ArithmeticException e)

17. {

18. System.out.print("B");

19. }

20. }

21. }

a) 12345
b) 12345A
c) 12345B
d) 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

8. What is the output of this program?

1. class exception_handling

2. {

3. static void throwexception() throws ArithmeticException

4. {

5. System.out.print("0");

6. throw new ArithmeticException ("Exception");

7. }

8. public static void main(String args[])


9. {

10. try

11. {

12. throwexception();

13. }

14. catch (ArithmeticException e)

15. {

16. System.out.println("A");

17. }

18. }

19. }

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

Answer: c
Explanation: None.
Output:
$ javac exception_handling.java
$ java exception_handling
0A

9. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. int a = 1;

8. int b = 10 / a;

9. try

10. {

11. if (a == 1)
12. a = a / a - a;

13. if (a == 2)

14. {

15. int c[] = {1};

16. c[8] = 9;

17. }

18. finally

19. {

20. System.out.print("A");

21. }

22.

23. }

24. catch (NullPointerException e)

25. {

26. System.out.println("B");

27. }

28. }

29. }

a) A
b) B
c) AB
d) BA
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

10. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])


4. {

5. try

6. {

7. int a = args.length;

8. int b = 10 / a;

9. System.out.print(a);

10. try

11. {

12. if (a == 1)

13. a = a / a - a;

14. if (a == 2)

15. {

16. int c = {1};

17. c[8] = 9;

18. }

19. }

20. catch (ArrayIndexOutOfBoundException e)

21. {

22. System.out.println("TypeA");

23. }

24. catch (ArithmeticException e)

25. {

26. System.out.println("TypeB");

27. }

28. }

29. }

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

Java Questions & Answers – Java.lang – Rounding Functions

This section of our 1000+ Java MCQs focuses on rounding functions in Java Programming Language.

1. Which of these class provides various types of rounding functions?


a) Math
b) Process
c) System
d) Object
View Answer

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.

4. Which of these method is a rounding function of Math class?


a) max()
b) min()
c) abs()
d) rint()
View Answer

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.

6. Which of function return absolute value of a variable?


a) abs()
b) absolute()
c) absolutevariable()
d) none of the mentioned
View Answer

Answer: a
Explanation: abs() returns the absolute value of a variable.

7. What is the output of this program?

1. class A

2. {

3. int x;

4. int y;

5. void display()

6. {

7. System.out.print(x + " " + y);

8. }

9. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. A obj1 = new A();

15. A obj2 = new A();

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

8. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. double x = 3.14;

6. int y = (int) Math.abs(x);

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. {

3. public static void main(String args[])

4. {

5. double x = 3.14;

6. int y = (int) Math.ceil(x);

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

10. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. double x = 3.14;

6. int y = (int) Math.floor(x);

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

Java Questions & Answers – Java.lang – Byte & Short Wrappers

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.

3. Which of these is a super class of wrappers Byte and short wrappers?


a) Long
b) Digits
c) Float
d) Number
View Answer

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.

5. Which of these exceptions is thrown by compareTo() method defined in double wrapper?


a) IOException
b) SystemException
c) CastException
d) ClassCastException
View Answer

Answer: d
Explanation: compareTo() methods compare the specified object to be double, if it is not then ClassCastException is
thrown.

6. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. Double i = new Double(257.5);

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

7. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])


4. {

5. Double i = new Double(257.5);

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

8. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. Integer i = new Integer(257);

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

9. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. Double i = new Double(257.578123456789);

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

10. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. Double y = new Double(257.57812);

6. Double i = new Double(257.578123456789);

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

Java Questions & Answers – Java.lang – Character Wrapper Advance

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.

2. Which of the following constant are defined in Character wrapper?


a) MAX_RADIX
b) MAX_VALUE
c) TYPE
d) All of the mentioned
View Answer

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.

5. Which of these coding techniques is used by method isDefined()?


a) Latin
b) ASCII
c) ANSI
d) UNICODE
View Answer

Answer: d
Explanation: isDefined() returns true if ch is defined by Unicode. Otherwise, it returns false.

6. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

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
?

7. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

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

8. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. char a[] = {'a', '5', 'A', ' '};

6. System.out.print(Character.isDigit(a[0])+ " ");

7. System.out.print(Character.isWhitespace(a[3])+ " ");

8. System.out.print(Character.isUpperCase(a[2]));

9. }
10. }

a) true false true


b) false true true
c) true true false
d) false false false
View Answer

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

9. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. char a = (char) 98;

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

10. What is the output of this program?

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

Java Questions & Answers – Java.lang – Boolean Wrapper Advance

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

1. Which of these methods of Boolean wrapper returns boolean equivalent of an object.


a) getBool()
b) booleanValue()
c) getbooleanValue()
d) getboolValue()
View Answer

Answer: b
Explanation: None.

2. Which of the following constant are defined in Boolean wrapper?


a) TRUE
b) FALSE
c) TYPE
d) All of the mentioned
View Answer

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

3. Which of these methods return string equivalent of Boolean object?


a) getString()
b) toString()
c) converString()
d) getStringObject()
View Answer

Answer: b
Explanation: None.

4. Which of these methods is used to know whether a string contains “true”?


a) valueOf()
b) valueOfString()
c) getString()
d) none of the mentioned
View Answer

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

5. Which of these class have only one field?


a) Character
b) Boolean
c) Byte
d) void
View Answer

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.

6. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. String str = "true";

6. boolean x = Boolean.valueOf(str);

7. System.out.print(x);

8. }

9. }

a) True
b) False
c) Compilation Error
d) Runtime Error
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

7. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. String str = "true false true";

6. boolean x = Boolean.valueOf(str);

7. System.out.print(x);

8. }

9. }

a) True
b) False
c) Compilation Error
d) Runtime Error
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

8. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. String str = "TRUE";

6. boolean x = Boolean.valueOf(str);

7. System.out.print(x);

8. }

9. }
a) True
b) False
c) Compilation Error
d) Runtime Error
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

9. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. String str = "true false";

6. boolean x = Boolean.parseBoolean(str);

7. System.out.print(x);

8. }

9. }

a) True
b) False
c) System Dependent
d) Compilation Error
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

10. What is the output of this program?

1. class Output
2. {

3. public static void main(String args[])

4. {

5. String x = Boolean.toString(false);

6. }

7. }

a) True
b) False
c) System Dependent
d) Compilation Error
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.

2. Which of these method return a pseudorandom number?


a) rand()
b) random()
c) randomNumber()
d) randGenerator()
View Answer

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.

4. Which of these method converts radians to degrees?


a) toRadian()
b) toDegree()
c) convertRadian()
d) converDegree()
View Answer

Answer: b
Explanation: None.

5. toRadian() and toDegree() methods were added by which version of Java?


a) Java 1.0
b) Java 1.5
c) Java 2.0
d) Java 3.0
View Answer

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.

7. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. double x = 3.14;

6. int y = (int) Math.toDegrees(x);


7. System.out.print(y);

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

8. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. double x = 3.14;

6. int y = (int) Math.toRadians(x);

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

9. What is the output of this program?

1. class Output
2. {

3. public static void main(String args[])

4. {

5. double x = 102;

6. double y = 5;

7. double z = Math.IEEEremainder(x, y);

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

10. Will this program generate same output is executed again?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. int y = double z = Math.random();

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

Java Questions & Answers – Java.lang – Runtime & ClassLoader Classes

This section of our 1000+ Java MCQs focuses Runtime & ClassLoader classes of Java Programming Language.

1. Which of these classes encapsulate runtime enviroment?


a) Class
b) System
c) Runtime
d) ClassLoader
View Answer

Answer: c
Explanation: None.

2. Which of the following exceptions is thrown by every method of Runtime class?


a) IOException
b) SystemException
c) SecurityException
d) RuntimeException
View Answer

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.

4. Which of these class defines how the classes are loaded?


a) Class
b) System
c) Runtime
d) ClassLoader
View Answer

Answer: d
Explanation: None.

5. Which of these methods return a class object given its name?


a) getClass()
b) findClass()
c) getSystemClass()
d) findSystemClass()
View Answer
Answer: d
Explanation: findSystemClass() returns a class object given its name.

6. Which of these Exceptions is thrown by loadClass() method of ClassLoader class?


a) IOException
b) SystemException
c) ClassFormatError
d) ClassNotFoundException
View Answer

Answer: d
Explanation: None.

7. 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. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. X a = new X();

15. Y b = new Y();

16. Class obj;

17. obj = b.getClass();

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. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. X a = new X();

15. Y b = new Y();

16. Class obj;

17. obj = b.getClass();

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

9. 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. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. X a = new X();

15. Y b = new Y();

16. Class obj;

17. obj = b.getClass();

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

10. 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. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. X a = new X();

15. Y b = new Y();

16. Class obj;

17. obj = b.getClass();

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 – Class

This section of our 1000+ Java MCQs focuses Class of java.lang library of Java Programming Language.

1. Which of these classes encapsulate run-time state of an object?


a) Class
b) System
c) Runtime
d) Catche
View Answer

Answer: a
Explanation: None.

2. Which of the following constant are defined in Boolean wrapper?


a) TRUE
b) FLASE
c) TYPE
d) All of the mentioned
View Answer

Answer: d
Explanation: Boolean wrapper defines 3 constants – TRUE, FLASE & TYPE.

3. Which of these methods returns the class of an object?


a) getClass()
b) Class()
c) WhoseClass()
d) WhoseObject()
View Answer

Answer: a
Explanation: None.

4. Which of these methods is used to know whether a string contains “true”?


a) valueOf()
b) valueOfString()
c) getString()
d) None of the mentioned
View Answer

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

5. Which of these class have only one field?


a) Character
b) Boolean
c) Byte
d) void
View Answer
Answer: d
Explanation: Void class has only one field – TYPE, which holds a reference to the Class object for type void. We do
not create instance of this class.

6. 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. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. X a = new X();

15. Y b = new Y();

16. Class obj;

17. obj = a.getClass();

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

7. 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. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. X a = new X();

15. Y b = new Y();

16. Class obj;

17. obj = b.getClass();

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. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. X a = new X();

15. Y b = new Y();

16. Class obj;

17. obj = b.getClass();

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

9. 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. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. X a = new X();

15. Y b = new Y();

16. Class obj;

17. obj = b.getClass();

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

10. 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. }

10. class Output

11. {

12. public static void main(String args[])

13. {

14. X a = new X();

15. Y b = new Y();

16. Class obj;

17. obj = b.getClass();

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.

2. Which of these class is used to make a thread?


a) String
b) System
c) Thread
d) Runnable
View Answer

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.

3. Which of these interface is implemented by Thread class?


a) Runnable
b) Connections
c) Set
d) MapConnections
View Answer

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.

5. toRadian() and toDegree() methods were added by which version of Java?


a) Java 1.0
b) Java 1.5
c) Java 2.0
d) Java 3.0
View Answer

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. What is the output of this program?

1. class newthread implements Runnable

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. }

11. public void run()

12. {

13. t2.setPriority(Thread.MAX_PRIORITY);

14. System.out.print(t1.equals(t2));

15. }

16. }

17. class multithreaded_programing

18. {

19. public static void main(String args[])

20. {

21. new newthread();

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?

1. class newthread implements Runnable

2. {

3. Thread t;

4. newthread()

5. {

6. t = new Thread(this,"New Thread");

7. t.start();

8. }

9. public void run()

10. {

11. t.setPriority(Thread.MAX_PRIORITY);

12. System.out.println(t);

13. }

14. }

15. class multithreaded_programing

16. {

17. public static void main(String args[])

18. {

19. new newthread();

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?

1. class newthread implements Runnable

2. {

3. Thread t;

4. newthread()

5. {

6. t = new Thread(this,"My Thread");

7. t.start();

8. }

9. }

10. class multithreaded_programing

11. {

12. public static void main(String args[])

13. {

14. new newthread();

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()

9. What is the output of this program?

1. class newthread implements Runnable

2. {

3. Thread t;

4. newthread()
5. {

6. t = new Thread(this,"My Thread");

7. t.start();

8. }

9. public void run()

10. {

11. System.out.println(t.getName());

12. }

13. }

14. class multithreaded_programing

15. {

16. public static void main(String args[])

17. {

18. new newthread();

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

10. What is the output of this program?

1. class newthread implements Runnable

2. {

3. Thread t;

4. newthread()

5. {

6. t = new Thread(this,"My Thread");


7. t.start();

8. }

9. public void run()

10. {

11. System.out.println(t);

12. }

13. }

14. class multithreaded_programing

15. {

16. public static void main(String args[])

17. {

18. new newthread();

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]

Java Questions & Answers – Environment Properties

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Environment Properties”.

1. Which object Java application uses to create a new process?


a) Process
b) Builder
c) ProcessBuilder
d) CreateBuilder
View Answer

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.

3. Java system properties can be set at runtime.


a) True
b) False
View Answer

Answer: a
Explanation: Java system properties can be set at runtime using System.setProperty(name, value) or using
System.getProperties().load() methods.

4. Which system property stores installation directory of JRE?


a) user.home
b) java.class.path
c) java.home
d) user.dir
View Answer

Answer: c
Explanation: java.home is the installation directory of Java Runtime Environment.

5. What does System.getProperty(“variable”) return?


a) compilation error
b) value stored in variable
c) runtime error
d) null
View Answer

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.

6. What is true about setProperties method?


a) setProperties method changes the set of Java Properties which are persistent
b) Changing the system properties within an application will affect future invocations
c) setProperties method changes the set of Java Properties which are not persistent
d) setProperties writes the values directly into the file which stores all the properties
View Answer

Answer: c
Explanation: The changes made by setProperties method are not persistent. Hence, it does not affect future
invocation.

7. How to use environment properties in the class?


a) @Environment
b) @Variable
c) @Property
d) @Autowired
View Answer

Answer: d
Explanation: @Autowired
private Environment env;
This is how environment variables are injected in the class where they can be used.

8. How to assign values to variable using property?


a) @Value(“${my.property}”)
private String prop;
b) @Property(“${my.property}”)
private String prop;
c) @Environment(“${my.property}”)
private String prop;
d) @Env(“${my.property}”)
private String prop;
View Answer

Answer: a
Explanation: @Value are used to inject the properties and assign them to variables.

9. Which environment variable is used to set java path?


a) JAVA
b) JAVA_HOME
c) CLASSPATH
d) MAVEN_HOME
View Answer

Answer: b
Explanation: JAVA_HOME is used to store path to the java installation.

10. How to read a classpath file?


a) InputStream in =this.getClass().getResource(“SomeTextFile.txt”);
b) InputStream in =this.getClass().getResourceClasspath(“SomeTextFile.txt”);
c) InputStream in =this.getClass().getResourceAsStream(“SomeTextFile.txt”);
d) InputStream in =this.getClass().getResource(“classpath:/SomeTextFile.txt”);
View Answer

Answer: c
Explanation: This method can be used to load files using relative path to the package of the class.

Java Questions & Answers – Serialization – 1

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Serialization – 1”.

1. Which of these is a process of writing the state of an object to a byte stream?


a) Serialization
b) Externalization
c) File Filtering
d) All of the mentioned
View Answer

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.

2. Which of these process occur automatically by java run time system?


a) Serialization
b) Garbage collection
c) File Filtering
d) All of the mentioned
View Answer

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.

3. Which of these is an interface for control over serialization and deserialization?


a) Serializable
b) Externalization
c) FileFilter
d) ObjectInput
View Answer

Answer: b
Explanation: None.

4. Which of these interface extends DataOutput interface?


a) Serializable
b) Externalization
c) ObjectOutput
d) ObjectInput
View Answer

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.

7. What is the output of this program?

1. import java.io.*;

2. class serialization

3. {

4. public static void main(String[] args)

5. {

6. try

7. {

8. Myclass object1 = new Myclass("Hello", -7, 2.1e10);

9. FileOutputStream fos = new FileOutputStream("serial");

10. ObjectOutputStream oos = new ObjectOutputStream(fos);

11. oos.writeObject(object1);

12. oos.flush();

13. oos.close();

14. }

15. catch(Exception e)

16. {

17. System.out.println("Serialization" + e);

18. System.exit(0);

19. }

20. try

21. {

22. Myclass object2;

23. FileInputStream fis = new FileInputStream("serial");

24. ObjectInputStream ois = new ObjectInputStream(fis);

25. object2 = (Myclass)ois.readObject();


26. ois.close();

27. System.out.println(object2);

28. }

29. catch (Exception e)

30. {

31. System.out.print("deserialization" + e);

32. System.exit(0);

33. }

34. }

35. }

36. class Myclass implements Serializable

37. {

38. String s;

39. int i;

40. double d;

41. Myclass (String s, int i, double d)

42. {

43. this.d = d;

44. this.i = i;

45. this.s = s;

46. }

47. }

a) s=Hello; i=-7; d=2.1E10


b) Hello; -7; 2.1E10
c) s; i; 2.1E10
d) Serialization
View Answer

Answer: a
Explanation: None.
Output:
$ javac serialization.java
$ java serialization
s=Hello; i=-7; d=2.1E10

8. What is the output of this program?


1. import java.io.*;

2. class serialization

3. {

4. public static void main(String[] args)

5. {

6. try

7. {

8. Myclass object1 = new Myclass("Hello", -7, 2.1e10);

9. FileOutputStream fos = new FileOutputStream("serial");

10. ObjectOutputStream oos = new ObjectOutputStream(fos);

11. oos.writeObject(object1);

12. oos.flush();

13. oos.close();

14. }

15. catch(Exception e)

16. {

17. System.out.println("Serialization" + e);

18. System.exit(0);

19. }

20. try

21. {

22. int x;

23. FileInputStream fis = new FileInputStream("serial");

24. ObjectInputStream ois = new ObjectInputStream(fis);

25. x = ois.readInt();

26. ois.close();

27. System.out.println(x);

28. }

29. catch (Exception e)

30. {
31. System.out.print("deserialization");

32. System.exit(0);

33. }

34. }

35. }

36. class Myclass implements Serializable

37. {

38. String s;

39. int i;

40. double d;

41. Myclass(String s, int i, 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

9. What is the output of this program?

1. import java.io.*;

2. class Chararrayinput

3. {

4. public static void main(String[] args)


5. {

6. String obj = "abcdefgh";

7. int length = obj.length();

8. char c[] = new char[length];

9. obj.getChars(0, length, c, 0);

10. CharArrayReader input1 = new CharArrayReader(c);

11. CharArrayReader input2 = new CharArrayReader(c, 1, 4);

12. int i;

13. int j;

14. try

15. {

16. while ((i = input1.read()) == (j = input2.read()))

17. {

18. System.out.print((char)i);

19. }

20. }

21. catch (IOException e)

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. {

4. public static void main(String[] args)

5. {

6. try

7. {

8. FileOutputStream fos = new FileOutputStream("serial");

9. ObjectOutputStream oos = new ObjectOutputStream(fos);

10. oos.writeFloat(3.5);

11. oos.flush();

12. oos.close();

13. }

14. catch(Exception e)

15. {

16. System.out.println("Serialization" + e);

17. System.exit(0);

18. }

19. try

20. {

21. float x;

22. FileInputStream fis = new FileInputStream("serial");

23. ObjectInputStream ois = new ObjectInputStream(fis);

24. x = ois.readInt();

25. ois.close();

26. System.out.println(x);

27. }

28. catch (Exception e)

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

Java Questions & Answers – Serialization – 2

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Serialization – 2”.

1. How an object can become serializable?


a) If class implements java.io.Serializable class
b) If class or any superclass implements java.io.Serializable interface
c) Any object is serializable
d) No object is serializable
View Answer

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.

4. How many methods Serializable has?


a) 1
b) 2
c) 3
d) 0
View Answer

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

5. What type of members are not serialized?


a) Private
b) Protected
c) Static
d) Throwable
View Answer

Answer: c
Explanation: All static and transient variables are not serialized.

6. If member does not implement serialization, which exception would be thrown?


a) RuntimeException
b) SerializableException
c) NotSerializableException
d) UnSerializedException
View Answer

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

7. Default Serialization process cannot be overridden.


a) True
b) False
View Answer

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.

10. Serializaed object can be transfered via network.


a) True
b) False
View Answer

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.

Java Questions & Answers – Serialization & Deserialization

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Serialization & Deserialization”.

1. Which of these is a process of extracting/removing the state of an object from a stream?


a) Serialization
b) Externalization
c) File Filtering
d) Deserialization
View Answer

Answer: d
Explanation: Deserialization is a process by which the data written in the stream can be extracted out from the
stream.

2. Which of these process occur automatically by java run time system?


a) Serialization
b) Memory allocation
c) Deserialization
d) All of the mentioned
View Answer

Answer: d
Explanation: Serialization, deserialization and Memory allocation occur automatically by java run time system.

3. Which of these is an interface for control over serialization and deserialization?


a) Serializable
b) Externalization
c) FileFilter
d) ObjectInput
View Answer

Answer: b
Explanation: None.

4. Which of these interface extends DataInput interface?


a) Serializable
b) Externalization
c) ObjectOutput
d) ObjectInput
View Answer

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.

6. Which of these class extend InputStream class?


a) ObjectStream
b) ObjectInputStream
c) ObjectOutput
d) ObjectInput
View Answer

Answer: b
Explanation: ObjectInputStream class extends the InputStream class and implements the ObjectInput interface.

7. What is the output of this program?

1. import java.io.*;

2. class streams

3. {

4. public static void main(String[] args)

5. {

6. try

7. {

8. FileOutputStream fos = new FileOutputStream("serial");

9. ObjectOutputStream oos = new ObjectOutputStream(fos);


10. oos.writeInt(5);

11. oos.flush();

12. oos.close();

13. }

14. catch(Exception e)

15. {

16. System.out.println("Serialization" + e);

17. System.exit(0);

18. }

19. try

20. {

21. int z;

22. FileInputStream fis = new FileInputStream("serial");

23. ObjectInputStream ois = new ObjectInputStream(fis);

24. z = ois.readInt();

25. ois.close();

26. System.out.println(x);

27. }

28. catch (Exception e)

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

8. What is the output of this program?

1. import java.io.*;

2. class serialization

3. {

4. public static void main(String[] args)

5. {

6. try

7. {

8. Myclass object1 = new Myclass("Hello", -7, 2.1e10);

9. FileOutputStream fos = new FileOutputStream("serial");

10. ObjectOutputStream oos = new ObjectOutputStream(fos);

11. oos.writeObject(object1);

12. oos.flush();

13. oos.close();

14. }

15. catch(Exception e)

16. {

17. System.out.println("Serialization" + e);

18. System.exit(0);

19. }

20. try

21. {

22. int x;

23. FileInputStream fis = new FileInputStream("serial");

24. ObjectInputStream ois = new ObjectInputStream(fis);

25. x = ois.readInt();

26. ois.close();
27. System.out.println(x);

28. }

29. catch (Exception e)

30. {

31. System.out.print("deserialization");

32. System.exit(0);

33. }

34. }

35. }

36. class Myclass implements Serializable

37. {

38. String s;

39. int i;

40. double d;

41. Myclass(String s, int i, 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

9. What is the output of this program?


1. import java.io.*;

2. class streams

3. {

4. public static void main(String[] args)

5. {

6. try

7. {

8. FileOutputStream fos = new FileOutputStream("serial");

9. ObjectOutputStream oos = new ObjectOutputStream(fos);

10. oos.writeFloat(3.5);

11. oos.flush();

12. oos.close();

13. }

14. catch(Exception e)

15. {

16. System.out.println("Serialization" + e);

17. System.exit(0);

18. }

19. try

20. {

21. FileInputStream fis = new FileInputStream("serial");

22. ObjectInputStream ois = new ObjectInputStream(fis);

23. ois.close();

24. System.out.println(ois.available());

25. }

26. catch (Exception e)

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

10. What is the output of this program?

1. import java.io.*;

2. class streams

3. {

4. public static void main(String[] args)

5. {

6. try

7. {

8. FileOutputStream fos = new FileOutputStream("serial");

9. ObjectOutputStream oos = new ObjectOutputStream(fos);

10. oos.writeFloat(3.5);

11. oos.flush();

12. oos.close();

13. }

14. catch(Exception e)

15. {

16. System.out.println("Serialization" + e);

17. System.exit(0);

18. }

19. try
20. {

21. FileInputStream fis = new FileInputStream("serial");

22. ObjectInputStream ois = new ObjectInputStream(fis);

23. System.out.println(ois.available());

24. }

25. catch (Exception e)

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;

2. public class FileOutputStreamExample

3. {

4. public static void main(String args[])

5. {

6. try

7. {

8. FileOutputStream fout=new FileOutputStream("D:\\sanfoundry.txt");


9. String s="Welcome to Sanfoundry.";

10. byte b[]=s.getBytes();//converting string into byte array

11. fout.write(b);

12. fout.close();

13. System.out.println("Success");

14. } catch(Exception e){System.out.println(e);}

15. }

16. }

a) “Success” to the output and “Welcome to Sanfoundry” to the file


b) only “Welcome to Sanfoundry” to the file
c) compile time error
d) No Output
View Answer

Answer: a
Explanation: First, it will print “Success” and besides that it will write “Welcome to Sanfoundry” to the file
sanfoundry.txt.

Java Questions & Answers – Networking Basics

This section of our 1000+ Java MCQs focuses on networking basics of Java Programming Language.

1. Which of these package contains classes and interfaces for networking?


a) java.io
b) java.util
c) java.net
d) java.network
View Answer

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.

3. How many ports of TCP/IP are reserved for specific protocols?


a) 10
b) 1024
c) 2048
d) 512
View Answer

Answer: b
Explanation: None.

4. How many bits are in a single IP address?


a) 8
b) 16
c) 32
d) 64
View Answer

Answer: c
Explanation: None.

5. Which of these is a full form of DNS?


a) Data Network Service
b) Data Name Service
c) Domain Network Service
d) Domain Name Service
View Answer

Answer: d
Explanation: None.

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.

7. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws UnknownHostException

5. {

6. InetAddress obj1 = InetAddress.getByName("sanfoundary.com");

7. InetAddress obj2 = InetAddress.getByName("sanfoundary.com");

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

8. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws UnknownHostException

5. {

6. InetAddress obj1 = InetAddress.getByName("cisco.com");

7. InetAddress obj2 = InetAddress.getByName("sanfoundary.com");

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

9. What is the output of this program?

1. import java.io.*;

2. import java.net.*;

3. public class URLDemo

4. {

5. public static void main(String[] args)

6. {

7. try

8. {

9. URL url=new URL("https://www.sanfoundry.com/java-mcq");

10. System.out.println("Protocol: "+url.getProtocol());

11. System.out.println("Host Name: "+url.getHost());

12. System.out.println("Port Number: "+url.getPort());

13. } catch(Exception e){System.out.println(e);}

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.

10. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws UnknownHostException

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”.

1. Which of these interface abstractes the output of messages from httpd?


a) LogMessage
b) LogResponse
c) Httpdserver
d) httpdResponse
View Answer

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.

3. Which of these is a standard for communicating multimedia content over email?


a) http
b) https
c) Mime
d) httpd
View Answer
Answer: c
Explanation: MIME is an internet standard for communicating multimedia content over email. The HTTP protocol
uses and extends the notion of MIME headers to pass attribute pairs between HTTP client and server.

4. Which of these methods is used to make raw MIME formatted string?


a) parse()
b) toString()
c) getString()
d) parseString()
View Answer

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.

7. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws Exception

5. {

6. URL obj = new URL("https://www.sanfoundry.com/javamcq");

7. URLConnection obj1 = obj.openConnection();

8. System.out.print(obj1.getContentType());

9. }
10. }

Note: Host URL is written in html and simple text.


a) html
b) text
c) html/text
d) text/html
View Answer

Answer: d
Explanation: None.
Output:
$ javac networking.java
$ java networking
text/html

8. Which of these is an instance variable of class httpd?


a) port
b) cache
c) log
d) All of the mentioned
View Answer

Answer: d
Explanation: There are 5 instance variables : port, docRoot, log, cache and stopFlag. All of them are private.

9. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws MalformedURLException

5. {

6. URL obj = new URL("https://www.sanfoundry.com/javamcq");

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

Java Questions & Answers – Networking – httpd.java Class

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.

7. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws Exception

5. {

6. URL obj = new URL("https://www.sanfoundry.com/javamcq");

7. URLConnection obj1 = obj.openConnection();

8. int len = obj1.getContentLength();

9. System.out.print(len);

10. }

11. }

Note: Host URL is having length of content 127.


a) 126
b) 127
c) Compilation Error
d) Runtime Error
View Answer

Answer: b
Explanation: None.
Output:
$ javac networking.java
$ java networking
127

8. Which of these method is used to start a server thread?


a) run()
b) start()
c) runThread()
d) startThread()
View Answer

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.

10. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws UnknownHostException

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 – URL Class

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “URL Class”.

1. What does URL stands for?


a) Uniform Resource Locator
b) Uniform Resource Latch
c) Universal Resource Locator
d) Universal Resource Latch
View Answer

Answer: a
Explanation: URL is Uniform Resource Locator.

2. Which of these exception is thrown by URL class’s constructors?


a) URLNotFound
b) URLSourceNotFound
c) MalformedURLException
d) URLNotFoundException
View Answer

Answer: c
Explanation: None.

3. Which of these methods is used to know host of an URL?


a) host()
b) getHost()
c) GetHost()
d) gethost()
View Answer

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.

7. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws MalformedURLException

5. {

6. URL obj = new URL("https://www.sanfoundry.com/javamcq");

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

8. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws MalformedURLException

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

9. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws MalformedURLException

5. {

6. URL obj = new URL("https://www.sanfoundry.com/javamcq");

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

10. What is the output of this program?


1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws MalformedURLException

5. {

6. URL obj = new URL("https://www.sanfoundry.com/javamcq");

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

Java Questions & Answers – HttpResponse & URLConnection Class

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.

7. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws Exception

5. {

6. URL obj = new URL("https://www.sanfoundry.com/javamcq");


7. URLConnection obj1 = obj.openConnection();

8. System.out.print(obj1.getContentType());

9. }

10. }

Note: Host URL is written in html and simple text.


a) html
b) text
c) html/text
d) text/html
View Answer

Answer: d
Explanation: None.
Output:
$ javac networking.java
$ java networking
text/html

8. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws Exception

5. {

6. URL obj = new URL("https://www.sanfoundry.com/javamcq");

7. URLConnection obj1 = obj.openConnection();

8. int len = obj1.getContentLength();

9. System.out.print(len);

10. }

11. }

Note: Host URL is having length of content 127.


a) 126
b) 127
c) Compilation Error
d) Runtime Error
View Answer

Answer: b
Explanation: None.
Output:
$ javac networking.java
$ java networking
127

9. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws Exception

5. {

6. URL obj = new URL("https://www.sanfoundry.com/javamcq");

7. URLConnection obj1 = obj.openConnection();

8. System.out.print(obj1.getLastModified);

9. }

10. }

Note: Host URL was last modified on july 18 tuesday 2013 .


a) july
b) 18-6-2013
c) Tue 18 Jun 2013
d) Tue Jun 18 2013
View Answer

Answer: d
Explanation: None.
Output:
$ javac networking.java
$ java networking
Tue Jun 18 2013

10. What is the output of this program?

1. import java.net.*;

2. class networking

3. {

4. public static void main(String[] args) throws MalformedURLException

5. {

6. URL obj = new URL("https://www.sanfoundry.com/javamcq");

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

Java Questions & Answers – Networking – Datagrams

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

1. Which of these is a bundle of information passed between machines?


a) Mime
b) Cache
c) Datagrams
d) DatagramSocket
View Answer

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

2. Which of these class is necessary to implement datagrams?


a) DatagramPacket
b) DatagramSocket
c) All of the mentioned
d) None of the mentioned
View Answer

Answer: c
Explanation: None.

3. Which of these method of DatagramPacket is used to find the port number?


a) port()
b) getPort()
c) findPort()
d) recievePort()
View Answer

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.

8. Which of these is a return type of getAddress() method of DatagramPacket class?


a) DatagramPacket
b) DatagramSocket
c) InetAddress
d) ServerSocket
View Answer

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

Java Questions & Answers – Java.util – ArrayList Class

This section of our 1000+ Java MCQs focuses on ArrayList class of Java Programming Language.

1. Which of these standard collection classes implements a dynamic array?


a) AbstractList
b) LinkedList
c) ArrayList
d) AbstractSet
View Answer

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.

6. Which of these method is used to reduce the capacity of an ArrayList object?


a) trim()
b) trimSize()
c) trimTosize()
d) trimToSize()
View Answer

Answer: d
Explanation: trimTosize() is used to reduce the size of the array that underlines an ArrayList object.

7. What is the output of this program?

1. import java.util.*;

2. class Arraylist

3. {

4. public static void main(String args[])

5. {

6. ArrayList obj = new ArrayList();

7. obj.add("A");

8. obj.add("B");

9. obj.add("C");

10. obj.add(1, "D");

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].

8. What is the output of this program?

1. import java.util.*;

2. class Output

3. {

4. public static void main(String args[])

5. {

6. ArrayList obj = new ArrayList();

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

9. What is the output of this program?

1. import java.util.*;

2. class Output

3. {

4. public static void main(String args[])

5. {

6. ArrayList obj = new ArrayList();

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

10. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

4. {

5. ArrayList obj = new ArrayList();

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

Java Questions & Answers – Data Structures-HashMap

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Data Structures-HashMap”.

1. Map implements collection interface?


a) True
b) False
View Answer

Answer: b
Explanation: Collection interface provides add, remove, search or iterate while map has clear, get, put, remove, etc.

2. Which of the below doesnt implement Map interface?


a) HashMap
b) Hashtable
c) EnumMap
d) Vector
View Answer

Answer: d
Explanation: Vector implements AbstractList which internally implements Collection. Others come from
implementing Map interface.

3. What is the premise of equality for IdentityHashMap?


a) Reference equality
b) Name equality
c) Hashcode equality
d) Length equality
View Answer

Answer: a
Explanation: IdentityHashMap is rarely used as it violates the basic contract of implementing equals() and hashcode()
method.

4. What happens if we put a key object in a HashMap which exists?


a) The new object replaces the older object
b) The new object is discarded
c) The old object is removed from the map
d) It throws an exception as the key already exists in the map
View Answer

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.

6. Is hashmap an ordered collection?


a) True
b) False
View Answer

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.

8. How to externally synchronize hashmap?


a) HashMap.synchronize(HashMap a);
b) HashMap a = new HashMap();
a.synchronize();
c) Collections.synchronizedMap(new HashMap<String, String>());
d) Collections.synchronize(new HashMap<String, String>());
View Answer

Answer: c
Explanation: Collections.synchronizedMap() synchronizes entire map. ConcurrentHashMap provides thread safety
without synchronizing entire map.

9. What is the output of below snippet?

1. public class Demo

2. {

3. public static void main(String[] args)

4. {

5. Map<Integer, Object> sampleMap = new TreeMap<Integer, Object>();

6. sampleMap.put(1, null);

7. sampleMap.put(5, null);
8. sampleMap.put(3, null);

9. sampleMap.put(2, null);

10. sampleMap.put(4, null);

11.

12. System.out.println(sampleMap);

13. }

14. }

a) {1=null, 2=null, 3=null, 4=null, 5=null}


b) {5=null}
c) Exception is thrown
d) {1=null, 5=null, 3=null, 2=null, 4=null}
View Answer

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.

Java Questions & Answers – Data Structures-List

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Data Structures-List”.

1. How can we remove an object from ArrayList?


a) remove() method
b) using Iterator
c) remove() method and using Iterator
d) delete() method
View Answer

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.

2. How to remove duplicates from List?


a) HashSet<String> listToSet = new HashSet<String>(duplicateList);
b) HashSet<String> listToSet = duplicateList.toSet();
c) HashSet<String> listToSet = Collections.convertToSet(duplicateList);
d) HashSet<String> listToSet = duplicateList.getSet();
View Answer
Answer: a
Explanation: Duplicate elements are allowed in List. Set contains unique objects.

3. How to sort elements of ArrayList?


a) Collection.sort(listObj);
b) Collections.sort(listObj);
c) listObj.sort();
d) Sorter.sortAsc(listObj);
View Answer

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.

5. How is Arrays.asList() different than the standard way of initialising List?


a) Both are same
b) Arrays.asList() throws compilation error
c) Arrays.asList() returns a fixed length list and doesn’t allow to add or remove elements
d) We cannot access the list returned using Arrays.asList()
View Answer

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.

6. What is the difference between length() and size() of ArrayList?


a) length() and size() return the same value
b) length() is not defined in ArrayList
c) size() is not defined in ArrayList
d) length() returns the capacity of ArrayList and size() returns the actual number of elements stored in the list
View Answer

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.

7. Which class provides thread safe implementation of List?


a) ArrayList
b) CopyOnWriteArrayList
c) HashList
d) List
View Answer
Answer: b
Explanation: CopyOnWriteArrayList is a concurrent collection class. Its very efficient if ArrayList is mostly used for
reading purpose, because it allows multiple threads to read data without locking, which was not possible with
synchronized ArrayList.

8. Which of the below is not an implementation of List interface?


a) RoleUnresolvedList
b) Stack
c) AttibuteList
d) SessionList
View Answer

Answer: d
Explanation: SessionList is not an implementation of List interface. The others are concrete classes of List.

9. What is the worst case complexity of accessing an element in ArrayList?


a) O(n)
b) O(1)
c) O(nlogn)
d) O(2)
View Answer

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.

1. public void setMyArray(String[] myArray)

2. {

3. if(myArray == null)

4. {

5. this.myArray = new String[0];

6. }

7. else

8. {

9. this.myArray = Arrays.copyOf(newArray, newArray.length);

10. }
11. }

Java Questions & Answers – Data Structures-Set

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Data Structures-Set”.

1. What is the default clone of HashSet?


a) Deep clone
b) Shallow clone
c) Plain clone
d) Hollow clone
View Answer

Answer: b
Explanation: Default clone() method uses shallow copy. The internal elements are not cloned. A shallow copy only
copies the reference object.

2. Do we have get(Object o) method in HashSet?


a) True
b) False
View Answer

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.

3. What does Collections.emptySet() return?


a) Immutable Set
b) Mutable Set
c) The type of Set depends on the parameter passed to the emptySet() method
d) Null object
View Answer

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.

4. What is the initial capacity and load factor of HashSet?


a) 10, 1.0
b) 32, 0.75
c) 16, 0.75
d) 32, 1.0
View Answer

Answer: c
Explanation: We should not set the initial capacity too high and load factor too low if iteration performance is
needed.

5. What is the relation between hashset and hashmap?


a) HashSet internally implements HashMap
b) HashMap internally implements HashSet
c) HashMap is the interface; HashSet is the concrete class
d) HashSet is the interface; HashMap is the concrete class
View Answer

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.

6. What is the output of below code snippet?

1. public class Test

2. {

3. public static void main(String[] args)

4. {

5. Set s = new HashSet();

6. s.add(new Long(10));

7. s.add(new Integer(10));

8. for(Object object : s)

9. {

10. System.out.println("test - "+object);

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.

7. Set has contains(Object o) method?


a) True
b) False
View Answer

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.

9. What happens if two threads simultaneously modify TreeSet?


a) ConcurrentModificationException is thrown
b) Both threads can perform action successfully
c) FailFastException is thrown
d) IteratorModificationException is thrown
View Answer

Answer: a
Explanation: TreeSet provides fail-fast iterator. Hence when concurrently modifying TreeSet it throws
ConcurrentModificationException.

10. What is the unique feature of LinkedHashSet?


a) It is not a valid class
b) It maintains the insertion order and guarantees uniqueness
c) It provides a way to store key values with uniqueness
d) The elements in the collection are linked to each other
View Answer

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.

2. Which of these classes implements Set interface?


a) ArrayList
b) HashSet
c) LinkedList
d) DynamicList
View Answer
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 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.

6. Which of these method is used to change an element in a LinkedList Object?


a) change()
b) set()
c) redo()
d) add()
View Answer

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.

7. What is the output of this program?

1. import java.util.*;

2. class Linkedlist

3. {
4. public static void main(String args[])

5. {

6. LinkedList obj = new LinkedList();

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].

8. What is the output of this program?

1. import java.util.*;

2. class Linkedlist

3. {

4. public static void main(String args[])

5. {

6. LinkedList obj = new LinkedList();

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]

9. What is the output of this program?

1. import java.util.*;

2. class Output

3. {

4. public static void main(String args[])

5. {

6. HashSet obj = new HashSet();

7. obj.add("A");

8. obj.add("B");

9. obj.add("C");

10. System.out.println(obj + " " + obj.size());

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

10. What is the output of this program?


1. import java.util.*;

2. class Output

3. {

4. public static void main(String args[])

5. {

6. TreeSet t = new TreeSet();

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].

Java Questions & Answers – Java.util – Maps

This section of our 1000+ Java MCQs focuses on Maps of Java Programming Language.

1. Which of these object stores association between keys and values?


a) Hash table
b) Map
c) Array
d) String
View Answer

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.

7. What is the output of this program?


1. import java.util.*;

2. class Maps

3. {

4. public static void main(String args[])

5. {

6. HashMap obj = new HashMap();

7. obj.put("A", new Integer(1));

8. obj.put("B", new Integer(2));

9. obj.put("C", new Integer(3));

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}

8. What is the output of this program?

1. import java.util.*;

2. class Maps

3. {

4. public static void main(String args[])

5. {

6. HashMap obj = new HashMap();

7. obj.put("A", new Integer(1));

8. obj.put("B", new Integer(2));

9. obj.put("C", new Integer(3));

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].

9. What is the output of this program?

1. import java.util.*;

2. class Maps

3. {

4. public static void main(String args[])

5. {

6. HashMap obj = new HashMap();

7. obj.put("A", new Integer(1));

8. obj.put("B", new Integer(2));

9. obj.put("C", new Integer(3));

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. {

4. public static void main(String args[])

5. {

6. TreeMap obj = new TreeMap();

7. obj.put("A", new Integer(1));

8. obj.put("B", new Integer(2));

9. obj.put("C", new Integer(3));

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].

Java Questions & Answers – Java.util – Vectors & Stack

This section of our 1000+ Java MCQs focuses on Vectors & Stack of Java Programming Language.

1. Which of these class object can be used to form a dynamic array?


a) ArrayList
b) Map
c) Vector
d) ArrayList & Vector
View Answer

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.

3. Which of these is the interface of legacy?


a) Map
b) Enumeration
c) HashMap
d) Hashtable
View Answer

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.

5. Which of these methods is used to add elements in vector at specific location?


a) add()
b) set()
c) AddElement()
d) addElement()
View Answer

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.

6. What is the output of this program?

1. import java.util.*;

2. class vector

3. {

4. public static void main(String args[])

5. {

6. Vector obj = new Vector(4,2);


7. obj.addElement(new Integer(3));

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

7. What is the output of this program?

1. import java.util.*;

2. class vector

3. {

4. public static void main(String args[])

5. {

6. Vector obj = new Vector(4,2);

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

8. What is the output of this program?

1. import java.util.*;

2. class vector

3. {

4. public static void main(String args[])

5. {

6. Vector obj = new Vector(4,2);

7. obj.addElement(new Integer(3));

8. obj.addElement(new Integer(2));

9. obj.addElement(new Integer(6));

10. obj.insertElementAt(new Integer(8), 2);

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].

9. What is the output of this program?

1. import java.util.*;

2. class vector

3. {

4. public static void main(String args[])


5. {

6. Vector obj = new Vector(4,2);

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

10. What is the output of this program?

1. import java.util.*;

2. class stack

3. {

4. public static void main(String args[])

5. {

6. Stack obj = new Stack();

7. obj.push(new Integer(3));

8. obj.push(new Integer(2));

9. obj.pop();

10. obj.push(new Integer(5));

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].

Java Questions & Answers – Java.util – Dictionary, Hashtable & Properties

This set of Java Problems focuses on “Java.util – Dictionary, Hashtable & Properties”.

1. Which of these class object uses key to store value?


a) Dictionary
b) Map
c) Hashtable
d) All of the mentioned
View Answer

Answer: d
Explanation: Dictionary, Map & Hashtable all implement Map interface hence all of them uses keys to store value in
the object.

2. Which of these method is used to insert value and its key?


a) put()
b) set()
c) insertElement()
d) addElement()
View Answer

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.

6. What is the output of this program?

1. import java.util.*;

2. class hashtable

3. {

4. public static void main(String args[])

5. {

6. Hashtable obj = new Hashtable();

7. obj.put("A", new Integer(3));

8. obj.put("B", new Integer(2));

9. obj.put("C", new Integer(8));

10. System.out.print(obj.contains(new Integer(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

7. What is the output of this program?

1. import java.util.*;

2. class hashtable

3. {

4. public static void main(String args[])

5. {

6. Hashtable obj = new Hashtable();

7. obj.put("A", new Integer(3));

8. obj.put("B", new Integer(2));

9. obj.put("C", new Integer(8));

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

8. What is the output of this program?

1. import java.util.*;

2. class hashtable

3. {

4. public static void main(String args[])

5. {

6. Hashtable obj = new Hashtable();


7. obj.put("A", new Integer(3));

8. obj.put("B", new Integer(2));

9. obj.put("C", new Integer(8));

10. obj.remove(new String("A"));

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}

9. What is the output of this program?

1. import java.util.*;

2. class hashtable

3. {

4. public static void main(String args[])

5. {

6. Hashtable obj = new Hashtable();

7. obj.put("A", new Integer(3));

8. obj.put("B", new Integer(2));

9. obj.put("C", new Integer(8));

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}

10. What is the output of this program?

1. import java.util.*;

2. class properties

3. {

4. public static void main(String args[])

5. {

6. Properties obj = new Properties();

7. obj.put("AB", new Integer(3));

8. obj.put("BC", new Integer(2));

9. obj.put("CD", new Integer(8));

10. System.out.print(obj.keySet());

11. }

12. }

a) {AB, BC, CD}


b) [AB, BC, CD].
c) [3, 2, 8].
d) {3, 2, 8}
View Answer

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].

Java Questions & Answers – Java.util – BitSet & Date class

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. {

4. public static void main(String args[])

5. {

6. BitSet obj = new BitSet(5);

7. for (int i = 0; i < 5; ++i)

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}

7. What is the output of this program?

1. import java.util.*;

2. class Bitset

3. {

4. public static void main(String args[])

5. {

6. BitSet obj = new BitSet(5);

7. for (int i = 0; i < 5; ++i)

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

8. What is the output of this program?

1. import java.util.*;

2. class Bitset

3. {

4. public static void main(String args[])

5. {

6. BitSet obj = new BitSet(5);

7. for (int i = 0; i < 5; ++i)

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

9. What is the output of this program?

1. import java.util.*;

2. class date

3. {

4. public static void main(String args[])

5. {

6. Date obj = new Date();

7. System.out.print(obj);

8. }

9. }

a) Prints Present Date


b) Runtime Error
c) Any Garbage Value
d) Prints Present Time & Date
View Answer

Answer: d
Explanation: None.
Output:
$ javac date.java
$ java date
Tue Jun 11 11:29:57 PDT 2013

10. What is the output of this program?

1. import java.util.*;

2. class Bitset

3. {

4. public static void main(String args[])

5. {

6. BitSet obj1 = new BitSet(5);

7. BitSet obj2 = new BitSet(10);

8. for (int i = 0; i < 5; ++i)

9. obj1.set(i);

10. for (int i = 3; i < 13; ++i)


11. obj2.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}

Java Questions & Answers – Collection Framework Overview

This section of our 1000+ Java MCQs focuses on collection framework of Java Programming Language.

1. Which of these packages contain all the collection classes?


a) java.lang
b) java.util
c) java.net
d) java.awt
View Answer

Answer: b
Explanation: None.

2. Which of these classes is not part of Java’s collection framework?


a) Maps
b) Array
c) Stack
d) Queue
View Answer

Answer: a
Explanation: Maps is not a part of collection framework.

3. Which of these interface is not a part of Java’s collection framework?


a) List
b) Set
c) SortedMap
d) SortedList
View Answer
Answer: d
Explanation: SortedList 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.

5. What is Collection in Java?


a) A group of objects
b) A group of classes
c) A group of interfaces
d) None of the mentioned
View Answer

Answer: a
Explanation: A collection is a group of objects, it is similar to String Template Library (STL) of C++ programming
language.

6. What is the output of this program?

1. import java.util.*;

2. class Array

3. {

4. public static void main(String args[])

5. {

6. int array[] = new int [5];

7. for (int i = 5; i > 0; i--)

8. array[5-i] = i;

9. Arrays.fill(array, 1, 4, 8);

10. for (int i = 0; i < 5 ; i++)

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

7. What is the output of this program?

1. import java.util.*;

2. class vector

3. {

4. public static void main(String args[])

5. {

6. Vector obj = new Vector(4,2);

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

8. What is the output of this program?

1. import java.util.*;
2. class stack

3. {

4. public static void main(String args[])

5. {

6. Stack obj = new Stack();

7. obj.push(new Integer(3));

8. obj.push(new Integer(2));

9. obj.pop();

10. obj.push(new Integer(5));

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].

9. What is the output of this program?

1. import java.util.*;

2. class hashtable

3. {

4. public static void main(String args[])

5. {

6. Hashtable obj = new Hashtable();

7. obj.put("A", new Integer(3));

8. obj.put("B", new Integer(2));

9. obj.put("C", new Integer(8));


10. obj.remove(new String("A"));

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}

10. What is the output of this program?

1. import java.util.*;

2. class Bitset

3. {

4. public static void main(String args[])

5. {

6. BitSet obj = new BitSet(5);

7. for (int i = 0; i < 5; ++i)

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}

Java Questions & Answers – Iterators

This section of our 1000+ Java MCQs focuses on iterators of Java Programming Language.

1. Which of these return type of hasNext() method of an iterator?


a) Integer
b) Double
c) Boolean
d) Collections Object
View Answer

Answer: c
Explanation: hasNext() returns boolean values true or false.

2. Which of these methods is used to obtain an iterator to the start of collection?


a) start()
b) begin()
c) iteratorSet()
d) iterator()
View Answer

Answer: d
Explanation: To obtain an iterator to the start of the start of the collection we use iterator() method.

3. Which of these methods can be used to move to next element in a collection?


a) next()
b) move()
c) shuffle()
d) hasNext()
View Answer

Answer: a
Explanation: None.

4. Which of these iterators can be used only with List?


a) Setiterator
b) ListIterator
c) Literator
d) None of the mentioned
View Answer

Answer: b
Explanation: None.

5. Which of these is a method of ListIterator used to obtain index of previous element?


a) previous()
b) previousIndex()
c) back()
d) goBack()
View Answer
Answer: b
Explanation: previousIndex() returns index of previous element. if there is no previous element then -1 is returned.

6. Which of these exceptions is thrown by remover() method?


a) IOException
b) SystemException
c) ObjectNotFoundExeception
d) IllegalStateException
View Answer

Answer: d
Explanation: None.

7. What is the output of this program?

1. import java.util.*;

2. class Collection_iterators

3. {

4. public static void main(String args[])

5. {

6. ListIterator a = list.listIterator();

7. if(a.previousIndex()! = -1)

8. while(a.hasNext())

9. System.out.print(a.next() + " ");

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

8. What is the output of this program?

1. import java.util.*;
2. class Collection_iterators

3. {

4. public static void main(String args[])

5. {

6. LinkedList list = new LinkedList();

7. list.add(new Integer(2));

8. list.add(new Integer(8));

9. list.add(new Integer(5));

10. list.add(new Integer(1));

11. Iterator i = list.iterator();

12. Collections.reverse(list);

13. while(i.hasNext())

14. System.out.print(i.next() + " ");

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

9. What is the output of this program?

1. import java.util.*;

2. class Collection_iterators

3. {

4. public static void main(String args[])

5. {

6. LinkedList list = new LinkedList();


7. list.add(new Integer(2));

8. list.add(new Integer(8));

9. list.add(new Integer(5));

10. list.add(new Integer(1));

11. Iterator i = list.iterator();

12. Collections.reverse(list);

13. Collections.sort(list);

14. while(i.hasNext())

15. System.out.print(i.next() + " ");

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

10. What is the output of this program?

1. import java.util.*;

2. class Collection_iterators

3. {

4. public static void main(String args[])

5. {

6. LinkedList list = new LinkedList();

7. list.add(new Integer(2));

8. list.add(new Integer(8));

9. list.add(new Integer(5));

10. list.add(new Integer(1));

11. Iterator i = list.iterator();


12. Collections.reverse(list);

13. Collections.shuffle(list);

14. i.next();

15. i.remove();

16. while(i.hasNext())

17. System.out.print(i.next() + " ");

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)

Java Questions & Answers – Data Structures-Queue

This set of Java Multiple Choice Questions & Answers focuses on “Data Structures-Queue”.

1. Which of the below is not a subinterface of Queue?


a) BlockingQueue
b) BlockingEnque
c) TransferQueue
d) BlockingQueue
View Answer

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.

4. What is difference between dequeue() and peek() function of java?


a) dequeue() and peek() remove and return the next time in line
b) dequeue() and peek() return the next item in line
c) dequeue() removes and returns the next item in line while peek() returns the next item in line
d) peek() removes and returns the next item in line while dequeue() returns the next item in line
View Answer

Answer: c
Explanation: dequeue() removes the item next in line. peek() returns the item without removing it from the queue.

5. What is the difference between Queue and Stack?


a) Stack is LIFO; Queue is FIFO
b) Queue is LIFO; Stack is FIFO
c) Stack and Queue is FIFO
d) Stack and Queue is LIFO
View Answer

Answer: a
Explanation: Stack is Last in First out (LIFO) and Queue is First in First out(FIFO).

6. What is the use of front and rear pointers in CircularQueue implementation?


a) Front pointer points to first element; rear pointer points to the last element
b) Rear pointer points to first element; front pointer points to the last element
c) Front and read pointers point to the first element
d) Front pointer points to the first element; rear pointer points to null object
View Answer

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.

8. Which data structure is used in Breadth First Traversal of a graph?


a) Stack
b) Queue
c) Array
d) Tree
View Answer

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).

9. Where does a new element be inserted in linked list implementation of a queue?


a) Head of list
b) Tail of list
c) At the centre of list
d) All the old entries are pushed and then the new element is inserted
View Answer

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.

Java Questions & Answers – Java.util – Array Class

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.

2. Which of these classes implements Set interface?


a) ArrayList
b) HashSet
c) LinkedList
d) DynamicList
View Answer

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.

5. Which of these methods can be used to search an element in a list?


a) find()
b) sort()
c) get()
d) binaryserach()
View Answer

Answer: d
Explanation: binaryserach() method uses binary search to find a specified value. This method must be applied to
sorted arrays.

6. Which of these method is used to change an element in a LinkedList Object?


a) change()
b) set()
c) redo()
d) add()
View Answer

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.

7. What is the output of this program?

1. import java.util.*;
2. class Arraylist

3. {

4. public static void main(String args[])

5. {

6. ArrayList obj1 = new ArrayList();

7. ArrayList obj2 = new ArrayList();

8. obj1.add("A");

9. obj1.add("B");

10. obj2.add("A");

11. obj2.add(1, "B");

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

8. What is the output of this program?

1. import java.util.*;

2. class Array

3. {

4. public static void main(String args[])

5. {

6. int array[] = new int [5];

7. for (int i = 5; i > 0; i--)

8. array[5 - i] = i;
9. Arrays.sort(array);

10. for (int i = 0; i < 5; ++i)

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 Array

3. {

4. public static void main(String args[])

5. {

6. int array[] = new int [5];

7. for (int i = 5; i > 0; i--)

8. array[5-i] = i;

9. Arrays.fill(array, 1, 4, 8);

10. for (int i = 0; i < 5 ; i++)

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

10. What is the output of this program?

1. import java.util.*;

2. class Array

3. {

4. public static void main(String args[])

5. {

6. int array[] = new int [5];

7. for (int i = 5; i > 0; i--)

8. array[5 - i] = i;

9. Arrays.sort(array);

10. System.out.print(Arrays.binarySearch(array, 4));

11. }

12. }

a) 2
b) 3
c) 4
d) 5
View Answer

Answer: b
Explanation: None.
Output:
$ javac Array.java
$ java Array
3

Java Questions & Answers – Collections Interface

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.

2. Which of these interface handle sequences?


a) Set
b) List
c) Comparator
d) Collection
View Answer

Answer: b
Explanation: None.

3. Which of these interface is not a part of Java’s collection framework?


a) List
b) Set
c) SortedMap
d) SortedList
View Answer

Answer: d
Explanation: SortedList is not a part of collection framework.

4. Which of these interface must contain a unique element?


a) Set
b) List
c) Array
d) Collection
View Answer

Answer: a
Explanation: Set interface extends collection interface to handle sets, which must contain unique elements.

5. Which of these is Basic interface that all other interface inherits?


a) Set
b) Array
c) List
d) Collection
View Answer

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

6. What is the output of this program?

1. import java.util.*;

2. class Maps

3. {
4. public static void main(String args[])

5. {

6. TreeMap obj = new TreeMap();

7. obj.put("A", new Integer(1));

8. obj.put("B", new Integer(2));

9. obj.put("C", new Integer(3));

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].

7. What is the output of this program?

1. import java.util.*;

2. class vector

3. {

4. public static void main(String args[])

5. {

6. Vector obj = new Vector(4,2);

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

8. What is the output of this program?

1. import java.util.*;

2. class Array

3. {

4. public static void main(String args[])

5. {

6. int array[] = new int [5];

7. for (int i = 5; i > 0; i--)

8. array[5 - i] = i;

9. Arrays.sort(array);

10. for (int i = 0; i < 5; ++i)

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. {

4. public static void main(String args[])

5. {

6. Vector obj = new Vector(4,2);

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

10. What is the output of this program?

1. import java.util.*;

2. class Bitset

3. {

4. public static void main(String args[])

5. {

6. BitSet obj = new BitSet(5);

7. for (int i = 0; i < 5; ++i)


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}

Java Questions & Answers – Collection Algorithms

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.

2. Which of these methods sets every element of a List to a specified object?


a) set()
b) fill()
c) Complete()
d) add()
View Answer

Answer: b
Explanation: None.

3. Which of these methods can randomize all elements in a list?


a) rand()
b) randomize()
c) shuffle()
d) ambigous()
View Answer
Answer: c
Explanation: shuffle – randomizes all the elements in a list.

4. Which of these methods can convert an object into a List?


a) SetList()
b) ConvertList()
c) singletonList()
d) CopyList()
View Answer

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.

5. Which of these is true about unmodifiableCollection() method?


a) unmodifiableCollection() returns a collection that cannot be modified
b) unmodifiableCollection() method is available only for List and Set
c) unmodifiableCollection() is defined in Collection class
d) none of the mentioned
View Answer

Answer: b
Explanation: unmodifiableCollection() is available for al collections, Set, Map, List etc.

6. Which of these is static variable defined in Collections?


a) EMPTY_SET
b) EMPTY_LIST
c) EMPTY_MAP
d) All of the mentioned
View Answer

Answer: d
Explanation: None.

7. What is the output of this program?

1. import java.util.*;

2. class Collection_Algos

3. {

4. public static void main(String args[])

5. {

6. LinkedList list = new LinkedList();

7. list.add(new Integer(2));

8. list.add(new Integer(8));

9. list.add(new Integer(5));

10. list.add(new Integer(1));


11. Iterator i = list.iterator();

12. while(i.hasNext())

13. System.out.print(i.next() + " ");

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

8. What is the output of this program?

1. import java.util.*;

2. class Collection_Algos

3. {

4. public static void main(String args[])

5. {

6. LinkedList list = new LinkedList();

7. list.add(new Integer(2));

8. list.add(new Integer(8));

9. list.add(new Integer(5));

10. list.add(new Integer(1));

11. Iterator i = list.iterator();

12. Collections.reverse(list);

13. while(i.hasNext())

14. System.out.print(i.next() + " ");

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

9. What is the output of this program?

1. import java.util.*;

2. class Collection_Algos

3. {

4. public static void main(String args[])

5. {

6. LinkedList list = new LinkedList();

7. list.add(new Integer(2));

8. list.add(new Integer(8));

9. list.add(new Integer(5));

10. list.add(new Integer(1));

11. Iterator i = list.iterator();

12. Collections.reverse(list);

13. Collections.sort(list);

14. while(i.hasNext())

15. System.out.print(i.next() + " ");

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

10. What is the output of this program?

1. import java.util.*;

2. class Collection_Algos

3. {

4. public static void main(String args[])

5. {

6. LinkedList list = new LinkedList();

7. list.add(new Integer(2));

8. list.add(new Integer(8));

9. list.add(new Integer(5));

10. list.add(new Integer(1));

11. Iterator i = list.iterator();

12. Collections.reverse(list);

13. Collections.shuffle(list);

14. while(i.hasNext())

15. System.out.print(i.next() + " ");

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.

1. When does Exceptions in Java arises in code sequence?


a) Run Time
b) Compilation Time
c) Can Occur Any Time
d) None of the mentioned
View Answer

Answer: a
Explanation: Exceptions in java are run-time errors.

2. Which of these keywords is not a part of exception handling?


a) try
b) finally
c) thrown
d) catch
View Answer

Answer: c
Explanation: Exceptional handling is managed via 5 keywords – try, catch, throws, throw and finally.

3. Which of these keywords must be used to monitor for exceptions?


a) try
b) finally
c) throw
d) catch
View Answer

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.

5. Which of these keywords is used to manually throw an exception?


a) try
b) finally
c) throw
d) catch
View Answer

Answer: c
Explanation: None.
6. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. System.out.print("Hello" + " " + 1 / 0);

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

7. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

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

8. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

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

9. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. int i, sum;

8. sum = 10;

9. for (i = -1; i < 3 ;++i)

10. sum = (sum / i);

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

10. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. int i, sum;

8. sum = 10;

9. for (i = -1; i < 3 ;++i)

10. {

11. sum = (sum / i);

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

Java Questions & Answers – Exception Handling

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

1. Which of the following keywords is used for throwing exception manually?


a) finally
b) try
c) throw
d) catch
View Answer

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.

3. Which of the following is a super class of all exception type classes?


a) Catchable
b) RuntimeExceptions
c) String
d) Throwable
View Answer
Answer: d
Explanation: Throwable is built in class and all exception types are subclass of this class.It is the super class of all
exceptions.

4. Which of the following operators is used to generate instance of an exception which can be thrown using throw?
a) thrown
b) alloc
c) malloc
d) new
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.

7. Which part of code gets executed whether exception is caught or not?


a) finally
b) try
c) catch
d) throw
View Answer

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.

9. What exception thrown by parseInt() method?


a) ArithmeticException
b) ClassNotFoundException
c) NullPointerException
d) NumberFormatException
View Answer

Answer: d
Explanation: parseInt() method parses input into integer. The exception thrown by this method is
NumberFormatException.

10. At run time, error is recoverable.


a) True
b) False
View Answer

Answer: b
Explanation: Error is not recoverable at run time. The control is lost from the application.

Java Questions & Answers – Exceptions Types

This section of our 1000+ Java MCQs focuses on Exceptions types in Java Programming Language.

1. Which of these is a super class of all exceptional type classes?


a) String
b) RuntimeExceptions
c) Throwable
d) Cachable
View Answer

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.

4. Which of these handles the exception when no catch is used?


a) Default handler
b) finally
c) throw handler
d) Java run time system
View Answer

Answer: a
Explanation: None.

5. Which of these keywords is used to manually throw an exception?


a) try
b) finally
c) throw
d) catch
View Answer

Answer: c
Explanation: None.

6. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. System.out.print("Hello" + " " + 1 / 0);

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

7. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

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

8. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. int a[] = {1, 2,3 , 4, 5};

8. for (int i = 0; i < 7; ++i)

9. System.out.print(a[i]);

10. }

11. catch(ArrayIndexOutOfBoundsException e)

12. {

13. System.out.print("0");

14. }

15. }

16. }

a) 12345
b) 123450
c) 1234500
d) Compilation Error
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

9. What is the output of this program?


1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. int i, sum;

8. sum = 10;

9. for (i = -1; i < 3 ;++i)

10. sum = (sum / i);

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

10. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])


4. {

5. try

6. {

7. int a[] = {1, 2,3 , 4, 5};

8. for (int i = 0; i < 5; ++i)

9. System.out.print(a[i]);

10. int x = 1/0;

11. }

12. catch(ArrayIndexOutOfBoundsException e)

13. {

14. System.out.print("A");

15. }

16. catch(ArithmeticException e)

17. {

18. System.out.print("B");

19. }

20. }

21. }

a) 12345
b) 12345A
c) 12345B
d) 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

Java Questions & Answers – Throw, Throws & Nested Try

This section of our 1000+ Java MCQs focuses on throw, throws & nested try of Java Programming Language.

1. Which of these keywords is used to generate an exception explicitly?


a) try
b) finally
c) throw
d) catch
View Answer

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.

4. Which of these handles the exception when no catch is used?


a) Default handler
b) finally
c) throw handler
d) Java run time system
View Answer

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.

6. What is the output of this program?


1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. int a = args.length;

8. int b = 10 / a;

9. System.out.print(a);

10. try

11. {

12. if (a == 1)

13. a = a / a - a;

14. if (a == 2)

15. {

16. int []c = {1};

17. c[8] = 9;

18. }

19. }

20. catch (ArrayIndexOutOfBoundException e)

21. {

22. System.out.println("TypeA");

23. }

24. catch (ArithmeticException e)

25. {

26. System.out.println("TypeB");

27. }

28. }

29. }

30. }
a) TypeA
b) TypeB
c) Compiler Time Error
d) 0TypeB
View Answer

Answer: c
Explanation: Because we can’t go beyond array limit

7. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. System.out.print("A");

8. throw new NullPointerException ("Hello");

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

8. What is the output of this program?


1. class exception_handling

2. {

3. static void throwexception() throws ArithmeticException

4. {

5. System.out.print("0");

6. throw new ArithmeticException ("Exception");

7. }

8. public static void main(String args[])

9. {

10. try

11. {

12. throwexception();

13. }

14. catch (ArithmeticException e)

15. {

16. System.out.println("A");

17. }

18. }

19. }

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

Answer: c
Explanation: None.
Output:
$ javac exception_handling.java
$ java exception_handling
0A

9. What is the output of this program?

1. public class San

2. {

3. public static void main(String[] args)


4. {

5. try

6. {

7. return;

8. }

9. finally

10. {

11. System.out.println( "Finally" );

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.

10. What is the output of this program?

1. public class San

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. System.out.print("Hello world ");

8. }

9. finally

10. {

11. System.out.println("Finally executing ");

12. }

13. }
14. }

a) The program will not compile because no exceptions are specified


b) The program will not compile because no catch clauses are specified
c) Hello world
d) Hello world Finally executing
View Answer

Answer: d
Explanation: None

Java Questions & Answers – Finally & Built in Exceptions

This section of our 1000+ Java MCQs focuses on keyword finally and built in exceptions of Java Programming
Language.

1. Which of these clause will be executed even if no exceptions are found?


a) throws
b) finally
c) throw
d) catch
View Answer

Answer: b
Explanation: finally keyword is used to define a set of instructions that will be executed irrespective of the exception
found or not.

2. A single try block must be followed by which of these?


a) finally
b) catch
c) finally & catch
d) none of the mentioned
View Answer

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.

3. Which of these packages contain all the Java’s built in exceptions?


a) java.io
b) java.util
c) java.lang
d) java.net
View Answer

Answer: c
Explanation: None.

4. Which of these exceptions handles the divide by zero error?


a) ArithmeticException
b) MathException
c) IllegalAccessException
d) IllegarException
View Answer

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.

6. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. int a = args.length;

8. int b = 10 / a;

9. System.out.print(a);

10. }

11. catch (ArithmeticException e)

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

7. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. throw new NullPointerException ("Hello");

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

8. What is the output of this program?

1. class exception_handling

2. {
3. static void throwexception() throws ArithmeticException

4. {

5. System.out.print("0");

6. throw new ArithmeticException ("Exception");

7. }

8. public static void main(String args[])

9. {

10. try

11. {

12. throwexception();

13. }

14. catch (ArithmeticException e)

15. {

16. System.out.println("A");

17. }

18. }

19. }

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

Answer: c
Explanation: None.
Output:
$ javac exception_handling.java
$ java exception_handling
0A

9. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try
6. {

7. int a = 1;

8. int b = 10 / a;

9. try

10. {

11. if (a == 1)

12. a = a / a - a;

13. if (a == 2)

14. {

15. int c[] = {1};

16. c[8] = 9;

17. }

18. }

19. finally

20. {

21. System.out.print("A");

22. }

23. }

24. catch (Exception e)

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

10. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. int a = args.length;

8. int b = 10 / a;

9. System.out.print(a);

10. try

11. {

12. if (a == 1)

13. a = a / a - a;

14. if (a == 2)

15. {

16. int []c = {1};

17. c[8] = 9;

18. }

19. }

20. catch (ArrayIndexOutOfBoundException e)

21. {

22. System.out.println("TypeA");

23. }

24. catch (ArithmeticException e)

25. {

26. System.out.println("TypeB");
27. }

28. }

29. }

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

Java Questions & Answers – Try & Catch

This section of our 1000+ Java MCQs focuses on try and catch in Java Programming Language.

1. What is the use of try & catch?


a) It allows us to manually handle the exception
b) It allows to fix errors
c) It prevents automatic terminating of the program in cases when an exception occurs
d) All of the mentioned
View Answer

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.

5. Which of these statements is incorrect?


a) try block need not to be followed by catch block
b) try block can be followed by finally block instead of catch block
c) try can be followed by both catch and finally block
d) try need not to be followed by anything
View Answer

Answer: d
Explanation: try must be followed by either catch or finally block.

6. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

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

7. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

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

8. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

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

9. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

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

10. What is the output of this program?

1. class Output

2. {

3. public static void main(String args[])

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

Java Questions & Answers – Creating Exceptions

This section of our 1000+ Java MCQs focuses on creating exceptions in Java Programming Language.

1. Which of these classes is used to define exceptions?


a) Exception
b) Trowable
c) Abstract
d) System
View Answer

Answer: a
Explanation: None.

2. Which of these methods return description of an exception?


a) getException()
b) getMessage()
c) obtainDescription()
d) obtainException()
View Answer

Answer: b
Explanation: getMessage() returns a description of the exception.

3. Which of these methods is used to print stack trace?


a) obtainStackTrace()
b) printStackTrace()
c) getStackTrace()
d) displayStackTrace()
View Answer

Answer: b
Explanation: None.

4. Which of these methods return localized description of an exception?


a) getLocalizedMessage()
b) getMessage()
c) obtainLocalizedMessage()
d) printLocalizedMessage()
View Answer

Answer: a
Explanation: None.

5. Which of these classes is super class of Exception class?


a) Throwable
b) System
c) RunTime
d) Class
View Answer

Answer: a
Explanation: None.

6. What is the output of this program?

1. class Myexception extends Exception

2. {

3. int detail;

4. Myexception(int a)

5. {

6. detail = a;

7. }

8. public String toString()

9. {
10. return "detail";

11. }

12. }

13. class Output

14. {

15. static void compute (int a) throws Myexception

16. {

17. throw new Myexception(a);

18. }

19. public static void main(String args[])

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

7. What is the output of this program?

1. class Myexception extends Exception


2. {

3. int detail;

4. Myexception(int a)

5. {

6. detail = a;

7. }

8. public String toString()

9. {

10. return "detail";

11. }

12. }

13. class Output

14. {

15. static void compute (int a) throws Myexception

16. {

17. throw new Myexception(a);

18. }

19. public static void main(String args[])

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

8. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. throw new NullPointerException ("Hello");

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

9. What is the output of this program?


1. class Myexception extends Exception

2. {

3. int detail;

4. Myexception(int a)

5. {

6. detail = a;

7. }

8. public String toString()

9. {

10. return "detail";

11. }

12. }

13. class Output

14. {

15. static void compute (int a) throws Myexception

16. {

17. throw new Myexception(a);

18. }

19. public static void main(String args[])

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

10. What is the output of this program?

1. class exception_handling

2. {

3. public static void main(String args[])

4. {

5. try

6. {

7. int a = args.length;

8. int b = 10 / a;

9. System.out.print(a);

10. try

11. {

12. if (a == 1)

13. a = a / a - a;

14. if (a == 2)

15. {

16. int c = {1};

17. c[8] = 9;

18. }

19. }

20. catch (ArrayIndexOutOfBoundException e)

21. {

22. System.out.println("TypeA");
23. }

24. catch (ArithmeticException e)

25. {

26. System.out.println("TypeB");

27. }

28. }

29. }

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

Java Questions & Answers – isAlive(), Join() & Thread Synchronization

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.

4. Which of these method waits for the thread to treminate?


a) sleep()
b) isAlive()
c) join()
d) stop()
View Answer

Answer: c
Explanation: None.

5. Which of these method is used to explicitly set the priority of a thread?


a) set()
b) make()
c) setPriority()
d) makePriority()
View Answer

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().

6. What is synchronization in reference to a thread?


a) It’s a process of handling situations when two or more threads need access to a shared resource
b) Its a process by which many thread are able to access same shared resource simultaneously
c) Its a process by which a method is able to access many different threads simultaneously
d) Its a method that allow to many threads to access any information require
View Answer

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

7. What is the output of this program?

1. class newthread extends Thread

2. {

3. newthread()

4. {

5. super("My Thread");
6. start();

7. }

8. public void run()

9. {

10. System.out.println(this);

11. }

12. }

13. class multithreaded_programing

14. {

15. public static void main(String args[])

16. {

17. new newthread();

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].

8. What is the output of this program?

1. class newthread extends Thread

2. {

3. Thread t;

4. newthread()

5. {

6. t = new Thread(this,"My Thread");

7. t.start();
8. }

9. public void run()

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. }

22. class multithreaded_programing

23. {

24. public static void main(String args[])

25. {

26. new newthread();

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

9. What is the output of this program?


1. class newthread extends Thread

2. {

3. Thread t;

4. newthread()

5. {

6. t = new Thread(this,"New Thread");

7. t.start();

8. }

9. public void run()

10. {

11. System.out.println(t.isAlive());

12. }

13. }

14. class multithreaded_programing

15. {

16. public static void main(String args[])

17. {

18. new newthread();

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

10. What is the output of this program?

1. class newthread extends Thread


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. }

11. public void run()

12. {

13. t2.setPriority(Thread.MAX_PRIORITY);

14. System.out.print(t1.equals(t2));

15. }

16. }

17. class multithreaded_programing

18. {

19. public static void main(String args[])

20. {

21. new newthread();

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”.

1. Which of these method is used to implement Runnable interface?


a) stop()
b) run()
c) runThread()
d) stopThread()
View Answer

Answer: b
Explanation: To implement Runnable interface, a class needs only to implement a single method called run().

2. Which of these interface is implemented by Thread class?


a) Runnable
b) Connections
c) Set
d) MapConnections
View Answer

Answer: a
Explanation: None.

3. Which of these method is used to begin the execution of a thread?


a) run()
b) start()
c) runThread()
d) startThread()
View Answer

Answer: b
Explanation: None.

4. Which of these method waits for the thread to treminate?


a) sleep()
b) isAlive()
c) join()
d) stop()
View Answer

Answer: c
Explanation: None.

5. Which of these statement is incorrect?


a) A thread can be formed by implementing Runnable interface only
b) A thread can be formed by a class that extends Thread class
c) start() method is used to begin execution of the thread
d) run() method is used to begin execution of a thread before start() method in special cases
View Answer

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.

6. What is the output of this program?

1. class newthread implements Runnable

2. {

3. Thread t;

4. newthread()

5. {

6. t = new Thread(this,"My Thread");

7. t.start();

8. }

9. public void run()

10. {

11. System.out.println(t.getName());

12. }

13. }

14. class multithreaded_programing

15. {

16. public static void main(String args[])

17. {

18. new newthread();

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?

1. class newthread implements Runnable

2. {

3. Thread t;

4. newthread()

5. {

6. t = new Thread(this,"My Thread");

7. t.start();

8. }

9. public void run()

10. {

11. System.out.println(t);

12. }

13. }

14. class multithreaded_programing

15. {

16. public static void main(String args[])

17. {

18. new newthread();

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]

8. What is the output of this program?

1. class newthread implements Runnable


2. {

3. Thread t;

4. newthread()

5. {

6. t = new Thread(this,"My Thread");

7. t.start();

8. }

9. }

10. class multithreaded_programing

11. {

12. public static void main(String args[])

13. {

14. new newthread();

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()

9. What is the output of this program?

1. class newthread implements Runnable

2. {

3. Thread t;

4. newthread()

5. {

6. t = new Thread(this,"New Thread");


7. t.start();

8. }

9. public void run()

10. {

11. t.setPriority(Thread.MAX_PRIORITY);

12. System.out.println(t);

13. }

14. }

15. class multithreaded_programing

16. {

17. public static void main(String args[])

18. {

19. new newthread();

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]

10. What is the output of this program?

1. class newthread implements Runnable

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. }

11. public void run()

12. {

13. t2.setPriority(Thread.MAX_PRIORITY);

14. System.out.print(t1.equals(t2));

15. }

16. }

17. class multithreaded_programing

18. {

19. public static void main(String args[])

20. {

21. new newthread();

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

Java Questions & Answers – Thread class

This section of our 1000+ Java MCQs focuses on Thread class of Java Programming Language.

1. Which of these class is used to make a thread?


a) String
b) System
c) Thread
d) Runnable
View Answer

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.

2. Which of these interface is implemented by Thread class?


a) Runnable
b) Connections
c) Set
d) MapConnections
View Answer

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.

6. What is the output of this program?

1. class multithreaded_programing
2. {

3. public static void main(String args[])

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]

7. What is the priority of the thread in output of this program?

1. class multithreaded_programing

2. {

3. public static void main(String args[])

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

8. What is the name of the thread in output of this program?

1. class multithreaded_programing

2. {

3. public static void main(String args[])

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

9. What is the name of the thread in output of this program?

1. class multithreaded_programing

2. {

3. public static void main(String args[])

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

Java Questions & Answers – Multithreading Basics

This section of our 1000+ Java MCQs focuses on Basics of multithreading of Java Programming Language.

1. What is multithreaded programming?


a) It’s a process in which two different processes run simultaneously
b) It’s a process in which two or more parts of same process run simultaneously
c) Its a process in which many different process are able to access same information
d) Its a process in which a single process can access information from many sources
View Answer

Answer: b
Explanation: Multithreaded programming a process in which two or more parts of same process run simultaneously.

2. Which of these are types of multitasking?


a) Process based
b) Thread based
c) Process and Thread based
d) None of the mentioned
View Answer

Answer: c
Explanation: There are two types of multitasking: Process based multitasking and Thread based multitasking.

3. Which of these packages contain all the Java’s built in exceptions?


a) java.io
b) java.util
c) java.lang
d) java.net
View Answer

Answer: c
Explanation: None.

4. Thread priority in Java is?


a) Integer
b) Float
c) double
d) long
View Answer
Answer: a
Explanation: Java assigns to each thread a priority that determines hoe that thread should be treated with respect to
others. Thread priority are integers that specify relative priority of one thread to another.

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.

6. Which of these statements is incorrect?


a) By multithreading CPU’s idle time is minimized, and we can take maximum use of it
b) By multitasking CPU’s idle time is minimized, and we can take maximum use of it
c) Two thread in Java can have same priority
d) A thread can exist only in two states, running and blocked
View Answer

Answer: d
Explanation: Thread exist in several states, a thread can be running, suspended, blocked, terminated & ready to run.

7. What is the output of this program?

1. class multithreaded_programing

2. {

3. public static void main(String args[])

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]

8. What is the priority of the thread in output of this program?

1. class multithreaded_programing

2. {

3. public static void main(String args[])

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]

9. What is the name of the thread in output of this program?

1. class multithreaded_programing

2. {

3. public static void main(String args[])

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]

10. What is the name of the thread in output of this program?

1. class multithreaded_programing

2. {

3. public static void main(String args[])

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

Java Questions & Answers – Multithreading

This set of Java Quiz focuses on “Multithreading”.

1. What requires less resources?


a) Thread
b) Process
c) Thread and Process
d) Neither Thread nor Process
View Answer
Answer: a
Explanation: Thread is a lightweight and requires less resources to create and exist in the process. Thread shares the
process resources.

2. What does not prevent JVM from terminating?


a) Process
b) Daemon Thread
c) User Thread
d) JVM Thread
View Answer

Answer: b
Explanation: Daemon thread runs in the background and does not prevent JVM from terminating. Child of daemon
thread is also daemon thread.

3. What decides thread priority?


a) Process
b) Process schdduler
c) Thread
d) Thread scheduler
View Answer

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.

4. What is true about time slicing?


a) Time slicing is OS service that allocates CPU time to available runnable thread
b) Time slicing is the process to divide the available CPU time to available runnable thread
c) Time slicing depends on its implementation in OS
d) Time slicing allocates more resources to thread
View Answer

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.

6. What should not be done to avoid deadlock?


a) Avoid using multiple threads
b) Avoid hold several locks at once
c) Execute foreign code while holding a lock
d) Use interruptible locks
View Answer

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.

8. Which of the following is correct constructor for thread?


a) Thread(Runnable a, String str)
b) Thread(int priority)
c) Thread(Runnable a, int priority)
d) Thread(Runnable a, ThreadGroup t)
View Answer

Answer: a
Explanation: Thread(Runnable a, String str) is a valid constructor for thread. Thread() is also a valid constructor.

9. Which of the following stops execution of a thread?


a) Calling SetPriority() method on a Thread object
b) Calling notify() method on an object
c) Calling wait() method on an object
d) Calling read() method on an InputStream object
View Answer

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.

Java Questions & Answers – Creating Threads

This section of our 1000+ Java MCQs focuses on creating threads in Java Programming Language.

1. Which of these keywords are used to implement synchronization?


a) sunchronize
b) syn
c) synch
d) synchronized
View Answer
Answer: d
Explanation: None.

2. Which of these method is used to avoid polling in Java?


a) wait()
b) notify()
c) notifyAll()
d) all of the mentioned
View Answer

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.

5. Which of these method wakes up all the threads?


a) wakeAll()
b) notify()
c) start()
d) notifyAll()
View Answer

Answer: d
Explanation: notifyAll() wakes up all the threads that called wait() on the same object. The highest priority thread will
run first.

6. What is synchronization in reference to a thread?


a) Its a process of handling situations when two or more threads need access to a shared resource
b) Its a process by which many thread are able to access same shared resource simultaneously
c) Its a process by which a method is able to access many different threads simultaneously
d) Its a method that allow to many threads to access any information the require
View Answer

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

7. What is the output of this program?

1. class newthread extends Thread

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. }

11. public void run()

12. {

13. }

14.

15. }

16. class multithreaded_programing

17. {

18. public static void main(String args[])

19. {

20. newthread obj1 = new newthread("one");

21. newthread obj2 = new newthread("two");

22. try

23. {

24. obj1.t.wait();

25. System.out.print(obj1.t.isAlive());
26. }

27. catch(Exception e)

28. {

29. System.out.print("Main thread interrupted");

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

8. What is the output of this program?

1. class newthread extends Thread

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. }

11. public void run()

12. {

13. }

14.
15. }

16. class multithreaded_programing

17. {

18. public static void main(String args[])

19. {

20. newthread obj1 = new newthread("one");

21. newthread obj2 = new newthread("two");

22. try

23. {

24. Thread.sleep(1000);

25. System.out.print(obj1.t.isAlive());

26. }

27. catch(InterruptedException e)

28. {

29. System.out.print("Main thread interrupted");

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

9. What is the output of this program?

1. class newthread extends Thread

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. }

11. public void run()

12. {

13. }

14.

15. }

16. class multithreaded_programing

17. {

18. public static void main(String args[])

19. {

20. newthread obj1 = new newthread("one");

21. newthread obj2 = new newthread("two");

22. try

23. {

24. System.out.print(obj1.t.equals(obj2.t));

25. }

26. catch(Exception e)

27. {

28. System.out.print("Main thread interrupted");

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

10. What is the output of this program?

1. class newthread extends Thread

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. }

11. public void run()

12. {

13. t2.setPriority(Thread.MAX_PRIORITY);

14. System.out.print(t1.equals(t2));

15. }

16. }

17. class multithreaded_programing

18. {

19. public static void main(String args[])

20. {

21. new newthread();

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 – Input & Output Basics

This section of our 1000+ Java MCQs focuses on creating threads in Java Programming Language.

1. What does AWT stands for?


a) All Window Tools
b) All Writing Tools
c) Abstract Window Toolkit
d) Abstract Writing Toolkit
View Answer

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.

3. Which of these is a type of stream in Java?


a) Integer stream
b) Short stream
c) Byte stream
d) Long stream
View Answer

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.

6. Which of these class is used to read from byte array?


a) InputStream.
b) BufferedInputStream.
c) ArrayInputStream.
d) ByteArrayInputStream.
View Answer

Answer: d
Explanation: None.

7. What is the output of this program if input given is ‘abcqfghqbcd’?

1. class Input_Output

2. {

3. public static void main(String args[]) throws IOException

4. {

5. char c;

6. BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));

7. do

8. {

9. c = (char) obj.read();

10. System.out.print(c);

11. } while(c != 'q');

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

8. What is the output of this program if input given is “abc’def/’egh”?

1. class Input_Output

2. {

3. public static void main(String args[]) throws IOException

4. {

5. char c;

6. BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));

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’

9. What is the output of this program?

1. class output

2. {
3. public static void main(String args[])

4. {

5. StringBuffer c = new StringBuffer("Hello");

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

10. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. StringBuffer s1 = new StringBuffer("Hello");

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

Java Questions & Answers – Reading Console Input

This section of our 1000+ Java MCQs focuses on reading console inputs in Java Programming Language.

1. Which exception is thrown by read() method?


a) IOException
b) InterruptedException
c) SystemException
d) SystemInputException
View Answer

Answer: a
Explanation: read method throws IOException.

2. Which of these is used to read a string from the input stream?


a) get()
b) getLine()
c) read()
d) readLine()
View Answer

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.

5. Which of these class is implemented by FilterInputStream class?


a) InputStream
b) InputOutputStream
c) BufferedInputStream
d) SequenceInputStream
View Answer
Answer: a
Explanation: FileInputStream implements InputStream.

6. Which of these class is used to read from a file?


a) InputStream
b) BufferedInputStream
c) FileInputStream
d) BufferedFileInputStream
View Answer

Answer: c
Explanation: None.

7. What is the output of this program if input given is “Hello stop World”?

1. class Input_Output

2. {

3. public static void main(String args[]) throws IOException

4. {

5. string str;

6. BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));

7. do

8. {

9. str = (char) obj.readLine();

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

8. What is the output of this program?


1. class output

2. {

3. public static void main(String args[])

4. {

5. StringBuffer c = new StringBuffer("Hello");

6. StringBuffer c1 = new StringBuffer(" World");

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

9. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. StringBuffer s1 = new StringBuffer("Hello");

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

10. What is the output of this program if input given is “abc’def/’egh”?

1. class Input_Output

2. {

3. public static void main(String args[]) throws IOException

4. {

5. char c;

6. BufferedReader obj = new BufferedReader(new InputStreamReader(System.in));

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’

Java Questions & Answers – Writing Console Output

This section of our 1000+ Java MCQs focuses on writing console outputs in Java Programming Language.

1. Which of these class contains the methods print() & println()?


a) System
b) System.out
c) BUfferedOutputStream
d) PrintStream
View Answer

Answer: d
Explanation: print() and println() are defined under the class PrintStream, System.out is the byte stream used by
these methods .

2. Which of these methods can be used to writing console output?


a) print()
b) println()
c) write()
d) all of the mentioned
View Answer

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.

4. Which of these method of class StringBuffer is used to reverse sequence of characters?


a) reverse()
b) reverseall()
c) Reverse()
d) reverseAll()
View Answer

Answer: a
Explanation: reverse() method reverses all characters. It returns the reversed object on which it was called.

5. Which of these classes are used by character streams 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.

6. Which of the following statement is correct?


a) reverse() method reverses all characters
b) reverseall() method reverses all characters
c) replace() method replaces first occurrence of a character in invoking string with another character
d) replace() method replaces last occurrence of a character in invoking string with another character
View Answer

Answer: a
Explanation: reverse() method reverses all characters. It returns the reversed object on which it was called.

7. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. String a="hello i love java";

6. System.out.println(indexof('i')+" "+indexof('o')+" "+lastIndexof('i')+" "+lastIndexof('o') ));

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

8. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. StringBuffer s1 = new StringBuffer("Hello");

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

9. What is the output of this program?

1. class output

2. {

3. public static void main(String args[])

4. {

5. StringBuffer s1 = new StringBuffer("Hello World");

6. s1.insert(6 , "Good ");

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

10. What is the output of this program?

1. class output

2. {
3. public static void main(String args[])

4. {

5. char c[]={'a','1','b',' ','A','0'];

6. for (int i = 0; i < 5; ++i)

7. {

8. if(Character.isDigit(c[i]))

9. System.out.println(c[i]" is a digit");

10. if(Character.isWhitespace(c[i]))

11. System.out.println(c[i]" is a Whitespace character");

12. if(Character.isUpperCase(c[i]))

13. System.out.println(c[i]" is an Upper case Letter");

14. if(Character.isUpperCase(c[i]))

15. System.out.println(c[i]" is a lower case Letter");

16. i = i + 3;

17. }

18. }

19. }

a) a is a lower case Letter


is White space character
b) b is a lower case Letter
is White space characte
c) a is a lower case Letter
A is a upper case Letter
d) a is a lower case Letter
0 is a digit
View Answer

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.

1. Which of these class contains the methods used to write in a file?


a) FileStream
b) FileInputStream
c) BUfferedOutputStream
d) FileBufferStream
View Answer

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.

3. Which of these methods are used to read in from file?


a) get()
b) read()
c) scan()
d) readFileInput()
View Answer

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.

5. Which of these exception is thrown by close() and read() methods?


a) IOException
b) FileException
c) FileNotFoundException
d) FileInputOutputException
View Answer
Answer: a
Explanation: Both close() and read() method throw IOException.

6. Which of these methods is used to write() into a file?


a) put()
b) putFile()
c) write()
d) writeFile()
View Answer

Answer: c
Explanation: None.

7. What is the output of this program?

1. import java.io.*;

2. class filesinputoutput

3. {

4. public static void main(String args[])

5. {

6. InputStream obj = new FileInputStream("inputoutput.java");

7. System.out.print(obj.available());

8. }

9. }

Note: inputoutput.java is stored in the disk.


a) true
b) false
c) prints number of bytes in file
d) prints number of characters in the file
View Answer

Answer: c
Explanation: obj.available() returns the number of bytes.
Output:
$ javac filesinputoutput.java
$ java filesinputoutput
1422
(Output will be different in your case)

8. What is the output of this program?

1. import java.io.*;

2. public class filesinputoutput

3. {
4. public static void main(String[] args)

5. {

6. String obj = "abc";

7. byte b[] = obj.getBytes();

8. ByteArrayInputStream obj1 = new ByteArrayInputStream(b);

9. for (int i = 0; i < 2; ++ i)

10. {

11. int c;

12. while((c = obj1.read()) != -1)

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

9. What is the output of this program?

1. import java.io.*;

2. class Chararrayinput
3. {

4. public static void main(String[] args)

5. {

6. String obj = "abcdef";

7. int length = obj.length();

8. char c[] = new char[length];

9. obj.getChars(0, length, c, 0);

10. CharArrayReader input1 = new CharArrayReader(c);

11. CharArrayReader input2 = new CharArrayReader(c, 0, 3);

12. int i;

13. try

14. {

15. while((i = input2.read()) != -1)

16. {

17. System.out.print((char)i);

18. }

19. }

20. catch (IOException e)

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. {

4. public static void main(String[] args)

5. {

6. String obj = "abcdefgh";

7. int length = obj.length();

8. char c[] = new char[length];

9. obj.getChars(0, length, c, 0);

10. CharArrayReader input1 = new CharArrayReader(c);

11. CharArrayReader input2 = new CharArrayReader(c, 1, 4);

12. int i;

13. int j;

14. try

15. {

16. while((i = input1.read()) == (j = input2.read()))

17. {

18. System.out.print((char)i);

19. }

20. }

21. catch (IOException e)

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

Java Questions & Answers – Applets Fundamentals

This section of our 1000+ Java MCQs focuses on Applets fundamentals in Java Programming Language.

1. Which of these functions is called to display the output of an applet?


a) display()
b) paint()
c) displayApplet()
d) PrintApplet()
View Answer

Answer: b
Explanation: Whenever the applet requires to redraw its output, it is done by using method paint().

2. Which of these methods can be used to output a sting in an applet?


a) display()
b) print()
c) drawString()
d) transient()
View Answer

Answer: c
Explanation: drawString() method is defined in Graphics class, it is used to output a string in an applet.

3. What does AWT stands for?


a) All Window Tools
b) All Writing Tools
c) Abstract Window Toolkit
d) Abstract Writing Toolkit
View Answer

Answer: c
Explanation: AWT stands for Abstract Window Toolkit, it is used by applets to interact with the user.

4. Which of these methods is a part of Abstract Window Toolkit (AWT) ?


a) display()
b) paint()
c) drawString()
d) transient()
View Answer

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.

7. What is the Message is displayed in the applet made by this program?

1. import java.awt.*;

2. import java.applet.*;

3. public class myapplet extends Applet

4. {

5. public void paint(Graphics g)

6. {

7. g.drawString("A Simple Applet", 20, 20);

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)

8. What is the length of the application box made by this program?


1. import java.awt.*;

2. import java.applet.*;

3. public class myapplet extends Applet

4. {

5. public void paint(Graphics g)

6. {

7. g.drawString("A Simple Applet", 20, 20);

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.

9. What is the length of the application box made by this program?

1. import java.awt.*;

2. import java.applet.*;

3. public class myapplet extends Applet

4. {

5. Graphic g;

6. g.drawString("A Simple Applet", 20, 20);

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.

10. What is the output of this program?

1. import java.io.*;
2. class Chararrayinput

3. {

4. public static void main(String[] args)

5. {

6. String obj = "abcdefgh";

7. int length = obj.length();

8. char c[] = new char[length];

9. obj.getChars(0, length, c, 0);

10. CharArrayReader input1 = new CharArrayReader(c);

11. CharArrayReader input2 = new CharArrayReader(c, 1, 4);

12. int i;

13. int j;

14. try

15. {

16. while((i = input1.read()) == (j = input2.read()))

17. {

18. System.out.print((char)i);

19. }

20. }

21. catch (IOException e)

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

Java Questions & Answers – Text Formatting

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.

2. Which of this class can be used to format dates and times?


a) Date
b) SimpleDate
c) DateFormat
d) textFormat
View Answer

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.

5. Which of these formatting strings of SimpleDateFormat class is used to print AM or PM in time?


a) a
b) b
c) c
d) d
View Answer

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.

7. What is the output of this program?

1. import java.text.*;

2. import java.util.*;

3. class Date_formatting

4. {

5. public static void main(String args[])

6. {

7. Date date = new Date();

8. SimpleDateFormat sdf;

9. sdf = new SimpleDateFormat("mm:hh:ss");

10. System.out.print(sdf.format(date));

11. }

12. }

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

Answer: c
Explanation: None.
Output:
$ javac Date_formatting.java
$ java Date_formatting
55:03:04

8. What is the output of this program?

1. import java.text.*;

2. import java.util.*;

3. class Date_formatting

4. {

5. public static void main(String args[])

6. {

7. Date date = new Date();

8. SimpleDateFormat sdf;

9. sdf = new SimpleDateFormat("hh:mm:ss");

10. System.out.print(sdf.format(date));

11. }

12. }

Note : The program is executed at 3 hour 55 minutes and 4 sec (24 hours time).
a) 3:55:4
b) 3.55.4
c) 55:03:04
d) 03:55:04
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

9. What is the output of this program?

1. import java.text.*;

2. import java.util.*;

3. class Date_formatting

4. {

5. public static void main(String args[])

6. {
7. Date date = new Date();

8. SimpleDateFormat sdf;

9. sdf = new SimpleDateFormat("E MMM dd yyyy");

10. System.out.print(sdf.format(date));

11. }

12. }

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

Answer: a
Explanation: None.
Output:
$ javac Date_formatting.java
$ java Date_formatting
Mon Jul 15 2013

10. What is the output of this program?

1. import java.text.*;

2. import java.util.*;

3. class Date_formatting

4. {

5. public static void main(String args[])

6. {

7. Date date = new Date();

8. SimpleDateFormat sdf;

9. sdf = new SimpleDateFormat("z");

10. System.out.print(sdf.format(date));

11. }

12. }

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

Answer: d
Explanation: format string “z” is used to print time zone.
Output:
$ javac Date_formatting.java
$ java Date_formatting
PDT

Java Questions & Answers – Regular Expression

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Regular Expression”.

1. Which of the following is not a class of java.util.regex?


a) Pattern class
b) matcher class
c) PatternSyntaxException
d) Regex class
View Answer

Answer: d
Explanation: java.util.regex consists 3 classes. PatternSyntaxException indicates syntax error in regex.

2. What is the significance of Matcher class for regular expression in java?


a) interpretes pattern in the string
b) Performs match in the string
c) interpretest both pattern and performs match operations in the string
d) None of the mentioned.
View Answer

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

3. Object of which class is used to compile regular expression?


a) Pattern class
b) Matcher class
c) PatternSyntaxException
d) None of the mentioned
View Answer

Answer: a
Explanation: object of Pattern class can represent compiled regular expression.

4. Which capturing group can represent the entire expression?


a) group *
b) group 0
c) group * or group 0
d) Noe of the mentioned
View Answer
Answer: b
Explanation: Group 0 is a special group which represents the entire expression.

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


a) True
b) False
View Answer

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.

8. What does public int end(int group) return?


a) offset from last character of the subsequent group
b) offset from first character of the subsequent group
c) offset from last character matched
d) offset from first character matched
View Answer

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

9. what does public String replaceAll(string replace) do?


a) Replace all characters that matches pattern with replacement string
b) Replace first subsequence that matches pattern with replacement string
c) Replace all other than first subsequence of that matches pattern with replacement string
d) Replace every subsequence of the input sequence that matches pattern with replacement string
View Answer

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.

Java Questions & Answers – Event Handling Basics

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.

2. What is an event in delegation event model used by Java programming language?


a) An event is an object that describes a state change in a source
b) An event is an object that describes a state change in processing
c) An event is an object that describes any change by the user and system
d) An event is a class used for defining object, to create events
View Answer

Answer: a
Explanation: An event is an object that describes a state change in a source.

3. Which of these methods are used to register a keyboard event listener?


a) KeyListener()
b) addKistener()
c) addKeyListener()
d) eventKeyboardListener()
View Answer

Answer: c
Explanation: None.

4. Which of these methods are used to register a mouse motion listener?


a) addMouse()
b) addMouseListener()
c) addMouseMotionListner()
d) eventMouseMotionListener()
View Answer
Answer: c
Explanation: None.

5. What is a listener in context to event handling?


a) A listener is a variable that is notified when an event occurs
b) A listener is a object that is notified when an event occurs
c) A listener is a method that is notified when an event occurs
d) None of the mentioned
View Answer

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.

6. Event class is defined in which of these libraries?


a) java.io
b) java.lang
c) java.net
d) java.util
View Answer

Answer: d
Explanation: None.

7. Which of these methods can be used to determine the type of event?


a) getID()
b) getSource()
c) getEvent()
d) getEventObject()
View Answer

Answer: a
Explanation: getID() can be used to determine the type of an event.

8. Which of these class is super class of all the events?


a) EventObject
b) EventClass
c) ActionEvent
d) ItemEvent
View Answer

Answer: a
Explanation: EventObject class is a super class of all the events and is defined in java.util package.

9. Which of these events will be notified if scroll bar is manipulated?


a) ActionEvent
b) ComponentEvent
c) AdjustmentEvent
d) WindowEvent
View Answer
Answer: c
Explanation: AdjustmentEvent is generated when a scroll bar is manipulated.

10. Which of these events will be generated if we close an applet’s window?


a) ActionEvent
b) ComponentEvent
c) AdjustmentEvent
d) WindowEvent
View Answer

Answer: d
Explanation: WindowEvent is generated when a window is activated, closed, deactivated, deiconfied, iconfied,
opened or quit.

Java Questions & Answers – Packages

This section of our 1000+ Java MCQs focuses on packages of Java Programming Language.

1. Which of these keywords is used to define packages in Java?


a) pkg
b) Pkg
c) package
d) Package
View Answer

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.

5. Which of the following is correct way of importing an entire package ‘pkg’?


a) import pkg.
b) Import pkg.
c) import pkg.*
d) Import pkg.*
View Answer

Answer: c
Explanation: Operator * is used to import the entire package.

6. Which of the following is incorrect statement about packages?


a) Package defines a namespace in which classes are stored
b) A package can contain other package within it
c) Java uses file system directories to store packages
d) A package can be renamed without renaming the directory in which the classes are stored
View Answer

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.

8. What is the output of this program?

1. package pkg;

2. class display

3. {

4. int x;

5. void show()

6. {

7. if (x > 1)

8. System.out.print(x + " ");


9. }

10. }

11. class packages

12. {

13. public static void main(String args[])

14. {

15. display[] arr=new display[3];

16. for(int i=0;i<3;i++)

17. arr[i]=new display();

18. arr[0].x = 0;

19. arr[1].x = 1;

20. arr[2].x = 2;

21. for (int i = 0; i < 3; ++i)

22. arr[i].show();

23. }

24. }

Note : packages.class file is in directory pkg;


a) 0
b) 1
c) 2
d) 0 1 2
View Answer

Answer: c
Explanation: None.
Output:
$ javac packages.java
$ java packages
2

9. What is the output of this program?

1. package pkg;

2. class output

3. {

4. public static void main(String args[])

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

10. What is the output of this program?

1. package pkg;

2. class output

3. {

4. public static void main(String args[])

5. {

6. StringBuffer s1 = new StringBuffer("Hello World");

7. s1.insert(6 , "Good ");

8. System.out.println(s1);

9. }

10. }

Note : Output.class file is not in directory pkg.


a) HelloGoodWorld
b) HellGoodoWorld
c) Compilation error
d) Runtime error
View Answer

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

Java Questions & Answers – Interfaces – 1

This section of our 1000+ Java MCQs focuses on interfaces of Java Programming Language.

1. Which of these keywords is used to define interfaces in Java?


a) interface
b) Interface
c) intf
d) Intf
View Answer

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.

3. Which of these access specifiers can be used for an interface?


a) Public
b) Protected
c) private
d) All of the mentioned
View Answer

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.

4. Which of these keywords is used by a class to use an interface defined previously?


a) import
b) Import
c) implements
d) Implements
View Answer

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.

6. Which of the following is incorrect statement about packages?


a) Interfaces specifies what class must do but not how it does
b) Interfaces are specified public if they are to be accessed by any code in the program
c) All variables in interface are implicitly final and static
d) All variables are static and methods are public if interface is defined pubic
View Answer

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.

8. What is the output of this program?

1. interface calculate

2. {

3. void cal(int item);

4. }

5. class display implements calculate

6. {

7. int x;

8. public void cal(int item)

9. {

10. x = item * item;

11. }

12. }

13. class interfaces

14. {
15. public static void main(String args[])

16. {

17. display arr = new display;

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

9. What is the output of this program?

1. interface calculate

2. {

3. void cal(int item);

4. }

5. class displayA implements calculate

6. {

7. int x;

8. public void cal(int item)

9. {

10. x = item * item;

11. }

12. }

13. class displayB implements calculate

14. {
15. int x;

16. public void cal(int item)

17. {

18. x = item / item;

19. }

20. }

21. class interfaces

22. {

23. public static void main(String args[])

24. {

25. displayA arr1 = new displayA;

26. displayB arr2 = new displayB;

27. arr1.x = 0;

28. arr2.x = 0;

29. arr1.cal(2);

30. arr2.cal(2);

31. System.out.print(arr1.x + " " + arr2.x);

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

10. What is the output of this program?

1. interface calculate

2. {
3. int VAR = 0;

4. void cal(int item);

5. }

6. class display implements calculate

7. {

8. int x;

9. public void cal(int item)

10. {

11. if (item<2)

12. x = VAR;

13. else

14. x = item * item;

15. }

16. }

17. class interfaces

18. {

19.

20. public static void main(String args[])

21. {

22. display[] arr=new display[3];

23.

24. for(int i=0;i<3;i++)

25. arr[i]=new display();

26. arr[0].cal(0);

27. arr[1].cal(1);

28. arr[2].cal(2);

29. System.out.print(arr[0].x+" " + arr[1].x + " " + arr[2].x);

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

Java Questions & Answers – Interfaces – 2

This set of Java Interview Questions and Answers for Experienced people focuses on “Interfaces – 2”.

1. Which of the following access specifiers can be used for an interface?


a) Protected
b) Private
c) Public
d) Public, protected, private
View Answer

Answer: a
Explanation: Interface can have either public access specifier or no specifier.The reason is they need to be
implemented by other classes.

2. Which of the following is correct way of implementing an interface A by class B?


a) class B extends A{}
b) class B implements A{}
c) class B imports A{}
d) None of the mentioned
View Answer

Answer: b
Explanation: Concrete class implements interface. They can be instantiated.

3. All methods must be implemented of an interface.


a) True
b) False
View Answer

Answer: a
Explanation: Concrete classes must implement all methods in an interface.Through interface multiple inheritance is
possible.

4. What type of variable can be defined in an interface?


a) public static
b) private final
c) public final
d) static final
View Answer
Answer: d
Explanation: variable defined in an interface is implicitly final and static. They are usually written in capital letters.

5. What does an interface contain?


a) Method definition
b) Method declaration
c) Method declaration and definition
d) Method name
View Answer

Answer: b
Explanation: Interface contains only declaration of the method.

6. What type of methods an interface contain by default?


a) abstract
b) static
c) final
d) private
View Answer

Answer: a
Explanation: By default, interface contains abstract methods.The abstract methods need to be implemented by
concrete classes.

7. What will happen if we provide concrete implementation of method in interface?


a) The concrete class implementing that method need not provide implementation of that method
b) Runtime exception is thrown
c) Compilation failure
d) Method not found exception is thrown
View Answer

Answer: c
Explanation: The methods of interfaces are always abstract. They provide only method definition.

8. What happens when constructor is defined for an interface?


a) Compilation failure
b) Runtime Exception
c) The interface compiles successfully
d) The implementing class will throw exception
View Answer

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.

Java Questions & Answers – Core Java API Packages

This section of our 1000+ Java MCQs focuses core Java API packages in Java Programming Language.

1. Which of these package is used for graphical user interface?


a) java.applet
b) java.awt
c) java.awt.image
d) java.io
View Answer

Answer: b
Explanation: java.awt provides capabilities for graphical user interface.

2. Which of these package is used for analyzing code during run-time?


a) java.applet
b) java.awt
c) java.io
d) java.lang.reflect
View Answer

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 .

5. Which of these package is used for invoking a method remotely?


a) java.rmi
b) java.awt
c) java.util
d) java.applet
View Answer

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.

7. What is the output of this program?

1. import java.lang.reflect.*;

2. class Additional_packages

3. {

4. public static void main(String args[])

5. {

6. try

7. {

8. Class c = Class.forName("java.awt.Dimension");

9. Constructor constructors[] = c.getConstructors();

10. for (int i = 0; i < constructors.length; i++)

11. System.out.println(constructors[i]);

12. }

13. catch (Exception e)

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 possible constructors of class ‘Class’
c) Program prints “Exception”
d) Runtime Error
View Answer

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)

8. What is the output of this program?

1. import java.lang.reflect.*;

2. class Additional_packages

3. {

4. public static void main(String args[])

5. {

6. try

7. {

8. Class c = Class.forName("java.awt.Dimension");

9. Field fields[] = c.getFields();

10. for (int i = 0; i < fields.length; i++)

11. System.out.println(fields[i]);

12. }

13. catch (Exception e)

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

9. What is the length of the application box made by this program?

1. import java.awt.*;

2. import java.applet.*;

3. public class myapplet extends Applet

4. {

5. Graphic g;

6. g.drawString("A Simple Applet",20,20);

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.

10. What is the output of this program?

1. import java.lang.reflect.*;

2. class Additional_packages

3. {

4. public static void main(String args[])

5. {

6. try

7. {

8. Class c = Class.forName("java.awt.Dimension");
9. Method methods[] = c.getMethods();

10. for (int i = 0; i < methods.length; i++)

11. System.out.println(methods[i]);

12. }

13. catch (Exception e)

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: 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()

Java Questions & Answers – Type Interface

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.

4. Which of these is an correct way of defining generic class?


a) class name(T1, T2, …, Tn) { /* … */ }
b) class name { /* … */ }
c) class name[T1, T2, …, Tn] { /* … */ }
d) class name{T1, T2, …, Tn} { /* … */ }
View Answer

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.

7. What is the output of this program?

1. public class BoxDemo

2. {

3. public static <U> void addBox(U u, java.util.List<Box<U>> boxes)

4. {

5. Box<U> box = new Box<>();

6. box.set(u);

7. boxes.add(box);

8. }

9. public static <U> void outputBoxes(java.util.List<Box<U>> boxes)

10. {

11. int counter = 0;

12. for (Box<U> box: boxes)

13. {

14. U boxContents = box.get();

15. System.out.println("Box #" + counter + " contains [" + boxContents.toString() + "]");

16. counter++;

17. }

18. }

19. public static void main(String[] args)

20. {

21. java.util.ArrayList<Box<Integer>> listOfIntegerBoxes = new java.util.ArrayList<>();

22. BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes);

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].

8. What is the output of this program?

1. public class BoxDemo

2. {

3. public static <U> void addBox(U u,

4. java.util.List<Box<U>> boxes)

5. {

6. Box<U> box = new Box<>();

7. box.set(u);

8. boxes.add(box);

9. }

10. public static <U> void outputBoxes(java.util.List<Box<U>> boxes)

11. {

12. int counter = 0;

13. for (Box<U> box: boxes)

14. {

15. U boxContents = box.get();

16. System.out.println("[" + boxContents.toString() + "]");

17. counter++;

18. }

19. }

20. public static void main(String[] args)

21. {
22. java.util.ArrayList<Box<Integer>> listOfIntegerBoxes = new java.util.ArrayList<>();

23. BoxDemo.<Integer>addBox(Integer.valueOf(0), listOfIntegerBoxes);

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]

9. What is the output of this program?

1. import java.util.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])


18. {

19. genericstack <String> gs = new genericstack<String>();

20. gs.push("Hello");

21. System.out.print(gs.pop() + " ");

22. genericstack <Integer> gs = new genericstack<Integer>();

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

10. What is the output of this program?

1. public class BoxDemo

2. {

3. public static <U> void addBox(U u,

4. java.util.List<Box<U>> boxes)

5. {

6. Box<U> box = new Box<>();

7. box.set(u);

8. boxes.add(box);

9. }

10. public static <U> void outputBoxes(java.util.List<Box<U>> boxes)

11. {

12. int counter = 0;

13. for (Box<U> box: boxes)


14. {

15. U boxContents = box.get();

16. System.out.println("Box #" + counter + " contains [" + boxContents.toString() + "]");

17. counter++;

18. }

19. }

20. public static void main(String[] args)

21. {

22. java.util.ArrayList<Box<Integer>> listOfIntegerBoxes = new java.util.ArrayList<>();

23. BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes);

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].

Java Questions & Answers – JUnits

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “JUnits”.

1. JUnits are used for which type of testing?


a) Unit Testing
b) Integration Testing
c) System Testing
d) Blackbox Testing
View Answer

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.

2. Which of the below statement about JUnit is false?


a) It is an open source framework
b) It provides annotation to identify test methods
c) It provides test runners for running test
d) They cannot be run automatically
View Answer

Answer: d
Explanation: JUnits test can be run automatically and they check their own results and provide immediate feedback.

3. Which of the below is an incorrect annotation with respect to JUnits?


a) @Test
b) @BeforeClass
c) @Junit
d) @AfterEach
View Answer

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.

4. Which of these is not a mocking framework?


a) EasyMock
b) Mockito
c) PowerMock
d) MockJava
View Answer

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.

6. What does assertSame() method use for assertion?


a) equals() method
b) isEqual() method
c) ==
d) compare() method
View Answer

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.

8. How can we simulate if then behavior in Junits?


a) if{..} else{..}
b) if(..){..} else{..}
c) Mockito.when(…).thenReturn(…);
d) Mockito.if(..).then(..);
View Answer

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();

10. How can junits be implemented using maven?


a)

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.

Java Questions & Answers – Java 8 Features

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Java 8 features”.

1. Which of the following is not introduced with Java 8?


a) Stream API
b) Serialization
c) Spliterator
d) Lambda Expression
View Answer

Answer: b
Explanation: Serialization is not introduced with Java 8. It was introduced with earlier version of Java.

2. What is the purpose of BooleanSupplier function interface?


a) represents supplier of Boolean-valued results
b) returns Boolean-valued result
c) There is no such function interface
d) returns null if Boolean is passed as argument
View Answer

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.

4. Which is the new method introduced in java 8 to iterate over a collection?


a) for (String i : StringList)
b) foreach (String i : StringList)
c) StringList.forEach()
d) List.for()
View Answer

Answer: c
Explanation: Traversing through forEach method of Iterable with anonymous class.

1. StringList.forEach(new Consumer<Integer>()

2. {

3. public void accept(Integer t)

4. {

5. }

6. });

7. //Traversing with Consumer interface implementation

8. MyConsumer action = new MyConsumer();

9. StringList.forEach(action);

10. }

11. }

5. What are the two types of Streams offered by java 8?


a) sequential and parallel
b) sequential and random
c) parallel and random
d) random and synchronized
View Answer

Answer: a
Explanation: Sequential stream and parallel stream are two types of stream provided by java.

1. Stream<Integer> sequentialStream = myList.stream();

2. Stream<Integer> parallelStream = myList.parallelStream();


6. Which feature of java 8 enables us to create a work stealing thread pool using all available processsors at its
target?
a) workPool
b) newWorkStealingPool
c) threadPool
d) workThreadPool
View Answer

Answer: b
Explanation: Executors newWorkStealingPool() method to create a work-stealing thread pool using all available
processors as its target parallelism level.

7. What does Files.lines(Path path) do?


a) It reads all the files at the path specified as a String
b) It reads all the lines from a file as a Stream
c) It reads the filenames at the path specified
d) It counts the number of lines for files at the path specified
View Answer

Answer: b
Explanation: Files.lines(Path path) that reads all lines from a file as a Stream.

8. What is Optional object used for ?


a) Optional is used for optional runtime argument
b) Optional is used for optional spring profile
c) Optional is used to represent null with absent value
d) Optional means its not mandatory for method to return object
View Answer

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.

9. What is the substitute of Rhino javascript engine in java 8?


a) Nashorn
b) V8
c) Inscript
d) Narcissus
View Answer

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.

10. What does SAM stand for in context of Functional Interface?


a) Single Ambivalue Method
b) Single Abstract Method
c) Simple Active Markup
d) Simple Abstract Markup
View Answer
Answer: b
Explanation: SAM Interface stands for Single Abstract Method Interface.Functional Interface is also know as SAM
Interface because it contains only one abstract method.

Java Questions & Answers – File and Directory

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “File and Directory”.

1. Which method is used to create a directory with fileattributes ?


a) Path.create()
b) Path.createDirectory()
c) Files.createDirectory(path, fileAttributes)
d) Files.create(fileAttributes)
View Answer

Answer: c
Explanation: New directory can be created using Files.createDirectory(path, fileAttribute).

2. Which method can be used to check fileAccessiblity?


a) isReadable(path)
b) isWritable(path)
c) isExecutable(path)
d) isReadable(path), isWritable(path), and isExecutable(path)
View Answer

Answer: d
Explanation: File accessibilty can be checked using isReadable(Path), isWritable(Path), and isExecutable(Path).

3. How can we delete all files in a directory ?


a) Files.delete(path)
b) Files.deleteDir()
c) Directory.delete()
d) Directory.delete(path)
View Answer

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.

4. How to copy the file from one location to other?


a) Files.copy(source, target)
b) Path.copy(source, target)
c) source.copy(target)
d) Files.createCopy(target)
View Answer

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.

5. How can we get the size of specified file?


a) capacity(path)
b) size(path)
c) length(path)
d) Path.size()
View Answer

Answer: b
Explanation: size(Path) returns the size of the specified file in bytes.

6. How to read entire file in one line using java 8?


a) Files.readAllLines()
b) Files.read()
c) Files.readFile()
d) Files.lines()
View Answer

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.

7. How can we create a symbolic link to file?


a) createLink()
b) createSymLink()
c) createSymbolicLink()
d) createTempLink()
View Answer

Answer: c
Explanation: createSymbolicLink() creates a symbolic link to a target.

8. How can we filter lines based on content?


a) lines.filter()
b) filter(lines)
c) lines.contains(filter)
d) lines.select()
View Answer

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.

10. Which feature of java 7 allows to not explicitly close IO resource?


a) try catch finally
b) IOException
c) AutoCloseable
d) Streams
View Answer

Answer: c
Explanation: Any class that has implemented Autocloseable releases the I/O resources.

Java Questions & Answers – Generics

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Generics”.

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.

4. Which of these is an correct way of defining generic class?


a) class name(T1, T2, …, Tn) { /* … */ }
b) class name { /* … */ }
c) class name[T1, T2, …, Tn] { /* … */ }
d) class name{T1, T2, …, Tn} { /* … */ }
View Answer

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.

7. What is the output of this program?

1. import java.util.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])

18. {

19. genericstack <String> gs = new genericstack<String>();


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.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])

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

9. What is the output of this program?

1. import java.util.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])


18. {

19. genericstack <String> gs = new genericstack<String>();

20. gs.push("Hello");

21. System.out.print(gs.pop() + " ");

22. genericstack <Integer> gs = new genericstack<Integer>();

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

10. What is the output of this program?

1. import java.util.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }
14. }

15. class Output

16. {

17. public static void main(String args[])

18. {

19. genericstack <Integer> gs = new genericstack<Integer>();

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

Java Questions & Answers – Generic Methods

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Generic Methods”.

1. What are generic methods?


a) Generic methods are the methods defined in a generic class
b) Generic methods are the methods that extend generic class’s methods
c) Generic methods are methods that introduce their own type parameters
d) Generic methods are methods that take void parameters
View Answer

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.

4. Which of these is an correct way of defining generic method?


a) name(T1, T2, …, Tn) { /* … */ }
b) public name { /* … */ }
c) class name[T1, T2, …, Tn] { /* … */ }
d) name{T1, T2, …, Tn} { /* … */ }
View Answer

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.

6. Which of the following allows us to call generic methods as a normal method?


a) Type Interface
b) Interface
c) Inner class
d) All of the mentioned
View Answer

Answer: a
Explanation: Type inference, allows you to invoke a generic method as an ordinary method, without specifying a type
between angle brackets.

7. What is the output of this program?


1. import java.util.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])

18. {

19. genericstack <String> gs = new genericstack<String>();

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.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])

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

9. What is the output of this program?

1. import java.util.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])

18. {

19. genericstack <String> gs = new genericstack<String>();

20. gs.push("Hello");

21. System.out.print(gs.pop() + " ");

22. genericstack <Integer> gs = new genericstack<Integer>();

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

10. What is the output of this program?

1. import java.util.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])

18. {

19. genericstack <Integer> gs = new genericstack<Integer>();

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

Java Questions & Answers – Restrictions on Generics

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Restrictions on Generics”.

1. Which of these types cannot be used to initiate a generic type?


a) Integer class
b) Float class
c) Primitive Types
d) Collections
View Answer

Answer: c
Explanation: None.

2. Which of these instance cannot be created?


a) Integer instance
b) Generic class instance
c) Generic type instance
d) Collection instances
View Answer

Answer: c
Explanation: It is not possible to create generic type instances. Example – “E obj = new E()” will give a compilation
error.

3. Which of these data type cannot be type parameterized?


a) Array
b) List
c) Map
d) Set
View Answer

Answer: a
Explanation: None.

4. Which of these Exception handlers cannot be type parameterized?


a) catch
b) throw
c) throws
d) all of the mentioned
View Answer

Answer: d
Explanation: we cannot Create, Catch, or Throw Objects of Parameterized Types as generic class cannot extend the
Throwable class directly or indirectly.

5. Which of the following cannot be Type parameterized?


a) Oveloaded Methods
b) Generic methods
c) Class methods
d) Overriding methods
View Answer

Answer: a
Explanation: Cannot Overload a Method Where the Formal Parameter Types of Each Overload Erase to the Same
Raw Type.

6. What is the output of this program?

1. public class BoxDemo

2. {

3. public static <U> void addBox(U u,

4. java.util.List<Box<U>> boxes)

5. {

6. Box<U> box = new Box<>();

7. box.set(u);

8. boxes.add(box);

9. }

10. public static <U> void outputBoxes(java.util.List<Box<U>> boxes)

11. {

12. int counter = 0;

13. for (Box<U> box: boxes)

14. {

15. U boxContents = box.get();

16. System.out.println("Box #" + counter + " contains [" + boxContents.toString() + "]");

17. counter++;

18. }

19. }
20. public static void main(String[] args)

21. {

22. java.util.ArrayList<Box<Integer>> listOfIntegerBoxes = new java.util.ArrayList<>();

23. BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes);

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]

7. What is the output of this program?

1. import java.util.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output


16. {

17. public static void main(String args[])

18. {

19. genericstack <String> gs = new genericstack<String>();

20. gs.push("Hello");

21. System.out.print(gs.pop() + " ");

22. genericstack <Integer> gs = new genericstack<Integer>();

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

8. What is the output of this program?

1. import java.util.*;

2. class Output

3. {

4. public static double sumOfList(List<? extends Number> list)

5. {

6. double s = 0.0;

7. for (Number n : list)

8. s += n.doubleValue();

9. return s;

10. }

11. public static void main(String args[])


12. {

13. List<Double> ld = Arrays.asList(1.2, 2.3, 3.5);

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

9. What is the output of this program?

1. import java.util.*;

2. class Output

3. {

4. public static void addNumbers(List<? super Integer> list)

5. {

6. for (int i = 1; i <= 10; i++)

7. {

8. list.add(i);

9. }

10. }

11. public static void main(String args[])

12. {

13. List<Double> ld = Arrays.asList();

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

10. What is the output of this program?

1. import java.util.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])

18. {

19. genericstack <Integer> gs = new genericstack<Integer>();

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

Advanced Java Questions & Answers – JDBC

This set of Advanced Java Multiple Choice Questions & Answers (MCQs) focuses on “JDBC”.

1. Which of the following contains both date and time?


a) java.io.date
b) java.sql.date
c) java.util.date
d) java.util.dateTime
View Answer

Answer: d
Explanation: java.util.date contains both date and time. Whereas, java.sql.date contains only date.

2. Which of the following is advantage of using JDBC connection pool?


a) Slow performance
b) Using more memory
c) Using less memory
d) Better performance
View Answer

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.

3. Which of the following is advantage of using PreparedStatement in Java?


a) Slow performance
b) Encourages SQL injection
c) Prevents SQL injection
d) More memory usage
View Answer

Answer: c
Explanation: PreparedStatement in Java improves performance and also prevents from SQL injection.

4. Which one of the following contains date information?


a) java.sql.TimeStamp
b) java.sql.Time
c) java.io.Time
d) java.io.TimeStamp
View Answer

Answer: a
Explanation: java.sql.Time contains only time. Whereas, java.sql.TimeStamp contains both time and date.

5. What does setAutoCommit(false) do?


a) commits transaction after each query
b) explicitly commits transaction
c) does not commit transaction automatically after each query
d) never commits transaction
View Answer

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.

6. Which of the following is used to call stored procedure?


a) Statement
b) PreparedStatement
c) CallableStatment
d) CalledStatement
View Answer

Answer: c
Explanation: CallableStatement is used in JDBC to call stored procedure from Java program.

7. Which of the following is used to limit the number of rows returned?


a) setMaxRows(int i)
b) setMinRows(int i)
c) getMaxrows(int i)
d) getMinRows(int i)
View Answer

Answer: a
Explanation: setMaxRows(int i) method is used to limit the number of rows that the database returns from the
query.

8. Which of the following is method of JDBC batch process?


a) setBatch()
b) deleteBatch()
c) removeBatch()
d) addBatch()
View Answer

Answer: d
Explanation: addBatch() is a method of JDBC batch process. It is faster in processing than executing one statement at
a time.

9. Which of the following is used to rollback a JDBC transaction?


a) rollback()
b) rollforward()
c) deleteTransaction()
d) RemoveTransaction()
View Answer

Answer: a
Explanation: rollback() method is used to rollback the transaction. It will rollback all the changes made by the
transaction.

10. Which of the following is not a JDBC connection isolation levels?


a) TRANSACTION_NONE
b) TRANSACTION_READ_COMMITTED
c) TRANSACTION_REPEATABLE_READ
d) TRANSACTION_NONREPEATABLE_READ
View Answer

Answer: d
Explanation: TRANSACTION_NONREPEATABLE_READ is not a JDBC connection isolation level.

Java Questions & Answers – Wildcards

This set of Java Multiple Choice Questions & Answers (MCQs) focuses on “Wildcards”.

1. Which of these is wildcard symbol?


a) ?
b) !
c) %
d) &
View Answer

Answer: a
Explanation: In generic code, the question mark (?), called the wildcard, represents an unknown type.

2. What is use of wildcards?


a) It is used in cases when type being operated upon is not known
b) It is used to make code more readable
c) It is used to access members of super class
d) It is used for type argument of generic method
View Answer

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.

3. Which of these keywords is used to upper bound a wildcard?


a) stop
b) bound
c) extends
d) implements
View Answer
Answer: c
Explanation: None.

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: .

7. What is the output of this program?

1. import java.util.*;

2. class Output

3. {

4. public static double sumOfList(List<? extends Number> list)

5. {

6. double s = 0.0;

7. for (Number n : list)

8. s += n.doubleValue();

9. return s;
10. }

11. public static void main(String args[])

12. {

13. List<Integer> li = Arrays.asList(1, 2, 3);

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

8. What is the output of this program?

1. import java.util.*;

2. class Output

3. {

4. public static double sumOfList(List<? extends Number> list)

5. {

6. double s = 0.0;

7. for (Number n : list)

8. s += n.doubleValue();

9. return s;

10. }

11. public static void main(String args[])

12. {

13. List<Double> ld = Arrays.asList(1.2, 2.3, 3.5);

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

9. What is the output of this program?

1. import java.util.*;

2. class Output

3. {

4. public static void addNumbers(List<? super Integer> list)

5. {

6. for (int i = 1; i <= 10; i++)

7. {

8. list.add(i);

9. }

10. }

11. public static void main(String args[])

12. {

13. List<Double> ld = Arrays.asList();

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

10. What is the output of this program?

1. import java.util.*;

2. public class genericstack <E>

3. {

4. Stack <E> stk = new Stack <E>();

5. public void push(E obj)

6. {

7. stk.push(obj);

8. }

9. public E pop()

10. {

11. E obj = stk.pop();

12. return obj;

13. }

14. }

15. class Output

16. {

17. public static void main(String args[])

18. {

19. genericstack <Integer> gs = new genericstack<Integer>();

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

You might also like