# Ocjp Mock Test - I

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.
| By Marikannan
M
Marikannan
Community Contributor
Quizzes Created: 1 | Total Attempts: 750
Questions: 46 | Attempts: 751

Settings

INTRODUCTION TO OOPS
INTRODUCTION TO JAVA AND SDE
LANGUAGE FUNDAMENTALS AND OPERATORS

• 1.

### 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: 12.3

• B.

Prints: -2.0

• C.

Prints: 10.3

• D.

Prints: 0.0

A. Prints: 12.3
Explanation
The code initializes a variable "d" with the value 12.3. It then creates an instance of the "Dec" class and calls the "dec" method on that instance, passing in the value of "d". Inside the "dec" method, the value of "d" is subtracted by 2.0. However, this does not affect the original value of "d" outside the method. Therefore, when the value of "d" is printed at line 6, it still retains its original value of 12.3.

Rate this question:

• 2.

### Consider the following code: public class LabeledBreak2 { public static void main(String args[]) { loop: for(int j=0; j<2; j++) { for(int i=0; i<10; i++) { if(i == 5) break loop; System.out.print(i + " "); } } } } Which of the following will be the output for the above code?

• A.

0 1 2 3 4 5

• B.

Indefinite Loop

• C.

1 2 3 4 5

• D.

0 1 2 3 4

• E.

0 1 2 3 4 0 1 2 3 4

D. 0 1 2 3 4
Explanation
The code uses nested loops. The outer loop runs twice and the inner loop runs 10 times. Inside the inner loop, when the value of i is 5, the statement "break loop" is executed. This causes the program to break out of both loops and continue with the rest of the code after the loops. Therefore, the output of the code will be 0 1 2 3 4, as it will print the values of i before it reaches 5.

Rate this question:

• 3.

### Consider the following scenario: Real Chocos Private Limited deals in manufacturing variety of chocolates. This organization manufactures three varieties of chocolates. 1. Fruit Chocolates 2. Rum Chocolates 3. Milk Chocolates A software system needs to be built. Which of the following options identifies the Classes and Objects?

• A.

Class: Real Chocos Private Limited Objects: Chocolate

• B.

Class: Chocolate Objects: Fruit Chocolates, Rum Chocolates, Milk Chocolates

• C.

Class: Chocolate Objects: Milk Chocolates

• D.

Class: Fruit Chocolates Objects: Rum Chocolates

B. Class: Chocolate Objects: Fruit Chocolates, Rum Chocolates, Milk Chocolates
Explanation
The correct answer is Class: Chocolate, Objects: Fruit Chocolates, Rum Chocolates, Milk Chocolates. In this scenario, the organization Real Chocos Private Limited is the company or business entity, which would be represented by a class. The different varieties of chocolates (Fruit Chocolates, Rum Chocolates, Milk Chocolates) are the objects of the class Chocolate, as they are specific instances or examples of chocolates that the company manufactures.

Rate this question:

• 4.

### Consider the following code: class A { } class B extends A { } public class Code2 { public void method(A a) { System.out.println("A"); } public void method(B b) { System.out.println("B"); } public static void main(String args[]) { new Code2().method(new Object()); } } Which of the following will be the output for the above code?

• A.

Throws ClassCastException at runtime

• B.

Prints: B

• C.

Compilation Error 'Cannot find the symbol'

• D.

Prints: A

• E.

Return this.name.hashCode() == a.name.hashCode();

C. Compilation Error 'Cannot find the symbol'
Explanation
The code is trying to call the method "method" with an instance of the Object class as an argument. However, there is no method in the Code2 class that accepts an Object parameter. Therefore, the code will not compile and will result in a compilation error stating "Cannot find the symbol".

Rate this question:

• 5.

### Consider the following code: class Planet { } class Earth extends Planet { } public class WelcomePlanet { public static void welcomePlanet(Planet planet)  { if (planet instanceof Earth) { System.out.println("Welcome!"); }  else if (planet instanceof Planet)  { System.out.println("Planet!"); } else { System.exit(0); } } public static void main(String args[])  { WelcomePlanet wp = new WelcomePlanet(); Planet planet = new Earth(); welcomePlanet(planet); } } Which of the following will be the output of the above program?

• A.

An exception is thrown at runtime

• B.

Planet!

• C.

The code runs with no output

• D.

Welcome!

• E.

