Java MCQ Set 1
1. What is the type of variable ‘b’ and ‘d’ in the below snippet?
int a[], b;
int []c, d;
a) ‘b’ and ‘d’ are int
b) ‘b’ and ‘d’ are arrays of type int
c) ‘b’ is int variable; ‘d’ is int array
d) ‘d’ is int variable; ‘b’ is int array
Answer
Answer: c [Reason:] If [] is declared after variable it is applicable only to one variable. If [] is declared before variable it is applicable to all the variables.
2. Which of these is an incorrect array declaration?
a) int arr[] = new int[5] ;
b) int [] arr = new int[5] ;
c) int arr[];
arr = new int[5];
d) int arr[] = int [5] new;
Answer
Answer: d [Reason:] Operator new must be succeeded by array type and array size. The order is important and determines the type of variable.
3. What will this code print?
-
int arr[] = new int [5];
-
System.out.print(arr);
a) 0
b) value stored in arr[0].
c) 00000
d) Garbage value
Answer
Answer: d [Reason:] arr is an array variable, it is pointing to array of integers. Printing arr will print garbage value. It is not same as printing arr[0].
4. What is the output of below snippet?
-
Object[] names = new String[3];
-
names[0] = new Integer(0);
a) ArrayIndexOutOfBoundsException
b) ArrayStoreException
c) Compilation Error
d) Code runs successfully
Answer
Answer: b [Reason:] ArrayIndexOutOfBoundsException comes when code tries to access an invalid index for a given array. ArrayStoreException comes when you have stored an element of type other than the type of array.
5. Generics does not work with?
a) Set
b) List
c) Tree
d) Array
Answer
Answer: d [Reason:] Generics gives the flexibility to strongly typecast collections. Generics is applicable to Set, List and Tree. It is not applicable to Array.
6. How to sort an array?
a) Array.sort()
b) Arrays.sort()
c) Collection.sort()
d) System.sort()
Answer
Answer: b [Reason:] Arrays class contains various methods for manipulating arrays (such as sorting and searching). Array is not a valid class.
7. How to copy contents of array?
a) System.arrayCopy()
b) Array.copy()
c) Arrays.copy()
d) Collection.copy()
Answer
Answer: a [Reason:] Arrays class contains various methods for manipulating arrays (such as sorting and searching). Array is not a valid class.
8. Can you make an array volatile?
a) True
b) False
Answer
Answer: a [Reason:] You can only make variable pointing to array volatile. If array is changed by replacing individual elements then guarantee provided by volatile variable will not be held.
9. Where is array stored in memory?
a) heap space
b) stack space
c) heap space and stack space
d) first generation memory
Answer
Answer: a [Reason:] Array is stored in heap space.Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it.
10. An array elements are always stored in ________ memory locations?
a) Sequential
b) Random
c) Sequential and Random
d) Binary search
Answer
Answer: a [Reason:] Array elements are stored in contiguous memory.Linked List is stored in random memory locations.
Java MCQ Set 2
1. How to format date from one form to another?
a) SimpleDateFormat
b) DateFormat
c) SimpleFormat
d) DateConverter
Answer
Answer: a [Reason:] SimpleDateFormat can be used as
Date now = new Date();
SimpleDateFormat sdf = new SimpleDateFormat (“yyyy-mm-dd’T’hh:MM:ss”);
String nowStr = sdf.format(now);
System.out.println(“Current Date: ” + );
2. How to convert Date object to String?
a) SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-mm-dd”);
sdf.parse(new Date());
b) SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-mm-dd”);
sdf.format(new Date());
c)SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-mm-dd”);
new Date().parse();
d) SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-mm-dd”);
new Date().format();
Answer
Answer: b [Reason:] SimpleDateFormat takes a string containing pattern. sdf.format converts the Date object to String.
3. How to convert a String to a Date object?
a) SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-mm-dd”);
sdf.parse(new Date());
b) SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-mm-dd”);
sdf.format(new Date());
c)SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-mm-dd”);
new Date().parse();
d) SimpleDateFormat sdf = new SimpleDateFormat(“yyyy-mm-dd”);
new Date().format();
Answer
Answer: a [Reason:] SimpleDateFormat takes a string containing pattern. sdf.parse converts the String to Date object.
4. Is SimpleDateFormat thread safe?
a) True
b) False
Answer
Answer: b [Reason:] SimpleDateFormat is not thread safe. In multithreaded environment we need to manage threads explicitly.
5. How to identify if a timezone is eligible for DayLight Saving?
a) useDaylightTime() of Time class
b) useDaylightTime() of Date class
c) useDaylightTime() of TimeZone class
d) useDaylightTime() of DateTime class
Answer
Answer: c [Reason:] public abstract boolean useDaylightTime() is provided in TimeZone class.
6. What is the replacement of joda time library in java 8?
a) java.time (JSR-310)
b) java.date (JSR-310)
c) java.joda
d) java.jodaTime
Answer
Answer: a [Reason:] In java 8,we are asked to migrate to java.time (JSR-310) which is a core part of the JDK which replaces joda library project.
7. How is Date stored in database?
a) java.sql.Date
b) java.util.Date
c) java.sql.DateTime
d) java.util.DateTime
Answer
Answer: a [Reason:] java.sql.Date is the datatype of Date stored in database.
8. What does LocalTime represent?
a) Date without time
b) Time without Date
c) Date and Time
d) Date and Time with timezone
Answer
Answer: b [Reason:] LocalTime of joda library represents time without date.
9. How to get difference between two dates?
a) long diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();
b) long diffInMilli = java.time.difference(dateTime1, dateTime2).toMillis();
c) Date diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();
d) Time diffInMilli = java.time.Duration.between(dateTime1, dateTime2).toMillis();
Answer
Answer: a [Reason:] Java 8 provides a method called between which provides Duration between two times.
10. How to get UTC time?
a) Time.getUTC();
b) Date.getUTC();
c) Instant.now();
d) TimeZone.getUTC();
Answer
Answer: c [Reason:] In java 8, Instant.now() provides current time in UTC/GMT.
Java MCQ Set 3
1. Which of these method is used to implement Runnable interface?
a) stop()
b) run()
c) runThread()
d) stopThread()
Answer
Answer: b [Reason:] 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
Answer
Answer: a [Reason:] None.
3. Which of these method is used to begin the execution of a thread?
a) run()
b) start()
c) runThread()
d) startThread()
Answer
Answer: b [Reason:] None.
4. Which of these method waits for the thread to treminate?
a) sleep()
b) isAlive()
c) join()
d) stop()
Answer
Answer: c [Reason:] 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
Answer
Answer: d [Reason:] 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?
-
class newthread implements Runnable
-
{
-
Thread t;
-
newthread()
-
{
-
t = new Thread(this,"My Thread");
-
t.start();
-
}
-
public void run()
-
{
-
System.out.println(t.getName());
-
}
-
}
-
class multithreaded_programing
-
{
-
public static void main(String args[])
-
{
-
new newthread();
-
}
-
}
a) My Thread
b) Thread[My Thread,5,main].
c) Compilation Error
d) Runtime Error
Answer
Answer: a [Reason:] None.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
My Thread
7. What is the output of this program?
-
class newthread implements Runnable
-
{
-
Thread t;
-
newthread()
-
{
-
t = new Thread(this,"My Thread");
-
t.start();
-
}
-
public void run()
-
{
-
System.out.println(t);
-
}
-
}
-
class multithreaded_programing
-
{
-
public static void main(String args[])
-
{
-
new newthread();
-
}
-
}
a) My Thread
b) Thread[My Thread,5,main].
c) Compilation Error
d) Runtime Error
Answer
Answer: b [Reason:] None.
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
Thread[My Thread,5,main]
8. What is the output of this program?
-
class newthread implements Runnable
-
{
-
Thread t;
-
newthread()
-
{
-
t = new Thread(this,"My Thread");
-
t.start();
-
}
-
}
-
class multithreaded_programing
-
{
-
public static void main(String args[])
-
{
-
new newthread();
-
}
-
}
a) My Thread
b) Thread[My Thread,5,main].
c) Compilation Error
d) Runtime Error
Answer
Answer: c [Reason:] 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?
-
class newthread implements Runnable
-
{
-
Thread t;
-
newthread()
-
{
-
t = new Thread(this,"New Thread");
-
t.start();
-
}
-
public void run()
-
{
-
t.setPriority(Thread.MAX_PRIORITY);
-
System.out.println(t);
-
}
-
}
-
class multithreaded_programing
-
{
-
public static void main(String args[])
-
{
-
new newthread();
-
}
-
}
a) Thread[New Thread,0,main].
b) Thread[New Thread,1,main].
c) Thread[New Thread,5,main].
d) Thread[New Thread,10,main].
Answer
Answer: d [Reason:] 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?
-
class newthread implements Runnable
-
{
-
Thread t;
-
newthread()
-
{
-
t1 = new Thread(this,"Thread_1");
-
t2 = new Thread(this,"Thread_2");
-
t1.start();
-
t2.start();
-
}
-
public void run()
-
{
-
t2.setPriority(Thread.MAX_PRIORITY);
-
System.out.print(t1.equals(t2));
-
}
-
}
-
class multithreaded_programing
-
{
-
public static void main(String args[])
-
{
-
new newthread();
-
}
-
}
a) true
b) false
c) truetrue
d) falsefalse
Answer
Answer: d [Reason:] 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 MCQ Set 4
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)
Answer
Answer: c [Reason:] 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)
Answer
Answer: d [Reason:] 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)
Answer
Answer: a [Reason:] 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)
Answer
Answer: a [Reason:] 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()
Answer
Answer: b [Reason:] 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()
Answer
Answer: a [Reason:] 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()
Answer
Answer: c [Reason:] 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()
Answer
Answer: a [Reason:] 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
Answer
Answer: b [Reason:] 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
Answer
Answer: c [Reason:] Any class that has implemented Autocloseable releases the I/O resources.