Java MCQ Number 01112

Java MCQ Set 1

1. What is the order of variables in Enum?
a) Ascending order
b) Descending order
c) Random order
d) depends on the order() method

Answer

Answer: a [Reason:] The compareTo() method is implemented to order the variable in ascending order.

2. Can we create instance of Enum outside of Enum itself?
a) True
b) False

Answer

Answer: b [Reason:] Enum does not have public constructor.

3.

  1.  enum Season {
  2.         WINTER, SPRING, SUMMER, FALL
  3.     };
  4.     System.out.println(Season.WINTER.ordinal());

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

Answer

Answer: a [Reason:] ordinal() method provides number to the variables defined in Enum.

4. If we try to add Enum constants to a TreeSet, what sorting order will it use?
a) Sorted in the order of declaration of Enums
b) Sorted in alphabetical order of Enums
c) Sorted based on order() method
d) Sorted in descending order of names of Enums

Answer

Answer: a [Reason:] Tree Set will sort the values in the order in which Enum constants are declared.

5. What is the output of below code snippet?

  1. class A
  2. {
  3.  
  4. }
  5.  
  6. enum Enums extends A
  7. {
  8.     ABC, BCD, CDE, DEF;
  9. }

a) Runtime Error
b) Compilation Error
c) It runs successfully
d) EnumNotDefined Exception

Answer

Answer: b [Reason:] Enum types cannot extend class.

6. What is the output of below code snippet?

  1.  enum Levels 
  2. {
  3.     private TOP,
  4.  
  5.     public MEDIUM,
  6.  
  7.     protected BOTTOM;
  8. }

a) Runtime Error
b) EnumNotDefined Exception
c) It runs successfully
d) Compilation Error

Answer

Answer: d [Reason:] Enum cannot have any modifiers. They are public, static and final by default.

7. What is the output of below code snippet?

  1. enum Enums
  2. {
  3.     A, B, C;
  4.  
  5.     private Enums()
  6.     {
  7.         System.out.println(10);
  8.     }
  9. }
  10.  
  11. public class MainClass
  12. {
  13.     public static void main(String[] args)
  14.     {
  15.         Enum en = Enums.B;
  16.     }
  17. }

a) 10
10
10
b) Compilation Error
c) 10
10
d) Runtime Exception

Answer

Answer: a [Reason:] The constructor of Enums is called which prints 10.

8. Which method returns the elements of Enum class?
a) getEnums()
b) getEnumConstants()
c) getEnumList()
d) getEnum()

Answer

Answer: b [Reason:] getEnumConstants() returns the elements of this enum class or null if this Class object does not represent an enum type.

9. Which class does all the Enums extend?
a) Object
b) Enums
c) Enum
d) EnumClass

Answer

Answer: c [Reason:] All enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.

10. Are enums are type-safe?
a) True
b) False

Answer

Answer: a [Reason:] Enums are type-safe as they have own name-space.

Java MCQ Set 2

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

Answer: d [Reason:] None.
output:
$ javac cons_method.java
$ java cons_method
30

Java MCQ Set 3

1. Which object Java application uses to create a new process?
a) Process
b) Builder
c) ProcessBuilder
d) CreateBuilder

Answer

Answer: c [Reason:] 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()

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

Answer: c [Reason:] This method can be used to load files using relative path to the package of the class.

Java MCQ Set 4

1. Which of the following keywords is used for throwing exception manually?
a) finally
b) try
c) throw
d) catch

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

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

Answer

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

Answer

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

Answer

Answer: b [Reason:] Error is not recoverable at run time. The control is lost from the application.

Java MCQ Set 5

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

Answer

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

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

DistPub Team

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