An Advanced Quiz On Core Java!

Approved & Edited by ProProfs Editorial Team
The editorial team at ProProfs Quizzes consists of a select group of subject experts, trivia writers, and quiz masters who have authored over 10,000 quizzes taken by more than 100 million users. This team includes our in-house seasoned quiz moderators and subject matter experts. Our editorial experts, spread across the world, are rigorously trained using our comprehensive guidelines to ensure that you receive the highest quality quizzes.
Learn about Our Editorial Process
| By Unrealvicky
U
Unrealvicky
Community Contributor
Quizzes Created: 5 | Total Attempts: 9,909
Questions: 45 | Attempts: 746

SettingsSettingsSettings
An Advanced Quiz On Core Java! - Quiz

JAVA is everywhere, from your microwave oven to DVD player, TV remotes to music players, almost everywhere JAVA is used. Well, cut to short, Core Java focuses on the language basics such as data structures, data types, operators, control statements, string handling, exception handling, etc. Here in this quiz, you will face forty-five questions of the same. So, let's get started.


Questions and Answers
  • 1. 

    Which of the following are uses of Object class?(Choose 3)

    • A.

      To achieve inheritance at user-defined class level

    • B.

      To generate String representation of an object

    • C.

      To get the HashCode for an object

    • D.

      To achieve polymorphism at user-defined class level

    • E.

      To handle any Java Object in the name of Object

    Correct Answer(s)
    B. To generate String representation of an object
    C. To get the HashCode for an object
    E. To handle any Java Object in the name of Object
    Explanation
    The Object class in Java is a built-in class that serves as the root of the class hierarchy. It is the superclass of all other classes in Java.

    One use of the Object class is to generate a String representation of an object. This is done by overriding the toString() method in a user-defined class. The toString() method returns a string that represents the object, which is useful for printing or debugging purposes.

    Another use of the Object class is to get the HashCode for an object. The hashCode() method in the Object class returns a unique identifier for an object. This identifier is typically used for hashing and indexing purposes.

    The third use of the Object class is to handle any Java Object in the name of Object. Since all classes in Java inherit from the Object class, it is possible to treat any object as an instance of the Object class. This allows for polymorphism, where objects of different types can be treated as objects of the Object class.

    Rate this question:

  • 2. 

    Which of the following options are true for StringBuffer class?(choose 3)

    • A.

      StringBuffer is extended from String class

    • B.

      StringBuffer is threadsafe

    • C.

      'capacity' property indicates the maximum number ofcharacters that a StringBuffer can have

    • D.

      StringBuffer implements Charsequence interface

    • E.

      Buffer space in StringBuffer can be shared

    Correct Answer(s)
    B. StringBuffer is threadsafe
    D. StringBuffer implements Charsequence interface
    E. Buffer space in StringBuffer can be shared
    Explanation
    The first statement is false. StringBuffer is not extended from the String class, but it is a separate class that provides similar functionality for manipulating strings.

    The second statement is true. StringBuffer is thread-safe, meaning that it can be safely used in a multi-threaded environment without causing any data corruption or synchronization issues.

    The third statement is true. The 'capacity' property of a StringBuffer indicates the maximum number of characters that it can hold. This capacity can be increased dynamically as needed.

    The fourth statement is false. StringBuffer does not implement the Charsequence interface. However, it does implement the CharSequence interface's sub-interface called Appendable.

    The fifth statement is true. The buffer space in a StringBuffer can be shared among multiple instances or threads, allowing for efficient memory usage and manipulation of strings.

    Rate this question:

  • 3. 

    Consider the following code snippet: class Train { String name = "Shatapdhi"; } class TestTrain { public static void main(String a[]) { Train t = new Train(); System.out.println(t); // Line a System.out.println(t.toString()); // Line b } } Which of the following statements are true?(Choose 3)

    • A.

      Output of Line a and Line b will be same

    • B.

      Output of Line a and Line b will be different

    • C.

      Line a prints the corresponding classname with Object'shashcode in Hexadecimal

    • D.

      Both Line a and Line b will print the corresponding classnamewith Object's hashcode in Hexa Decimal

    • E.

      Both Line a and Line b prints "Shatapdhi"

    Correct Answer(s)
    A. Output of Line a and Line b will be same
    C. Line a prints the corresponding classname with Object'shashcode in Hexadecimal
    D. Both Line a and Line b will print the corresponding classnamewith Object's hashcode in Hexa Decimal
    Explanation
    The output of Line a and Line b will be the same because when we print an object without explicitly calling its toString() method, the default implementation of toString() method is called, which returns the classname followed by the object's hashcode in hexadecimal. Therefore, Line a prints the corresponding classname with the object's hashcode in hexadecimal. Additionally, Line b explicitly calls the toString() method, so it will also print the corresponding classname with the object's hashcode in hexadecimal. Thus, both Line a and Line b will print the corresponding classname with the object's hashcode in hexadecimal.

    Rate this question:

  • 4. 

    Which of the following are true regarding PreparedStatement?(choose 3)

    • A.

      PreparedStatement are the SQL templates available in thedatabase server, that can be used directly without writingcomplex SQL code

    • B.

      PreparedStatement cannot be used to create ScrollableResultSet

    • C.

      Parameters can be passed to PreparedStatement at run-time

    • D.

      PreparedStatements are precompiled SQL statements thatare faster in execution

    • E.

      PreparedStatement is the sub interface of Statementinterface

    Correct Answer(s)
    C. Parameters can be passed to PreparedStatement at run-time
    D. PreparedStatements are precompiled SQL statements thatare faster in execution
    E. PreparedStatement is the sub interface of Statementinterface
    Explanation
    1. Parameters can be passed to PreparedStatement at run-time: This statement is true. PreparedStatements allow the use of parameterized queries, where values can be dynamically passed to the SQL statement at runtime, providing flexibility and preventing SQL injection attacks.
    2. PreparedStatements are precompiled SQL statements that are faster in execution: This statement is true. PreparedStatements are precompiled and cached by the database server, resulting in faster execution as compared to regular Statements.
    3. PreparedStatement is the sub interface of Statement interface: This statement is true. PreparedStatement is a sub interface of the Statement interface in Java, providing additional functionality for executing parameterized SQL queries.

    Rate this question:

  • 5. 

    Consider the following code snippet: public class TestString10{ public void print() { String s = "Hello"; StringBuffer sb = new StringBuffer("Hello"); concatinateStrings(s, sb); System.out.println(s+" "+sb); } public void concatinateStrings(String str, StringBuffer strBuff){ StringBuffer sk = strBuff; str = str + " world"; sk.append(" world"); } public static void main (String[] args) { TestString10 t = new TestString10(); t.print(); } } What will be the output of the above code snippet?

    • A.

      Hello Hello world

    • B.

      World world world

    • C.

      Hello Hello Hello

    • D.

      World Hello Hello

    • E.

      Hello world Hello

    Correct Answer
    A. Hello Hello world
    Explanation
    The output of the code snippet will be "Hello Hello world". This is because the method concatinateStrings modifies the StringBuffer object by appending " world" to it, which is then printed as part of the output. However, the variable "s" remains unchanged, so it still prints "Hello" as part of the output.

    Rate this question:

  • 6. 

    Consider the following code: 1. public class Circle1 { 2. private String string = "String1"; 3. void work() { 4. String x = "String2"; 5. class Circle2 { 6. public void peepOut() { 7. System.out.println(string); 8. System.out.println(x); 9. } 10. } 11. new Circle2().peepOut(); 12. } 13. 14. public static void main(String args[]) { 15. Circle1 c1 = new Circle1(); 16. c1.work(); 17. } 18. } Which of the following changes made to the above code will make the code to compile and execute properly and gives the following output? String1 String2

    • A.

      The variable at line 4 should be declared as final

    • B.

      The variable at line 2 should be declared as final

    • C.

      The method at line 6 should be defined as final method

    • D.

      The inner class Circle 2 should be an abstract class

    • E.

      The object for the inner class Circle2 should be created in main() method

    Correct Answer
    A. The variable at line 4 should be declared as final
    Explanation
    The variable at line 4 should be declared as final because it is being accessed from a local inner class (Circle2) which is defined within the work() method. Local inner classes can only access local variables if they are declared as final. By declaring the variable as final, it ensures that its value remains constant and can be accessed by the inner class.

    Rate this question:

  • 7. 

    Consider s1 and s2 are sets. Which of the following options gives the exact meaning of the method call s1.retainAll(s2)?

    • A.

      Transforms s1 into the union of s1 and s2

    • B.

      Transforms s1 into the intersection of s1 and s2.

    • C.

      Returns true if s2 is a subset of s1

    • D.

      Transforms s1 into the (asymmetric) set difference of s1 ands2

    • E.

      Copies elements from s2 to s1

    Correct Answer
    B. Transforms s1 into the intersection of s1 and s2.
    Explanation
    The method call s1.retainAll(s2) transforms s1 into the intersection of s1 and s2. This means that after the method call, s1 will only contain the elements that are present in both s1 and s2. Any elements that are not present in s2 will be removed from s1.

    Rate this question:

  • 8. 

    Consider the following scenario: A Chat application written in Java, currently works with a general room facility, where the messages posted by the logged user are displayed. A common synchronized object is ued to Queue up the messages received from the users. Now, the application needs additional feature called personal messaging, that enables the user to make one-to-one communication. Which of the following helps to implement the requirement?

    • A.

      A new synchronized object need to be created for every oneto-one personal messaging request from the user

    • B.

      The personal messaging feature cannot be added when thereis a general room facility

    • C.

      A part of the synchronized object that already exists for thegeneral room can be used

    • D.

      Just two more threads need to be created at the user end

    Correct Answer
    A. A new synchronized object need to be created for every oneto-one personal messaging request from the user
    Explanation
    In order to implement the requirement of personal messaging in the chat application, a new synchronized object needs to be created for every one-to-one personal messaging request from the user. This is because personal messaging requires a separate queue or container to store and manage the messages exchanged between two users privately. By creating a new synchronized object for each personal messaging request, the application can ensure that the messages are properly synchronized and delivered between the intended users without interfering with the general room facility.

    Rate this question:

  • 9. 

    Under which of the following scenarios a checked exception is thrown? (Choose 2)

    • A.

      5th element of an array is accessed, whose size is 3

    • B.

      A file that actually does not exist, is opened for reading

    • C.

      An attempt to connect to the database is made but failed.

    • D.

      Length() method is called on a String object, that is assignedto null

    • E.

      Given username and password is checked with database andfound invalid

    Correct Answer(s)
    B. A file that actually does not exist, is opened for reading
    C. An attempt to connect to the database is made but failed.
    Explanation
    In the given question, the correct answer is "A file that actually does not exist, is opened for reading" and "An attempt to connect to the database is made but failed". In both scenarios, a checked exception is thrown. When a file that does not exist is opened for reading, the system throws a FileNotFoundException, which is a checked exception. Similarly, when an attempt to connect to the database fails, a SQLException is thrown, which is also a checked exception.

    Rate this question:

  • 10. 

    Which of the following statement is true?

    • A.

      To call the sleep() method, a thread must own the lock of theobject which the call is to be made.

    • B.

      To call the join() method, a thread must own the lock of theobject on which the call is to be made

    • C.

      To call the wait() method, a thread must own the lock of theobject on which the call is to be made.

    • D.

      To call the yield() method, a thread must own the lock of theobject on which the call is to be made.

    • E.

      To call the wait() method, a thread must own the lock of thecurrent thread.

    Correct Answer
    C. To call the wait() method, a thread must own the lock of theobject on which the call is to be made.
    Explanation
    The correct answer is that to call the wait() method, a thread must own the lock of the object on which the call is to be made. The wait() method is used for thread synchronization and is typically called within a synchronized block or method. When a thread calls wait(), it releases the lock on the object it is currently synchronized on, allowing other threads to acquire the lock and execute their synchronized code. The thread will remain in a waiting state until another thread notifies it by calling the notify() or notifyAll() method on the same object, allowing it to reacquire the lock and continue execution.

    Rate this question:

  • 11. 

    Consider the following code: class Animal { public String noise() { return "noise"; } } class Dog extends Animal { public String noise() { return "bark"; } } class Cat extends Animal { public String noise() { return "meow"; } } class MakeNoise { public static void main(String args[]) { Animal animal = new Dog(); Cat cat = (Cat)animal; System.out.println(cat.noise()); } } Which of the following option will be the output of the above code snippet?

    • A.

      Noise

    • B.

      Bark

    • C.

      Meow

    • D.

      Compilation fails

    • E.

      An exception is thrown at runtime

    Correct Answer
    D. Compilation fails
    Explanation
    The code snippet will not compile because there is a type mismatch in the assignment statement "Cat cat = (Cat)animal;". The variable "animal" is of type Animal and is referring to an instance of Dog, which is a subclass of Animal. Trying to assign this instance to a variable of type Cat, which is also a subclass of Animal, will result in a compilation error.

    Rate this question:

  • 12. 

    Consider the following code: public class GetArray { public static void main(String args[]) { float invt[][]; float[] prct, grts[]; float[][] sms, hms[]; (// Insert statement1 here) (// Insert statement2 here)  (// Insert statement3 here) } } Which of the following listed statements can be inserted at the above commented lines (// Insert statement1 here, // Insert statement2 here, // Insert statement3 here) to make the program to compile without errors? (Choose 3)

    • A.

      Grts = new float[1][4];

    • B.

      Invt = grts;

    • C.

      Hms = new float[2][5];

    • D.

      Invt = new float[4][2];

    • E.

      Grts = new float[1];

    Correct Answer(s)
    A. Grts = new float[1][4];
    B. Invt = grts;
    D. Invt = new float[4][2];
  • 13. 

    Consider the following code: public class SwitchCase { public static void main(String args[]) { int x = 10; switch(x) { case 10: System.out.println("10"); case 10: System.out.println("10"); case 20: System.out.println("20"); default: System.out.println("30"); } } } Which of the following will be the output for the above program?

    • A.

      101020

    • B.

      1020

    • C.

      1010

    • D.

      Compilation Error

    • E.

      3014

    Correct Answer
    D. Compilation Error
    Explanation
    The code will result in a compilation error because the case "10" is repeated twice in the switch statement. Each case label in a switch statement must be unique.

    Rate this question:

  • 14. 

    Which of the following is the process of creating a new class from an existing class?

    • A.

      Polymorphism

    • B.

      Abstraction

    • C.

      Inheritance

    • D.

      Reusability

    Correct Answer
    C. Inheritance
    Explanation
    Inheritance is the process of creating a new class from an existing class. It allows the new class to inherit the properties and behaviors of the existing class, known as the parent class or base class. The new class, known as the child class or derived class, can then add or modify these inherited properties and behaviors as needed. This enables code reusability and promotes the concept of hierarchy in object-oriented programming.

    Rate this question:

  • 15. 

    Consider the following code snippet: String deepak = "Did Deepak see bees? Deepak did."; Which of the following options will give the output for the method call deepak.charAt(10)?

    • A.

      None of the listed options

    • B.

      S

    • C.

      H

    • D.

      Space

    Correct Answer
    D. Space
    Explanation
    The correct answer is "space". In the given code snippet, the string "deepak" is assigned the value "Did Deepak see bees? Deepak did.". The method call deepak.charAt(10) will return the character at index 10 of the string, which is a space character.

    Rate this question:

  • 16. 

    Consider the following code: package com.java.test; public class A { public void m1() {System.out.print("A.m1, ");} protected void m2() {System.out.print("A.m2, ");} private void m3() {System.out.print("A.m3, ");} void m4() {System.out.print("A.m4, ");} } class B { public static void main(String[] args) { A a = new A(); a.m1(); // 1 a.m2(); // 2 a.m3(); // 3 a.m4(); // 4 } } Assume that both of the above classes are stored in a single source file called 'A.java'. Which of the following gives the valid output of the above code?

    • A.

      Prints: A.m1, A.m2, A.m3, A.m4,

    • B.

      Compile-time error at 3.

    • C.

      Compile-time error at 4.

    • D.

      Compile-time error at 2.

    • E.

      Compile-time error at 1.

    Correct Answer
    B. Compile-time error at 3.
    Explanation
    The code will give a compile-time error at line 3 because the method m3() in class A is declared as private. Private methods can only be accessed within the same class and cannot be accessed by objects of other classes.

    Rate this question:

  • 17. 

    From a Collection object c, another Collection object needs to be created. It should contain the same elements in the same order as that of source object c, but with all duplicates eliminated. Which of the following options provide the valid code to accomplish the above given scenario?

    • A.

      New HashSet(c);

    • B.

      All of the listed options

    • C.

      New LinkedTreeSet(c);

    • D.

      New LinkedHashSet(c);

    Correct Answer
    D. New LinkedHashSet(c);
    Explanation
    The correct answer is "new LinkedHashSet(c)" because LinkedHashSet is a collection that maintains the insertion order of elements and eliminates duplicates. This means that when creating a new LinkedHashSet object with the source object c, it will contain the same elements in the same order as c, but without any duplicates. HashSet and LinkedTreeSet do not maintain the insertion order, so they would not fulfill the requirement of having the same order as the source object.

    Rate this question:

  • 18. 

    From JDK 1.6, which of the following interfaces is also implemented by java.util.TreeSet class?

    • A.

      NavigableSet

    • B.

      NavigableList

    • C.

      NavigableMap

    • D.

      Deque

    Correct Answer
    A. NavigableSet
    Explanation
    From JDK 1.6, the java.util.TreeSet class also implements the NavigableSet interface. This interface extends the SortedSet interface and provides additional navigation methods for accessing and manipulating the elements in a sorted set. The NavigableSet interface allows elements to be accessed in ascending or descending order, and provides methods for finding the closest elements to a given value, as well as methods for retrieving subsets of the set based on a range of values. Therefore, the correct answer is NavigableSet.

    Rate this question:

  • 19. 

    Which of the following modifier cannot be applied to the declaration of a field (member of a class)?

    • A.

      Public

    • B.

      Final

    • C.

      Abstract

    • D.

      Private

    • E.

      Protected

    Correct Answer
    C. Abstract
    Explanation
    The modifier "abstract" cannot be applied to the declaration of a field. The "abstract" modifier is used to declare abstract methods and abstract classes, which cannot be instantiated. Fields, on the other hand, are variables that hold data and do not have the concept of being abstract. Therefore, it is not possible to declare a field as abstract.

    Rate this question:

  • 20. 

    Which of the following statements are correct regarding Instance Block?(Choose 3)

    • A.

      A class can have more than one instance block

    • B.

      An instance block cannot initialise the class members

    • C.

      Instance blocks are executed only when the instances arecreated from main() method of that class

    • D.

      Instance blocks are executed before constructors

    • E.

      Instance blocks are executed for every created instance

    Correct Answer(s)
    A. A class can have more than one instance block
    D. Instance blocks are executed before constructors
    E. Instance blocks are executed for every created instance
    Explanation
    A class can have more than one instance block: This statement is correct because a class can have multiple instance blocks that are executed in the order they are defined.

    Instance blocks are executed before constructors: This statement is correct because instance blocks are executed before any constructors are invoked during the object creation process.

    Instance blocks are executed for every created instance: This statement is correct because instance blocks are executed every time a new instance of the class is created, ensuring that the block's code is executed for each object.

    Rate this question:

  • 21. 

    Which of the following is the correct syntax for Annotation declaration?

    • A.

      Interface author{@String name(),String date()}

    • B.

      @interface author{@String name();@String date();}

    • C.

      Interface author{String name(),String date()}

    • D.

      Interface @author{String name(),String date()}

    • E.

      @interface author{String name();String date();}

    Correct Answer
    E. @interface author{String name();String date();}
    Explanation
    The correct syntax for Annotation declaration is "@interface author{String name();String date();}". This syntax defines an annotation interface named "author" with two methods, "name()" and "date()", both of which return a String type.

    Rate this question:

  • 22. 

    Consider the following code: class Resource { } class UserThread extends Thread { public Resource res; public void run() { try { synchronized(res) { System.out.println("Planet"); res.wait(); Thread.sleep(1000); res.notify(); System.out.println("Earth"); } } catch(InterruptedException e) { } } } public class StartUserThreads { public static void main(String[] args) { Resource r = new Resource(); UserThread ut1 = new UserThread(); ut1.res = r; UserThread ut2 = new UserThread(); ut2.res = r; ut1.start(); ut2.start(); } } Which of the following will give the correct output for the above code?

    • A.

      Runtime Error "IllegalThreadStateException"

    • B.

      Compile-time Error

    • C.

      Prints the following output 2 times: Planet (waits for 1000 milli seconds) Earth

    • D.

      Prints the following output: Planet Planet (get into long wait. Never ends)

    • E.

      Prints the following output 1 time: Planet (waits for 1000 milli seconds) Earth

    Correct Answer
    D. Prints the following output: Planet Planet (get into long wait. Never ends)
    Explanation
    The correct answer is "Prints the following output: Planet Planet (get into long wait. Never ends)". This is because both UserThread objects, ut1 and ut2, are sharing the same Resource object, r. When the synchronized block is executed in the run() method, the first thread acquires the lock on the Resource object and prints "Planet". Then, it calls the wait() method, which releases the lock and waits indefinitely until it is notified. Meanwhile, the second thread also acquires the lock and prints "Planet" before calling the wait() method. Since neither thread is being notified, they both remain in a waiting state and the program does not terminate.

    Rate this question:

  • 23. 

    Which of the following options gives the relationship between a Spreadsheet Object and Cell Objects?

    • A.

      Polymorphism

    • B.

      Association

    • C.

      Inheritance

    • D.

      Aggregation

    • E.

      Persistence

    Correct Answer
    D. Aggregation
    Explanation
    Aggregation is the correct answer because it represents a relationship between a whole object (Spreadsheet) and its parts (Cell Objects). In an aggregation relationship, the parts can exist independently of the whole object, and multiple parts can be associated with the same whole object. This relationship accurately describes the connection between a Spreadsheet Object and Cell Objects, as cells are individual components that make up a spreadsheet and can exist and function independently.

    Rate this question:

  • 24. 

    Consider the following program: class joy extends Exception { } class smile extends joy { } interface happy { void a() throws smile; void z() throws smile; } class one extends Exception { } class two extends one { } abstract class test { public void a()throws one { } public void b() throws one { } } public class check extends test { public void a() throws smile { System.out.println("welcome"); throw new smile(); } public void b() throws one { throw new two(); } public void z() throws smile { throw new smile(); } public static void main(String args[]) { try { check obj=new check(); obj.b(); obj.a(); obj.z(); } catch(smile s) { System.out.println(s); }catch(two t) { System.out.println(t.getClass()); }catch(one o) { System.out.println(o); }catch(Exception e) { System.out.println(e); } } } What will be the output of the above program?

    • A.

      Throws a compile time exception as overridden method a() does not throw exception smile

    • B.

      Welcome class two

    • C.

      Two

    • D.

      Throws a compile time exception as overridden method z() does not throw exception smile

    • E.

      Class two

    Correct Answer
    A. Throws a compile time exception as overridden method a() does not throw exception smile
    Explanation
    The output of the program will be "throws a compile time exception as overridden method a() does not throw exception smile". This is because the method "a()" in the "check" class overrides the method "a()" in the "test" class, but it throws a different exception (smile) which is not declared in the method signature of the overridden method. Therefore, it will result in a compile-time error.

    Rate this question:

  • 25. 

    Consider the following code snippet: public class TasteIt{ public void show() { System.out.println("one"); } public static void main(String[] args) { TasteIt t = new TasteIt() { public void show() { System.out.println("two"); super.show(); } }; t.show(); } } Which of the following option will be the output for the above code snippet?

    • A.

      One two

    • B.

      Two one

    • C.

      Compilation fails. Cannot use super keyword inside an anonymous class

    • D.

      Runtime exception. Cannot find the super class version of show() method

    Correct Answer
    B. Two one
    Explanation
    The code snippet creates an anonymous class that extends the "TasteIt" class and overrides the "show" method. Inside the overridden "show" method, it first prints "two" and then calls the "show" method of the superclass using the "super.show()" statement. Therefore, the output will be "two one".

    Rate this question:

  • 26. 

    Consider the following code snippet: public class Welcome { String title; int value; public Welcome() { title += " Planet"; } public Welcome(int value) { this.value = value; title = "Welcome"; Welcome(); } public static void main(String args[]) { Welcome t = new Welcome(); System.out.println(t.title); } } Which of the following options will be the output for the above code snippet?

    • A.

      Welcome

    • B.

      Welcome Planet

    • C.

      Compilation fails

    • D.

      The code runs with no output

    • E.

      Welcome Planet 5

    Correct Answer
    C. Compilation fails
    Explanation
    The code will fail to compile because there is a syntax error in the line "Welcome();". The constructor cannot be called directly like a method.

    Rate this question:

  • 27. 

    Consider the following program: public class Exp3 { public static void main(String[] args) { try { if (args.length == 0) return; System.out.println(args[0]); } finally { System.out.println("The end"); } } } Which of the following options are true regarding the output of the above program? (Choose 2)

    • A.

      If run with no arguments, the program will print "The end"

    • B.

      If run with one argument, the program will print the given argument followed by "The end"

    • C.

      If run with one argument, the program will simply print the given argument

    • D.

      The program will throw an ArrayIndexOutOfBoundsException

    • E.

      If run with no arguments, the program will produce no output

    Correct Answer(s)
    A. If run with no arguments, the program will print "The end"
    B. If run with one argument, the program will print the given argument followed by "The end"
    Explanation
    The program uses a try-finally block. If the program is run with no arguments, it will return and not execute any further code, causing it to print "The end". If the program is run with one argument, it will print the given argument and then execute the finally block, printing "The end" afterwards. Therefore, the correct options are: If run with no arguments, the program will print "The end", and If run with one argument, the program will print the given argument followed by "The end".

    Rate this question:

  • 28. 

    Consider the following code snippets: class GC2 { public GC2 getIt(GC2 gc2) { return gc2; } public static void main(String a[]) { GC2 g = GC2(); GC2 c = GC2(); c = g.getIt(c); } } How many objects are eligible for Garbage Collection?

    • A.

      Four

    • B.

      One

    • C.

      None of the objects are eligible

    • D.

      Two

    • E.

      Three

    Correct Answer
    C. None of the objects are eligible
    Explanation
    In the given code, two objects of the class GC2 are created using the statements "GC2 g = new GC2();" and "GC2 c = new GC2();". The object referenced by "g" is then assigned to the variable "c" using the method "getIt(c)". Since both objects are still referenced by variables "g" and "c", none of the objects are eligible for garbage collection.

    Rate this question:

  • 29. 

    Consider the following scenario: A given String needs to be searched, in text file, and report the number of occurences with corresponding line numbers. Which of the following stream classes can be used to implement the above requirement?

    • A.

      FileInputStream and PipedInputStream

    • B.

      FileInputStream and InputStreamReader

    • C.

      InputStreamReader and FilterInputStream

    • D.

      FileInputStream and SearchInputStream

    • E.

      FileReader and BufferedReader

    Correct Answer
    E. FileReader and BufferedReader
    Explanation
    The FileReader and BufferedReader classes can be used to implement the given requirement. FileReader is used to read characters from a file, while BufferedReader is used to read text from a character-input stream. By using these classes, we can read the text file line by line and search for the given String. The BufferedReader class provides a convenient method, readLine(), which reads a line of text. We can iterate through the lines, check for the occurrence of the given String, and keep track of the line numbers where it is found.

    Rate this question:

  • 30. 

    Given the following method in an application: 1. public String setFileType( String fname ){ 2. int p = fname.indexOf( '.' ); 3. if( p > 0 ) fname = fname.substring( 0,p ); 4. fname += ".TXT"; 5. return fname; 6. } and given that another part of the class has the following code 7. String TheFile = "Program.java"; 8. File F = new File( setFileType( TheFile ) ); 9. System.out.println( "Created " + TheFile ); Which of the following will be the output for the statement in line 9?

    • A.

      Created Program.txt

    • B.

      Created Program

    • C.

      Created Program.java

    • D.

      Created Program.java.txt

    Correct Answer
    C. Created Program.java
    Explanation
    The output for the statement in line 9 will be "Created Program.java". This is because the setFileType method takes a filename as input and removes the file extension if it exists, then appends ".TXT" to the filename. In line 8, the setFileType method is called with "Program.java" as the input, so the filename remains unchanged. Therefore, in line 9, the output will be "Created Program.java".

    Rate this question:

  • 31. 

    Consider the following code snippet: import java.io.*; public class IOCode1 { public static void main(String args[]) throws IOException { BufferedReader br1 = new BufferedReader( new InputStreamReader(System.in)); BufferedWriter br2 = new BufferedWriter( new OutputStreamWriter(System.out)); String line = null; while( (line = br1.readLine()) != null ) { br2.write(line); br2.flush(); } br1.close(); br2.close(); } } What will be the output for the above code snippet?

    • A.

      Reads the text from keyboard line by line and prints the same to the console on pressing ENTER key at the end of every line, then the same is flushed (erased) from the console.

    • B.

      Reads the text from keyboard line by line and prints the same to the console on pressing ENTER key at the end of every line

    • C.

      Reads the text from keyboard and prints the same to the console on pressing Ctrl Z, flushes (erases) the same from the console.

    • D.

      Reads the text from keyboard and prints the same to the console on pressing Ctrl Z

    • E.

      Reads the text from keyboard character by character and prints the same to the console on typing every character.

    Correct Answer
    B. Reads the text from keyboard line by line and prints the same to the console on pressing ENTER key at the end of every line
    Explanation
    The code snippet uses BufferedReader to read input from the keyboard line by line using the readLine() method. It then uses BufferedWriter to write the input to the console using the write() method. The flush() method is called to ensure that the output is immediately visible on the console. The code continues reading and writing input until the input is null, indicating the end of the input. Therefore, the output will be the text entered from the keyboard, with each line printed to the console when the ENTER key is pressed.

    Rate this question:

  • 32. 

    Consider the following code: public class WrapIt { public static void main(String[] args) { new WrapIt().testC('a'); } public void testC(char ch) { Integer ss = new Integer(ch); Character cc = new Character(ch); if(ss.equals(cc)) System.out.print("equals "); if(ss.intValue()==cc.charValue()) { System.out.println("EQ"); } } } Which of the following gives the valid output for the above code?

    • A.

      Compile-time error: Integer wrapper cannot accept char type

    • B.

      Prints: EQ

    • C.

      Compile-time error: Wrapper types cannot be compared using equals

    • D.

      Prints: equals EQ

    • E.

      Prints: equals

    Correct Answer
    B. Prints: EQ
    Explanation
    The code initializes an Integer object with the value of the char variable 'ch'. It also initializes a Character object with the same value. The code then compares the two objects using the equals() method. Since the Integer and Character classes both inherit from the Object class, the equals() method can be used to compare them. The code also compares the integer value of the Integer object with the character value of the Character object using the intValue() and charValue() methods respectively. If the integer value and character value are equal, the code prints "EQ". Therefore, the valid output for the above code is "EQ".

    Rate this question:

  • 33. 

    Which of the following statements are true? (choose 2)

    • A.

      A program can suggest that garbage collection be performed but not force it

    • B.

      An object becomes eligible for garbage collection when all references denoting it are set to null

    • C.

      None of the listed options

    • D.

      Garbage collection is platform independent

    • E.

      The automatic garbage collection of the JVM prevents programs from ever running out of memory

    Correct Answer(s)
    A. A program can suggest that garbage collection be performed but not force it
    B. An object becomes eligible for garbage collection when all references denoting it are set to null
    Explanation
    A program can suggest that garbage collection be performed but not force it. This means that a program can make a recommendation or request for garbage collection to be done, but it cannot directly control or enforce the execution of the garbage collection process.

    An object becomes eligible for garbage collection when all references denoting it are set to null. This means that when there are no more references to an object in the program, it is considered eligible for garbage collection. Once all references are set to null, the object is no longer accessible and can be safely removed by the garbage collector.

    Rate this question:

  • 34. 

    Consider a List based object L, with size of 10 elements e, and the following two lines of code: L.add("e"); L.remove("e"); Which of the following options gives the status about the List object L after executing the above two lines of code?

    • A.

      New elements are added and old ones are taken out but size is increasing

    • B.

      New elements are added and old ones are taken out but there will be a change in size

    • C.

      No change because we are adding and deleting the same element

    • D.

      New elements are added and old ones are taken out but no change in size

    • E.

      New elements can be added but cannot be removed

    Correct Answer
    D. New elements are added and old ones are taken out but no change in size
    Explanation
    The code first adds the element "e" to the list using the L.add("e") line. Then, it removes the element "e" from the list using the L.remove("e") line. Since the element added and removed is the same ("e"), there will be no change in the size of the list. Therefore, the correct option is "New elements are added and old ones are taken out but no change in size".

    Rate this question:

  • 35. 

    Consider the following code: class A { public void method(Object object) { System.out.println("Object"); } public void method(String string) { System.out.println("String"); } public static void main(String args[]) { new A().method(null); } } Which of the following options will be the output for the above code?

    • A.

      Compilation Error 'Cannot pass null as method arguments'

    • B.

      Prints: String

    • C.

      Throws NullPointerException at runtime

    • D.

      Prints: Object

    Correct Answer
    B. Prints: String
    Explanation
    The output for the above code will be "Prints: String" because when the method is called with null as the argument, the compiler will choose the most specific method that matches the argument type. Since String is more specific than Object, the method with String parameter will be called and "String" will be printed.

    Rate this question:

  • 36. 

    Consider the following code snippet: class MyClass { int myValue; @Override public boolean equals(Object o1, Object o2){ MyClass mc1=(MyClass) o1; MyClass mc1=(MyClass) o2; if(mc1.myValue==mc2.myValue) return true; return false; } } what is the correct output of the above code snippet?

    • A.

      ClassCastExceprion will be thrown.

    • B.

      @Override cannot be used for equals() method.

    • C.

      Compile error: class doesn't override a method from it's superclass @Override.

    • D.

      Program compiles sucessfully and executes.

    Correct Answer
    C. Compile error: class doesn't override a method from it's superclass @Override.
    Explanation
    The correct answer is "Compile error: class doesn't override a method from its superclass @Override." This is because the equals() method in the code snippet is not correctly overriding the equals() method from the Object class. The correct signature for the equals() method should be "public boolean equals(Object o)".

    Rate this question:

  • 37. 

    Consider the following program: import java.io.*; public class SteppedTryCatch { public static void main(String[] args) { try { try { try { // Line 1 } catch(Exception e3) { System.out.println("Exception 1"); // Line 2 } } catch(IOException e2) { System.out.println("Exception 2"); // Line 3 } } catch(FileNotFoundException e1) { System.out.println("Exception 3"); } } } You need to make the above program to print the output as Exception 1 Exception 2 Exception 3 Which of the following when substituted in place of commented lines (// Line 1, Line 2 and Line 3) produce the desired output?

    • A.

      The code is wrong. Exceptions should be caught in reversed hierarchy order.

    • B.

      Line 1 : throw new Exception(); Line 2 : throw new IOException(); Line 3 : throw new FileNotFoundException();

    • C.

      Line 1 : throw new IOException(); Line 2 : throw new FileNotFoundException(); Line 3 : throw new Exception();

    • D.

      Line 1 : throw new IOException(); Line 2 : throw new IOException(); Line 3 : throw new IOException();

    • E.

      Line 1 : throw new FileNotFoundException(); Line 2 : throw new IOException(); Line 3 : throw new Exception();

    Correct Answer
    B. Line 1 : throw new Exception(); Line 2 : throw new IOException(); Line 3 : throw new FileNotFoundException();
    Explanation
    The desired output can be achieved by throwing exceptions in the reverse hierarchy order. This means that the most specific exception (Exception) should be thrown first, followed by less specific exceptions (IOException and FileNotFoundException). Therefore, the correct answer is Line 1: throw new Exception(); Line 2: throw new IOException(); Line 3: throw new FileNotFoundException();.

    Rate this question:

  • 38. 

    Consider the following code: class MyThread extends Thread { MyThread() { System.out.print(" MyThread"); } public void run() { System.out.print(" queen"); } public void run(String s) { System.out.print(" jack"); } } public class TestThreads { public static void main (String [] args) { Thread t = new MyThread() { public void run() { System.out.print(" king"); } }; t.start(); } } Which of the followingl gives the correct valid output for the above code?

    • A.

      Queen king

    • B.

      King queen

    • C.

      Compilation fails.

    • D.

      MyThread king

    • E.

      MyThread queen

    Correct Answer
    D. MyThread king
    Explanation
    The code defines a class MyThread that extends the Thread class. The constructor of MyThread class prints " MyThread" when an object of MyThread is created. The run method of MyThread class is overridden to print "queen". In the main method of TestThreads class, a new object of MyThread is created and its run method is overridden to print "king". Finally, the start method is called on the object of MyThread, which starts the execution of the thread. Therefore, the correct output is "MyThread king".

    Rate this question:

  • 39. 

    Consider the following code: public class Choco { Choco() { System.out.print("Choco"); } class Bar { Bar() { System.out.print("bar"); } public void go() { System.out.print("sweet"); } } public static void main(String[] args) { Choco c = new Choco(); c.makeBar(); } void makeBar(){ // Insert code here } } Which of the following code snippet when substituted individually to the above commented line (// Insert code here) will give the following output? Chocobarsweet

    • A.

      Go();

    • B.

      New Choco(). new Bar().go();

    • C.

      (new Bar() {}).go();

    • D.

      New Bar().go();

    • E.

      New Choco().go();

    Correct Answer
    C. (new Bar() {}).go();
    Explanation
    The correct answer is "(new Bar() {}).go();". This code snippet creates a new instance of the inner class Bar using an anonymous inner class syntax and calls the go() method on it. This will output "Chocobarsweet" as desired.

    Rate this question:

  • 40. 

    Which of the following are interfaces in JDBC API?(choose 3)

    • A.

      CallableStatement

    • B.

      DriverManager

    • C.

      Connection

    • D.

      Statement

    • E.

      SQLWarning

    Correct Answer(s)
    A. CallableStatement
    C. Connection
    D. Statement
    Explanation
    The correct answer is CallableStatement, Connection, and Statement. These three options are interfaces in the JDBC API. CallableStatement is used to execute SQL stored procedures, Connection is used to establish a connection with a database, and Statement is used to execute SQL statements. DriverManager and SQLWarning are not interfaces in the JDBC API.

    Rate this question:

  • 41. 

    Consider the following code: public class Code17 { public static void main(String args[]) { new Code17(); } { System.out.print("Planet "); } { System.out.print("Welcome "); } } Which of the following will be the valid output for the above code?

    • A.

      Compiles and Executes with no output

    • B.

      Welcome Planet

    • C.

      Planet Welcome

    • D.

      Planet

    • E.

      Compilation Error

    Correct Answer
    C. Planet Welcome
    Explanation
    The code creates an instance of the Code17 class and calls its constructor in the main method. The constructor contains two blocks of code that print "Planet " and "Welcome " respectively. Therefore, the valid output for the code will be "Planet Welcome".

    Rate this question:

  • 42. 

    Consider the following code: 1. class Test { 2. public static void main(String args[]) { 3. double d = 12.3; 4. Dec dec = new Dec(); 5. dec.dec(d); 6. System.out.println(d); 7. } 8. } 9. class Dec{ 10. public void dec(double d) { d = d - 2.0d; } 11. } Which of the following gives the correct value printed at line 6?

    • A.

      Prints: -2.0

    • B.

      Prints: 10.3

    • C.

      Prints: 12.3

    • D.

      Prints: 0.0

    Correct Answer
    C. Prints: 12.3
    Explanation
    The correct value printed at line 6 is "Prints: 12.3". In the code, a double variable "d" is initialized with the value 12.3. Then, an instance of the "Dec" class is created and the "dec" method is called, passing the "d" variable as an argument. Inside the "dec" method, the value of "d" is subtracted by 2.0, but this does not affect the original value of "d" in the main method. Therefore, when the value of "d" is printed at line 6, it still retains its original value of 12.3.

    Rate this question:

  • 43. 

    All kinds of looping constructs designed using while loop can also be constructed using do-while loop. State True or False.

    • A.

      True

    • B.

      False

    Correct Answer
    B. False
    Explanation
    The statement is false because while loops and do-while loops have different structures and behaviors. While loops first check the condition before executing the loop, whereas do-while loops execute the loop at least once before checking the condition. Therefore, not all looping constructs designed using while loops can be constructed using do-while loops.

    Rate this question:

  • 44. 

    ResultSet programming is more efficient, where there are frequent insertions, updations and deletions. State True or False.

    • A.

      True

    • B.

      False

    Correct Answer
    B. False
    Explanation
    The given statement is false. ResultSet programming is not more efficient for frequent insertions, updates, and deletions. ResultSet is used for retrieving and manipulating data from a database, but it is not optimized for frequent modifications. For frequent insertions, updates, and deletions, other programming techniques like batch processing or direct SQL statements are more efficient.

    Rate this question:

  • 45. 

    Consider the following code snippet: import java.util.*; import java.text.*; public class TestCol5 { public static void main(String[] args) { String dob = "17/03/1981"; // Insert Code here } } Which of the following code snippets, when substituted to (//Insert Code here) in the above program, will convert the dob from String to Date type?

    • A.

      DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); try { Date d = df.parse(dob); } catch(ParseException pe) { }

    • B.

      GregorianCalendar g = new GregorianCalendar(dob); Date d = g.getDate();

    • C.

      Date d = new Date(dob);

    • D.

      CalendarFormat cf = new SimpleCalendarFormat("dd/MM/yyyy"); try { Date d = cf.parse(dob); } catch(ParseException pe) { }

    • E.

      Calendar c = new Calendar(dob); Date d = g.getDate();

    Correct Answer
    A. DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); try { Date d = df.parse(dob); } catch(ParseException pe) { }
    Explanation
    The correct answer is the first option:

    DateFormat df = new SimpleDateFormat("dd/MM/yyyy"); try { Date d = df.parse(dob); } catch(ParseException pe) { }

    This code snippet uses the SimpleDateFormat class to specify the format of the date string "dob" as "dd/MM/yyyy". It then uses the parse() method of the SimpleDateFormat class to convert the string into a Date object. If any exception occurs during the parsing process, it is caught and handled in the catch block.

    Rate this question:

Quiz Review Timeline +

Our quizzes are rigorously reviewed, monitored and continuously updated by our expert board to maintain accuracy, relevance, and timeliness.

  • Current Version
  • Mar 21, 2023
    Quiz Edited by
    ProProfs Editorial Team
  • Apr 27, 2011
    Quiz Created by
    Unrealvicky
Back to Top Back to top
Advertisement
×

Wait!
Here's an interesting quiz for you.

We have other quizzes matching your interest.