250+ TOP MCQs on Writing Console Output and Answers

Java MCQs 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

Answer: d
Clarification: 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

Answer: d
Clarification: None.

3. Which of these classes are used by character streams output operations?
a) InputStream
b) Writer
c) ReadStream
d) InputOutputStream

Answer: b
Clarification: Character streams uses Writer and Reader classes for input & output operations.

4. Which of these class is used to read from a file?
a) InputStream
b) BufferedInputStream
c) FileInputStream
d) BufferedFileInputStream

Answer: c
Clarification: None.

5. What will be the output of the following Java 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

Answer: a
Clarification: 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
6 4 6 9

6. What will be the output of the following Java 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

Answer: a
Clarification: 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

7. What will be the output of the following Java 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

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

$ javac output.java
$ java output
olleH

250+ TOP MCQs on JUnits and Answers

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

1. JUnits are used for which type of testing?
a) Unit Testing
b) Integration Testing
c) System Testing
d) Blackbox Testing

Answer: a
Clarification: 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 an annotation to identify test methods
c) It provides test runners for running test
d) They cannot be run automatically

Answer: d
Clarification: 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

Answer: c
Clarification: @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

Answer: d
Clarification: EasyMock, jMock, Mockito, Unitils Mock, PowerMock and JMockit are a various mocking framework.

5. Which method is used to verify the actual and expected results in Junits?
a) assert()
b) equals()
c) ==
d) isEqual()

Answer: a
Clarification: 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

Answer: c
Clarification: == 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)

Answer: d
Clarification: @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(..);

Answer: c
Clarification: 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

Answer: a
Clarification: @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>junitgroupId>
  3.     <artifactId>junitartifactId>
  4.     <version>4.8.1version>
  5.  dependency>

b)

  1.  <dependency>
  2.     <groupId>org.junitgroupId>
  3.     <artifactId>junitartifactId>
  4.     <version>4.8.1version>
  5.  dependency>

c)

  1.  <dependency>
  2.     <groupId>mock.junitgroupId>
  3.     <artifactId>junitartifactId>
  4.     <version>4.8.1version>
  5.  dependency>

d)

  1.  <dependency>
  2.     <groupId>junitsgroupId>
  3.     <artifactId>junitartifactId>
  4.     <version>4.8.1version>
  5.  dependency>

Answer: a
Clarification: JUnits can be used using dependency tag in maven in pom.xml. The version as desired and available in repository can be used.

 
 

Advanced 250+ TOP MCQs on Servlet and Answers

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

1. How constructor can be used for a servlet?
a) Initialization
b) Constructor function
c) Initialization and Constructor function
d) Setup() method

Answer: c
Clarification: We cannot declare constructors for interface in Java. This means we cannot enforce this requirement to any class which implements Servlet interface.
Also, Servlet requires ServletConfig object for initialization which is created by container.

2. Can servlet class declare constructor with ServletConfig object as an argument?
a) True
b) False

Answer: b
Clarification: ServletConfig object is created after the constructor is called and before init() is called. So, servlet init parameters cannot be accessed in the constructor.

3. What is the difference between servlets and applets?
i. Servlets execute on Server; Applets execute on browser
ii. Servlets have no GUI; Applet has GUI
iii. Servlets creates static web pages; Applets creates dynamic web pages
iv. Servlets can handle only a single request; Applet can handle multiple requests
a) i, ii, iii are correct
b) i, ii are correct
c) i, iii are correct
d) i, ii, iii, iv are correct

Answer: b
Clarification: Servlets execute on Server and doesn’t have GUI. Applets execute on browser and has GUI.

4. Which of the following code is used to get an attribute in a HTTP Session object in servlets?
a) session.getAttribute(String name)
b) session.alterAttribute(String name)
c) session.updateAttribute(String name)
d) session.setAttribute(String name)

Answer: a
Clarification: session has various methods for use.

5. Which method is used to get three-letter abbreviation for locale’s country in servlets?
a) Request.getISO3Country()
b) Locale.getISO3Country()
c) Response.getISO3Country()
d) Local.retrieveISO3Country()

Answer: a
Clarification: Each country is usually denoted by a 3 digit code.ISO3 is the 3 digit country code.