Compilation fails

D. Welcome!
Explanation
The output of the above program will be "Welcome!" because the object "planet" is an instance of the subclass Earth, and the if statement checks if it is an instance of Earth first. Since it is, the program will print "Welcome!". The else if statement is not executed because the if statement condition is already met.

Rate this question:

• 6.

### Consider the following code:  public class Code13 { public static void main(String... args)  { for(String s:args) System.out.print(s + ", "); System.out.println(args.length); } }  Which of the following will be the output if the above code is attempted to compile and execute?

• A.

Program compiles successfully and prints the passed arguments as comma separated values and finally prints the length of the arguments-list

• B.

Runtime Error: NoSuchMethodError

• C.

Variable arguments cannot be used with enhanced for-loop

• D.

Compilation Error: var-args cannot be used as arguments for main() method

A. Program compiles successfully and prints the passed arguments as comma separated values and finally prints the length of the arguments-list
Explanation
The code provided is a valid Java program that uses the varargs feature in the main method. Varargs allow a method to accept a variable number of arguments of a specified type. In this case, the main method accepts a variable number of String arguments.

When the code is executed, it will print all the passed arguments as comma-separated values using a for-each loop. Finally, it will print the length of the arguments list using the args.length property.

Therefore, the correct answer is "Program compiles successfully and prints the passed arguments as comma-separated values and finally prints the length of the arguments-list."

Rate this question:

• 7.

### Consider the following code: class UT1 { static byte m1() { final char c = 'u0001'; return c; } static byte m3(final char c) { return c; } public static void main(String[] args) { char c = 'u0003'; System.out.print(""+m1()+m3(c)); } } Which of the following gives the valid output of the above code?

• A.

Compile-time error

• B.

Prints: 13

• C.

Run-time error

• D.

Prints: 4

• E.

None of the listed options

A. Compile-time error
Explanation
The code will result in a compile-time error because the method m1() is declared to return a byte, but it is trying to return a char value. Since char is a larger data type than byte, it cannot be automatically converted.

Rate this question:

• 8.

### Which are all platform independent among the following? (Choose 3)

• A.

JAR Files

• B.

Java Virtual Machine (JVM)

• C.

Java Development Kit (JDK)

• D.

Java Class Files

• E.

Java Source Files

A. JAR Files
D. Java Class Files
E. Java Source Files
Explanation
JAR Files, Java Class Files, and Java Source Files are all platform independent. JAR Files are archives that contain compiled Java classes and other resources. Java Class Files are the compiled bytecode versions of Java source code that can be executed on any platform with a JVM. Java Source Files are the human-readable source code files that can be compiled into Java Class Files and run on any platform with a JVM. The JVM, JDK, and other platform-specific tools are not platform independent as they are specific to certain operating systems or architectures.

Rate this question:

• 9.

### Consider the following partial code: public class CreditCard { private String cardID; private Integer limit; public String ownerName; public void setCardInformation(String cardID, String ownerName, Integer limit) { this.cardID = cardID; this.ownerName = ownerName; this.limit = limit; } } Which of the following statement is True regarding the above given code?

• A.

The class is fully encapsulated

• B.

The setCardInformation method breaks encapsulation

• C.

The code demonstrates polymorphism

• D.

The cardID and limit variables break polymorphism

• E.

The ownerName variable breaks encapsulation

E. The ownerName variable breaks encapsulation
Explanation
The ownerName variable breaks encapsulation because it is declared as public, which means it can be accessed and modified directly from outside the class. In encapsulation, the variables should be declared as private and accessed through getter and setter methods to maintain data integrity and control access to the variables.

Rate this question:

• 10.

### Consider the following code: 1. public class DagRag { 2. public static void main(String [] args) { 3. 4. int [][] x = new int[2][4]; 5. 6. for(int y = 0; y < 2; y++) { 7. for(int z = 0; z < 4; z++) { 8. x[y][z] = z; 9. } 10. } 11. 12. dg: for(int g = 0; g < 2; g++) { 13. rg: for(int h = 0; h < 4; h++) { 14. System.out.println(x[g][h]); 15. 16. } 17. System.out.println("The end."); 18. 19. } 20. 21. } 22. } Which of the following code snippet when inserted at lines 15 and 18 respectively, will make the above program to generate the below output? 0 1 2 3 The end.

• A.

