1.
Which of the following are uses of Object class?(Choose 3)
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.
2.
Which of the following options are true for StringBuffer class?(choose 3)
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.
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)
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.
4.
Which of the following are true regarding PreparedStatement?(choose 3)
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.
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?
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.
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
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.
7.
Consider s1 and s2 are sets. Which of the following options gives the exact meaning of the method call s1.retainAll(s2)?
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.
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?
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.
9.
Under which of the following scenarios a checked exception is thrown? (Choose
2)
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.
10.
Which of the following statement is true?
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.
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?
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.
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)
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?
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.
14.
Which of the following is the process of creating a new class from an existing class?
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.
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)?
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.
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?
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.
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?
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.
18.
From JDK 1.6, which of the following interfaces is also implemented by java.util.TreeSet class?
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.
19.
Which of the following modifier cannot be applied to the declaration of a field (member of a class)?
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.
20.
Which of the following statements are correct regarding Instance Block?(Choose 3)
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.
21.
Which of the following is the correct syntax for Annotation declaration?
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.
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?
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.
23.
Which of the following options gives the relationship between a Spreadsheet
Object and Cell Objects?
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.
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?
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.
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?
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".
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?
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.
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)
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".
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?
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.
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?
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.
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?
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".
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?
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.
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?
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".
33.
Which of the following statements are true? (choose 2)
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.
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?
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".
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?
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.
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?
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)".
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?
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();.
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?
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".
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
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.
40.
Which of the following are interfaces in JDBC API?(choose 3)
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.
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?
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".
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?
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.
43.
All kinds of looping constructs designed using while loop can also be
constructed using do-while loop.
State True or 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.
44.
ResultSet programming is more efficient, where there are frequent insertions,
updations and deletions. State True or 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.
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?
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.