6. Which of the following code retrieves the body of the request as binary data?
a) DataInputStream data = new InputStream()
b) DataInputStream data = response.getInputStream()
c) DataInputStream data = request.getInputStream()
d) DataInputStream data = request.fetchInputStream()

Answer: c
Clarification: InputStream is an abstract class. getInputStream() retrieves the request in binary data.

7. When destroy() method of a filter is called?
a) The destroy() method is called only once at the end of the life cycle of a filter
b) The destroy() method is called after the filter has executed doFilter method
c) The destroy() method is called only once at the begining of the life cycle of a filter
d) The destroyer() method is called after the filter has executed

Answer: a
Clarification: destroy() is an end of life cycle method so it is called at the end of life cycle.

8. Which of the following is true about servlets?
a) Servlets execute within the address space of web server
b) Servlets are platform-independent because they are written in java
c) Servlets can use the full functionality of the Java class libraries
d) Servlets execute within the address space of web server, platform independent and uses the functionality of java class libraries

Answer: d
Clarification: Servlets execute within the address space of a web server. Since it is written in java it is platform independent. The full functionality is available through libraries.

9. How is the dynamic interception of requests and responses to transform the information done?
a) servlet container
b) servlet config
c) servlet context
d) servlet filter

Answer: d
Clarification: Servlet has various components like container, config, context, filter. Servlet filter provides the dynamic interception of requests and responses to transform the information.

10. Which are the session tracking techniques?
i. URL rewriting
ii. Using session object
iii.Using response object
iv. Using hidden fields
v. Using cookies
vi. Using servlet object
a) i, ii, iii, vi
b) i, ii, iv, v
c) i, vi, iii, v
d) i, ii, iii, v

Answer: b
Clarification: URL rewriting, using session object, using cookies, using hidden fields are session tracking techniques.

250+ TOP MCQs on Class Fundamentals & Declaring objects and Answers

Java MCQs on class fundamentals & object declaration in Java Programming Language.

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

a) Memory address of allocated memory of object
b) NULL
c) Any arbitrary pointer
d) Garbage

Answer: b
Clarification: 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

Answer: a
Clarification: 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;

Answer: a
Clarification: None.

4. Which of these operators is used to allocate memory for an object?
a) malloc
b) alloc
c) new
d) give

Answer: c
Clarification: 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

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

6. What will be the output of the following Java 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

Answer: c
Clarification: 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

Answer: a
Clarification: None.

8. What will be the output of the following Java 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

Answer: b
Clarification: None.
output:

$ javac mainclass.java
$ java mainclass
200

9. What will be the output of the following Java 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

Answer: a
Clarification: 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 will be the output of the following Java 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) [email protected] in hexadecimal form

Answer: d
Clarification: When we print object internally toString() will be called to return string into this format [email protected] in hexadecimal form.
output:

250+ TOP MCQs on Inheritance – Abstract Class and Super and Answers

Java MCQs 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

Answer: b
Clarification: None.

2. Which of these is not abstract?
a) Thread
b) AbstractList
c) List
d) None of the Mentioned

Answer: a
Clarification: 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

Answer: a
Clarification: 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

Answer: c
Clarification: 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

Answer: a
Clarification: None.

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

  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

Answer: d
Clarification: 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 will be the output of the following Java code?

  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

Answer: a
Clarification: 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
1 2

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

  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

Answer: c
Clarification: 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

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

  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

Answer: a
Clarification: 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
1 2

250+ TOP MCQs on Memory Management and Answers

This set of Java Multiple Choice Questions & Answers (MCQs) 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

Answer: d
Clarification: There are only 3 types of memory segment. Stack Segment, Heap Segment and Code Segment.

2. Does code Segment loads the java code?
a) True
b) False

Answer: a
Clarification: Code Segment loads compiled java bytecode. Bytecode is platform independent.

3. What is JVM?
a) Bootstrap
b) Interpreter
c) Extension
d) Compiler

Answer: b
Clarification: JVM is Interpreter. 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) Interpreter

Answer: a
Clarification: 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

Answer: b
Clarification: 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

Answer: d
Clarification: Young generation is further classified into Eden space and Survivor space. Old generation is also the tenured space. The 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

Answer: c
Clarification: 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

Answer: d
Clarification: 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

Answer: b
Clarification: 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

Answer: a
Clarification: 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.