If(g==3) break rg; if(h==0) break dg;

• B.

If(h > 3) break dg; if(g > 0) break rg;

• C.

If(h==3) break rg; if(g==0) break dg;

• D.

If(h > 3) break dg; if(g > 0) break dg;

C. If(h==3) break rg; if(g==0) break dg;
Explanation
The code snippet "if(h==3) break rg; if(g==0) break dg;" will make the program generate the given output because it breaks out of the inner loop when h equals 3 and breaks out of the outer loop when g equals 0. This ensures that the inner loop iterates until h reaches 3 and the outer loop iterates only once.

Rate this question:

• 11.

### Consider the following code snippet: class Animal { String name; public boolean equals(Object o) { Animal a = (Animal) o; // Code Here } } class TestAnimal { public static void main(String args[]) { Animal a = new Animal(); a.name = "Dog"; Animal b = new Animal(); b.name = "dog"; System.out.println(a.equals(b)); } } Which of the following code snippets should be replaced for the comment line (//Code Here) in the above given code, to get the output as true?

• A.

Return this.name.equalsIgnoreCase(a.name);

• B.

Return this.name.equals(a.name);

• C.

Return super.equals(a);

• D.

Return this.name == a.name;

A. Return this.name.equalsIgnoreCase(a.name);
Explanation
The correct answer is "return this.name.equalsIgnoreCase(a.name);" because it compares the names of the two Animal objects (a and b) in a case-insensitive manner. By using the equalsIgnoreCase() method, it ignores any differences in capitalization and returns true if the names are the same regardless of case.

Rate this question:

• 12.

### Consider the following code snippet: public class TestString9 { public static void main(String st[]){ String s1 = "java"; String s2 = "java"; String s3 = "JAVA"; s2.toUpperCase(); s3.toUpperCase(); boolean b1 = s1==s2; boolean b2 = s1==s3; System.out.print(b1); System.out.print(" "+b2); } } What will be the output of the above code snippet?

• A.

False true

• B.

True true

• C.

True false

• D.

Runtime error

• E.

false false

C. True false
Explanation
The output of the above code snippet will be "true false". This is because the variables s1 and s2 both refer to the same string "java", so the comparison s1==s2 will return true. However, the variable s3 refers to a different string "JAVA" (with different case), so the comparison s1==s3 will return false.

Rate this question:

• 13.

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

• A.

Compilation fails

• B.

Welcome Planet 5

• C.

Welcome 5

• D.

Welcome Planet

• E.

The code runs with no output

C. Welcome 5
Explanation
The code will output "Welcome 5". This is because when the Welcome object is created with the parameterized constructor, the value is assigned to the instance variable "value" and the instance variable "title" is assigned the value "Welcome". Then, the Welcome() method is called, which prints out the value of "title" and "value", resulting in "Welcome 5" being printed.

Rate this question:

• 14.

### Consider the following code: class ExampleFive { public static void main(String[] args) { final int i = 22; byte b = i; System.out.println(i + ", " + b); } } Which of the following gives the valid output for the above code?

• A.

Prints: 22, 20

• B.

Runtime Error: Cannot type cast int to byte

• C.

Prints: 22, 22

• D.

Compile Time Error: Loss of precision

C. Prints: 22, 22
Explanation
The code is attempting to assign a value of type int to a variable of type byte. This would result in a loss of precision, as the range of values that can be stored in a byte is smaller than the range of values that can be stored in an int. However, since the int value being assigned (22) falls within the range of values that can be stored in a byte, no compile-time or runtime errors occur. Therefore, the output of the code will be "22, 22".

Rate this question:

• 15.

### Consider the following code snippet: class TestString2 { public static void main(String args[]) { String s1 = "Test1"; String s2 = "Test2"; s1.concat(s2); System.out.println(""+s1.charAt(s1.length() - 3) + s1.indexOf(s2)); } } What will be the output of the above code snippet?

• A.

S5

• B.

S-1

• C.

T4

• D.

15

• E.

T4

B. S-1
Explanation
The code snippet creates two String objects, s1 and s2, with values "Test1" and "Test2" respectively. The concat() method is called on s1 and s2, which concatenates the two strings but does not assign the result to any variable. The charAt() method is then called on s1, passing in the argument s1.length() - 3, which returns the character at the third position from the end of the string, which is 's'. The indexOf() method is called on s1, passing in s2 as the argument, which returns -1 because s2 is not found in s1. The output statement then prints the concatenation of 's' and -1, resulting in "s-1".

Rate this question:

• 16.

### Consider the following code: 1. public class SwitchIt { 2. public static void main(String[] args) 3. int w1 = 1; 4. int w2 = 2; 5. System.out.println(getW1W2(w1, w2)); 6. } 7. 8. public static int getW1W2(int x, int y) { 9. switch (x) { 10. case 1: x = x + y; 11. case 2: x = x + y; 12. } 13. return x; 14. } 15. } Which of the following gives the valid output of above code?

• A.

Compilation succeeds and the program prints "5"

• B.

Compilation fails because of an error on line 9

• C.

Compilation succeeds and the program prints "3"

• D.

Compilation fails because of errors on lines 10 and 11

A. Compilation succeeds and the program prints "5"
Explanation
The code will compile successfully because there are no syntax errors. The program will print "5" because the value of x is initially 1, and the switch statement will match the case 1. It will then add the values of x and y, resulting in x being 3. However, there is no break statement after case 1, so the program will continue to execute the statements under case 2 as well. This will add the values of x and y again, resulting in x being 5. Finally, the value of x is returned and printed.

Rate this question:

• 17.

### 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.

Line a prints the corresponding classname with Object's hashcode in Hexadecimal

• B.

Both Line a and Line b prints "Shatapdhi"

• C.

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

• D.

Output of Line a and Line b will be different

• E.

Output of Line a and Line b will be same

A. Line a prints the corresponding classname with Object's hashcode in Hexadecimal
C. Both Line a and Line b will print the corresponding classname with Object's hashcode in Hexa Decimal
E. Output of Line a and Line b will be same
Explanation
In Java, when an object is printed without explicitly calling the toString() method, the default toString() method is called. The default implementation of toString() returns the classname followed by the object's hashcode in hexadecimal. Therefore, Line a will print the corresponding classname with Object's hashcode in Hexadecimal. Line b explicitly calls the toString() method, which in this case will return the same result as the default implementation. Hence, both Line a and Line b will print the corresponding classname with Object's hashcode in Hexa Decimal. The output of Line a and Line b will be the same.

Rate this question:

• 18.

### Which of the following are true about inheritance?(Choose 3)

• A.

In an inheritance hierarchy, a subclass can also act as a super class

• B.

Inheritance enables adding new features and functionality to an existing class without modifying the existing class

• C.

Inheritance enables adding new features and functionality to an existing class without modifying the existing class

• D.

Inheritance is a kind of Encapsulation

• E.

Inheritance does not allow sharing data and methods among multiple classes

A. In an inheritance hierarchy, a subclass can also act as a super class
B. Inheritance enables adding new features and functionality to an existing class without modifying the existing class
C. Inheritance enables adding new features and functionality to an existing class without modifying the existing class
Explanation
Inheritance allows a subclass to inherit the properties and methods of its superclass, and in an inheritance hierarchy, a subclass can also act as a superclass for another subclass. This enables the reuse of code and promotes code organization. Additionally, inheritance allows for the addition of new features and functionality to an existing class without modifying the existing class itself, which helps to maintain the integrity of the original code.

Rate this question:

• 19.

### Consider the following code: 1 public class A { 2 public void m1() {System.out.print("A.m1, ");} 3 protected void m2() {System.out.print("A.m2, ");} 4 private void m3() {System.out.print("A.m3, ");} 5 void m4() {System.out.print("A.m4, ");} 6 7 public static void main(String[] args) { 8 A a = new A(); 9 a.m1(); 10 a.m2(); 11 a.m3(); 12 a.m4(); 13 } 14 } Which of the following gives the lines that need to be removed in order to compile and run the above code correctly?

• A.

Lines 10, 11

• B.

No need to comment any line. Will compile and run

• C.

Lines 10, 11 and 12

• D.

Line 11

B. No need to comment any line. Will compile and run
Explanation
The code will compile and run correctly without any lines needing to be removed. All the methods called in the main method (m1, m2, m3, m4) are accessible within the class A. Although m3 is declared as private, it can still be accessed within the same class. Therefore, no lines need to be removed for the code to compile and run correctly.

Rate this question:

• 20.

### Which of the following options gives the difference between == operator and equals() method?

• A.

Equals compares hash value and == compares character sequence

• B.

No difference;they are essentially the same

• C.

If equals() is true then == is also true

• D.

==compares object's memory address but equals character sequence

• E.

== works on numbers equals() works on characters

D. ==compares object's memory address but equals character sequence
Explanation
The correct answer is that the == operator compares the memory address of objects, while the equals() method compares the character sequence of objects.

Rate this question:

• 21.

### Which of the following classes is new to JDK 1.6?

• A.

Java.io.File

• B.

Java.io.Serializable

• C.

Java.io.FileFilter

• D.

Java.io.Console

• E.

Java.io.Externalizable

D. Java.io.Console
Explanation
The class "java.io.Console" is new to JDK 1.6. This class provides a way to interact with the user through the command line, allowing input and output operations. It provides methods for reading input from the user and writing output to the console. Prior to JDK 1.6, developers had to use other classes like "System.in" and "System.out" for console input and output operations. The addition of the "java.io.Console" class in JDK 1.6 made it easier and more convenient for developers to interact with the console.

Rate this question:

• 22.

### Which of the following statements are correct regarding Static Blocks?(Choose 3)

• A.

A class that have static block, should have the main() method defined in it

• B.

A class can have more than one static block

• C.

Static blocks are executed only once

• D.

Static blocks are executed before main() method

• E.

A static block can call other methods in a class

B. A class can have more than one static block
C. Static blocks are executed only once
D. Static blocks are executed before main() method
Explanation
A class can have more than one static block: This statement is correct because a class can have multiple static blocks defined in it.

Static blocks are executed only once: This statement is correct because static blocks are executed only once when the class is loaded into memory.

Static blocks are executed before main() method: This statement is correct because static blocks are executed before the main() method is called.

Static blocks are used to initialize static variables or perform any other static initialization tasks. They are executed when the class is loaded into memory, before the main() method is called. A class can have multiple static blocks, but they are executed only once. These blocks can also call other methods in the class.

Rate this question:

• 23.

### Which of the following flow control features does Java support? (Choose 2)

• A.

Labeled continue

• B.

Labeled goto

• C.

Labeled throw

• D.

Labeled catch

• E.

Labeled break

A. Labeled continue
E. Labeled break
Explanation
Java supports the flow control features of labeled continue and labeled break. Labeled continue is used to skip the current iteration of a loop and continue with the next iteration, while labeled break is used to terminate the loop or switch statement and continue with the code after the loop or switch statement. Labeled goto, labeled throw, and labeled catch are not supported in Java.

Rate this question:

• 24.

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

• A.

Polymorphism

• B.

Association

• C.

Aggregation

• D.

Inheritance

• E.

Persistence

C. Aggregation
Explanation
Aggregation is the correct answer because it represents a relationship between a Spreadsheet Object and Cell Objects where a Spreadsheet Object is composed of multiple Cell Objects. Aggregation is a type of association where one object is composed of or contains other objects. In this case, the Spreadsheet Object contains multiple Cell Objects, and changes to the Spreadsheet Object can affect the Cell Objects within it.

Rate this question:

• 25.

### Consider the following program: public class D extends Thread { public void run() { System.out.println("Before start method"); this.stop(); System.out.println("After stop method"); } public static void main(String[] args) { D a = new D(); a.start(); } } What will be the output of the above program?

• A.

'Before start method' and 'After stop method'

• B.

Compilation error

• C.

'Before start method' only

• D.

Runtime exception

C. 'Before start method' only
Explanation
The output of the program will be 'Before start method' only. This is because the stop() method is called immediately after the start() method, which causes the thread to stop before it has a chance to print 'After stop method'.

Rate this question:

• 26.

### 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?

• A.

New Choco().go();

• B.

New Bar().go();

• C.

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

• D.

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

• E.

Go();

D. (new Bar() {}).go();
Explanation
The correct answer is "(new Bar() {}).go();". This code snippet creates a new instance of the Bar class using an anonymous inner class. It then calls the go() method on this new instance, which prints "sweet".

Rate this question:

• 27.

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

• A.

10

• B.

11

• C.

No output

• D.

30

A. 10
Explanation
The code initializes the variable x to 10 and then uses a switch statement to check the value of x. Since the value of x is 10, it matches the case 10 and enters the corresponding block of code. The block of code contains a for loop that does not have any statements inside it, so it immediately breaks out of the loop. The next statement is a break statement, which causes the program to exit the switch statement. Therefore, the output of the program will be 10.

Rate this question:

• 28.

### Consider the following code: class One { public One() { System.out.print(1); } } class Two extends One { public Two() { System.out.print(2); } } class Three extends Two { public Three() { System.out.print(3); } } public class Numbers { public static void main(String[] argv) { new Three(); } } Which of the following will be the output for the above program?

• A.

321

• B.

No output

• C.

123

• D.

32

• E.

3

C. 123
Explanation
The output of the program will be 123. This is because the main method creates an instance of the Three class, which is a subclass of Two, which is a subclass of One. When an instance of Three is created, the constructor of the Three class is called, which prints 3. Then, since Three is a subclass of Two, the constructor of the Two class is called, which prints 2. Finally, since Two is a subclass of One, the constructor of the One class is called, which prints 1. Therefore, the output is 123.

Rate this question:

• 29.

### Consider the following code: public class TestOne { public static void main(String args[]) { byte x = 3; byte y = 5; System.out.print((y%x) + ", "); System.out.println(y == ((y/x) *x +(y%x))); } } Which of the following gives the valid output for above?

• A.

Prints: 1, true

• B.

Prints 2, false

• C.

Prints: 1, false

• D.

Prints: 2, true

D. Prints: 2, true
Explanation
The code first prints the result of (y%x), which is 5%3 = 2. Then it checks if y is equal to ((y/x) *x +(y%x)), which evaluates to (5/3) * 3 + (5%3) = 1 * 3 + 2 = 5. Since y is indeed equal to 5, the expression evaluates to true. Therefore, the output of the code is "2, true".

Rate this question:

• 30.

### Consider the following code: 1. public class Garment { 2. public enum Color { 3. RED(0xff0000), GREEN(0x00ff00), BLUE(0x0000ff); 4. private final int rgb; 5. Color( int rgb) { this.rgb = rgb; } 6. public int getRGB() { return rgb; } 7. }; 8. public static void main( String[] argv) { 9. // insert code here 10. } 11.} Which of the following code snippets, when inserted independently at line 9, allow the Garment class to compile? (Choose 2)

• A.

Color treeColor = Color.GREEN;

• B.

Color purple = new Color( 0xff00ff);

• C.

Color skyColor = BLUE;

• D.

If( RED.getRGB() < BLUE.getRGB() ) {}

• E.

If( Color.RED.ordinal() < Color.BLUE.ordinal() ) {}

A. Color treeColor = Color.GREEN;
E. If( Color.RED.ordinal() < Color.BLUE.ordinal() ) {}
Explanation
The first code snippet "Color treeColor = Color.GREEN;" allows the Garment class to compile because it assigns the Color.GREEN value to the treeColor variable.

The second code snippet "if( Color.RED.ordinal() < Color.BLUE.ordinal() ) {}" allows the Garment class to compile because it compares the ordinal values of Color.RED and Color.BLUE, which are both of type Color.

Rate this question:

• 31.

### Consider the following code: class Alpha { protected Beta b; } class Gamma extends Alpha { } class Beta { } Which of the following statement is True?

• A.

Beta has-a Gamma and Gamma is-a Alpha.

• B.

Gamma has-a Beta and Gamma is-a Alpha

• C.

Alpha is-a Gamma and has-a Beta.

• D.

Gamma is-a Beta and has-a Alpha.

• E.

Alpha has-a Beta and Alpha is-a Gamma

B. Gamma has-a Beta and Gamma is-a Alpha
• 32.

### Consider the following code snippet:   String deepak = "Did Deepak see bees? Deepak did.";   Which of the following method calls would refer to the letter b in the string referred by the variable deepak?

• A.

CharAt(13)

• B.

CharAt(15)

• C.

CharAt(12)

• D.

CharAt(16)

• E.

CharAt(14)

B. CharAt(15)
Explanation
The method call charAt(15) refers to the letter "b" in the string referred by the variable deepak because the index of the letter "b" in the string is 15. The charAt() method returns the character at the specified index in a string.

Rate this question:

• 33.

### Which of the following codes will compile and run properly?

• A.

Public class Test2 { static public void main(String[] in) { System.out.println("Test2"); } }

• B.

Public class Test4 { static int main(String args[]) { System.out.println("Test4"); } }

• C.

public class Test1 { public static void main() { System.out.println("Test1"); } }

• D.

Public class Test3 { public static void main(String args) { System.out.println("Test3"); } }

• E.

Public class Test5 { static void main(String[] data) { System.out.println("Test5"); } }

A. Public class Test2 { static public void main(String[] in) { System.out.println("Test2"); } }
Explanation
The correct answer is the first option, public class Test2 { static public void main(String[] in) { System.out.println("Test2"); } }. This code will compile and run properly because it follows the standard Java syntax for the main method, which is public static void main(String[] args). The main method is the entry point for a Java program, and it must be declared exactly as shown in the correct answer for the code to compile and run successfully.

Rate this question:

• 34.

### 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

A. The variable at line 4 should be declared as final
Explanation
In Java, local variables referenced from an inner class must be final or effectively final. Since the variable 'x' at line 4 is referenced in the inner class Circle2, it needs to be declared as final to compile and execute properly. Declaring it as final will allow the inner class to access and print its value.

Rate this question:

• 35.

### Which of the following options gives the relationship between a Pilot class and Plane class?

• A.

Inheritance

• B.

Polymorphism

• C.

Persistence

• D.

Aggregation

• E.

Association

E. Association
Explanation
Association is a relationship between two separate classes, where both classes can exist independently. In the context of a Pilot class and Plane class, an association could mean that a pilot can be associated with multiple planes or a plane can be associated with multiple pilots. This relationship does not imply any kind of hierarchy or dependency between the two classes, unlike inheritance or polymorphism. Persistence refers to the ability to store and retrieve data, which is not relevant to the relationship between these classes. Aggregation implies a "has-a" relationship, where one class contains or owns another class, which is not specified in the question.

Rate this question:

• 36.

### Consider the following code: public class Key1 { public boolean testAns( String ans, int n ) { boolean rslt; if (ans.equalsIgnoreCase("YES") & n > 5) rslt = true; return rslt; } public static void main(String args[]) { System.out.println(new Key1().testAns("no", 5)); } } Which of the following will be the output of the above program?

• A.

Compile-time error

• B.

Runtime Error

• C.

NO

• D.

False

• E.

True

A. Compile-time error
Explanation
The code will result in a compile-time error because the variable "rslt" is not initialized before it is returned.

Rate this question:

• 37.

### Which of the following methods are defined in Object class? (Choose 3)

• A.

ToString()

• B.

CompareTo(Object)

• C.

HashCode()

• D.

Equals(Object)

• E.

Run()

A. ToString()
C. HashCode()
D. Equals(Object)
Explanation
The methods toString(), hashCode(), and equals(Object) are defined in the Object class. The toString() method returns a string representation of an object, the hashCode() method returns a unique integer value for an object, and the equals(Object) method compares two objects for equality. These methods are inherited by all classes in Java and can be overridden to provide custom implementations. The run() and compareTo(Object) methods are not defined in the Object class.

Rate this question:

• 38.

### Consider the following code: public class Code4 { private int second = first; private int first = 1000; public static void main(String args[]) { System.out.println(new Code4().second); } } Which of the following will be the output for the above code?

• A.

Throws a Runtime error 'Illegal forward reference'

• B.

1000

• C.

Compiler complains about forward referencing of member variables first and second

• D.

Compiler complains about private memebers is not accessible from main() method

C. Compiler complains about forward referencing of member variables first and second
Explanation
The code will not compile because the variable 'second' is being assigned the value of 'first' before 'first' has been declared. This is known as forward referencing, which is not allowed in Java. Therefore, the correct answer is "Compiler complains about forward referencing of member variables first and second".

Rate this question:

• 39.

### Consider the following code: public class ObParam{ public int b = 20; public static void main(String argv[]){ ObParam o = new ObParam(); methodA(o); } public static void methodA(ObParam a) { a.b++; System.out.println(a.b); methodB(a); System.out.println(a.b); } public void methodB(ObParam b) { b.b--; } } Which of the following gives the correct output for the above code?

• A.

Prints: 21 21

• B.

Prints: 20 21

• C.

Compilation Error: Non-static method methodB() cannot be referenced from static context methodA()

• D.

Prints: 20 20

• E.

Prints: 21 20

C. Compilation Error: Non-static method methodB() cannot be referenced from static context methodA()
Explanation
The correct answer is "Compilation Error: Non-static method methodB() cannot be referenced from static context methodA()". This is because the method methodB() is not a static method, so it cannot be called directly from the static method methodA(). To fix this error, either the methodB() should be made static or an instance of the class ObParam should be created in methodA() and then the methodB() should be called on that instance.

Rate this question:

• 40.

### Which of the following statements are true? (Choose 2)

• A.

All exceptions are thrown programmatically from the code or API

• B.

All exceptions are thrown by JVM

• C.

JVM cannot throw user-defined exceptions

• D.

JVM thrown exceptions can be thrown programmatically

• E.

All RuntimeException are thrown by JVM

C. JVM cannot throw user-defined exceptions
D. JVM thrown exceptions can be thrown programmatically
Explanation
The JVM (Java Virtual Machine) is responsible for executing Java programs. It can throw exceptions that are predefined and built-in, but it cannot throw user-defined exceptions. User-defined exceptions are exceptions that are created by the programmer to handle specific scenarios in their code. On the other hand, exceptions thrown by the JVM can be thrown programmatically, meaning that the programmer can intentionally throw these exceptions in their code. Therefore, the two true statements are: JVM cannot throw user-defined exceptions and JVM thrown exceptions can be thrown programmatically.

Rate this question:

• 41.

### Delimiters themselves be considered as tokens. State True or False.

• A.

True

• B.

False

B. False
Explanation
Delimiters themselves should not be considered as tokens. In programming or text processing, tokens are usually defined as meaningful units of information, such as words or symbols, that are separated by delimiters. Delimiters serve as separators between tokens and help identify the boundaries of each token. Therefore, it is more accurate to say that delimiters are used to define tokens rather than being considered tokens themselves.

Rate this question:

• 42.

### Consider the following code: public class ExampleSeven { public static void main(String [] args) { String[] y = new String[1]; String x = "hello"; y[0] = x; // Code here System.out.println("match"); } else { System.out.println("no match"); } } } Which of the following code snippet when substituted at the commented line (// Code here) in the above code will make the program to print "no match"?

• A.

If (x != y[0].toString()) {

• B.

If (x & y[0]) {

• C.

If (x.equals(y[0])) {

• D.

If (!x.equals(y[0])) {

D. If (!x.equals(y[0])) {
Explanation
The correct answer is "if (!x.equals(y[0])) {". This code snippet checks if the value of x is not equal to the value of y[0]. If they are not equal, it will execute the code inside the if statement and print "no match".

Rate this question:

• 43.

### 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

E. An exception is thrown at runtime
Explanation
The code snippet tries to assign an instance of the Dog class to a variable of type Cat. Since Dog is a subclass of Animal and Cat is also a subclass of Animal, this assignment is allowed at compile time. However, at runtime, an exception will be thrown because the actual object being referred to is an instance of Dog, not Cat. Therefore, when the noise() method is called on the cat object, an exception will be thrown.

Rate this question:

• 44.

### 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];

A. Grts = new float[1][4];
B. Invt = grts;
D. Invt = new float[4][2];
Explanation
The first statement "grts = new float[1][4];" creates a new two-dimensional array of type float with 1 row and 4 columns and assigns it to the variable "grts". This statement is valid because it matches the declaration of "float[][] grts;".

The second statement "invt = grts;" assigns the value of the variable "grts" to the variable "invt". Since both variables are declared as two-dimensional arrays of type float, this assignment is valid.

The third statement "invt = new float[4][2];" creates a new two-dimensional array of type float with 4 rows and 2 columns and assigns it to the variable "invt". This statement is also valid because it matches the declaration of "float[][] invt;".

These three statements ensure that the program compiles without errors.

Rate this question:

• 45.

### 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 are created from main() method of that class

• D.

Instance blocks are executed before constructors

• E.

Instance blocks are executed for every created instance

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, which are used to initialize instance variables.

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

Instance blocks are executed for every created instance: This statement is correct because instance blocks are executed each time an object of the class is created, ensuring that the necessary initialization steps are performed for each instance.

Rate this question:

• 46.

### Which one do you like?

• A.

Option 1

• B.

Option 2

• C.

Option 3

• D.

Option 4

A. Option 1

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 22, 2023
Quiz Edited by
ProProfs Editorial Team
• Feb 17, 2018
Quiz Created by
Marikannan

Related Topics