Java Certification Test! Programming Trivia Questions Quiz

Reviewed by Editorial Team
The ProProfs editorial team is comprised of experienced subject matter experts. They've collectively created over 10,000 quizzes and lessons, serving over 100 million users. Our team includes in-house content moderators and subject matter experts, as well as a global network of rigorously trained contributors. All adhere to our comprehensive editorial guidelines, ensuring the delivery of high-quality content.
Learn about Our Editorial Process
| By Catherine Halcomb
Catherine Halcomb
Community Contributor
Quizzes Created: 1443 | Total Attempts: 6,714,021
| Attempts: 875 | Questions: 95
Please wait...
Question 1 / 95
0 %
0/100
Score 0/100
1. Given the code fragment:
public class Test {
    public static void main(String[] args) {
        int a[] = {1, 2, 3, 4, 5};
        for (xxx) {
            System.out.print(a[e]);
        }
    }
}
Which option can replace xxx to enable the code to print 135?

Explanation

The correct option is "int e = 0; e

Submit
Please wait...
About This Quiz
Java Certification Test! Programming Trivia Questions Quiz - Quiz

Are you reading to get your java certification test? There are different things that you need to understand to ensure you do not fail the test properly, and... see morethe programming trivia questions quiz below will help you get a clue of what they are. How about you give it a shot and get to see if you actually know enough to sit for the test or need more study hours. see less

2. Given the code snippet from a compiled Java source file:
public class MyFile{
    public static void main(String[] args) {
        String arg1 = args[1];
        String arg2 = args[2];
        String arg3 = args[3];
        System.out.println("Arg is "+ arg3);
    }
}
Which command-line arguments should you pass to the program to obtain the following result?
Arg is 2

Explanation

The correct answer is "java MyFile 1 3 2 2". This is because the code snippet accesses the third command-line argument (args[3]) and assigns it to the variable arg3. Therefore, in order to obtain the result "Arg is 2", the value 2 must be passed as the third command-line argument.

Submit
3. What is the name of the Java concept that uses access modifiers to protect variables and hide them within a class?

Explanation

Encapsulation is the Java concept that uses access modifiers to protect variables and hide them within a class. It allows for the bundling of data and methods together, providing control over the accessibility of the variables. This ensures that the variables can only be accessed and modified through the defined methods, promoting data security and preventing direct manipulation of the data from outside the class.

Submit
4. You are asked to create a method that accepts an array of integers and returns the highest value from that array. Given the code fragment:
class Test{
    public static void main(String[] args) {
        int numbers[] = {12, 13, 42, 32, 15, 156, 23, 51, 12};
        int max = findMax(numbers);
    }
    /* line n1*/{
        int max = 0;
        /*code goes here*/
        return max;
    }
}
Which method signature do you use at line n1?

Explanation

The correct method signature to use at line n1 is "static int findMax(int[] numbers)". This is because the method is expected to accept an array of integers as a parameter and return an integer value, which matches the method signature "int[] numbers".

Submit
5. Given:
class Test {
    public static void main(String[] args) {
        int x = 1;
        int y = 0;
        if(x++ > ++y){
            System.out.print("Hello ");
        } else{
            System.out.print("Welcome ");
        }
        System.out.print("Log " + x + ": "+ y);
    }
}
What is the result?

Explanation

The result is "Welcome Log 2: 1". In the if statement, the expression "x++ > ++y" is evaluated. Since x is initially 1 and y is initially 0, the expression becomes "1 > 1" after the post-increment of x and pre-increment of y. This expression evaluates to false, so the else block is executed. "Welcome" is printed, followed by the string "Log 2: 1" which represents the values of x and y after the if statement.

Submit
6. Given the code from the Greeting.java file:
public class Greeting{
    public static void main(String[] args) {
        System.out.println("Hello "+ args[0]);
    }
}
Which set of commands prints Hello Duke in the console?

Explanation

The set of commands "javac Greeting.java" compiles the Greeting.java file into bytecode, and "java Greeting Duke" executes the compiled bytecode, resulting in the output "Hello Duke" printed in the console.

Submit
7. Given:
public class CD {
    int r;
    CD(int r) {
        this.r = r;
    }
}
class DVD extends CD {
    int c;
    DVD(int r, int c) {
        // line n1
        
    }
}
And given the code fragment:
DVD dvd=new DVD(10,20);
Which code fragment should you use at line n1 to instantiate the dvd object successfully?

Explanation

At line n1, the code should use "super(r);" to invoke the constructor of the superclass, CD, with the parameter "r". This ensures that the instance variable "r" of the superclass is properly initialized. Then, "this.c=c;" sets the value of the instance variable "c" in the subclass, DVD, to the value of the parameter "c". This ensures that both instance variables in the subclass are properly initialized.

Submit
8. Given:
class App{
    public static void main(String[] args) {
        int i = 10;
        int j = 20;
        int k = j += i / 5;
        System.out.print(i + " : " + j + " : " + k);
    }
}
What is the result?

Explanation

In this code, the value of `i` is 10 and the value of `j` is 20. The expression `j += i / 5` is equivalent to `j = j + (i / 5)`. Since `i` is an integer and the division is integer division, `i / 5` evaluates to 2. Therefore, `j += i / 5` becomes `j = j + 2`, which means `j` is incremented by 2. So, the value of `j` becomes 22. The value of `k` is assigned the value of `j`, which is 22. Therefore, the result is "10 : 22 : 22".

Submit
9. Given the following class declarations:
public abstract class Animal{}
interface Hunter{}
class Cat extends Animal implements Hunter{}
class Tiger extends Cat{}
Which answer fails to compile?

Explanation

The answer that fails to compile is "ArrayList myList = new ArrayList(); myList.add(new Cat());". This is because the ArrayList is declared to hold objects of type Tiger, but we are trying to add an object of type Cat, which is not a subclass of Tiger.

Submit
10. Given the code fragment:
class TestA{
    static int count = 0;
    int i = 0;
    public void changeCount(){
        while(i < 5){
            i++;
            count++;
        }
    }
    public static void main(String[] args) {
        TestA check1 = new TestA();
        TestA check2 = new TestA();
        check1.changeCount();
        check2.changeCount();
        System.out.println(check1.count + " : "+ check2.count);
    }
}
What is the result?

Explanation

The result is 10 : 10 because the variable "count" is declared as static, which means it is shared among all instances of the TestA class. Both check1 and check2 call the changeCount() method, which increments the "count" variable by 5 each time. Therefore, the final value of "count" is 10 for both check1 and check2.

Submit
11. Given:
class TestB{
    int x,y;
    public TestB(int x, int y){
        initialize(x,y);
    }
    public void initialize(int x, int y){
        this.x = x * x;
        this.y = y * y;
    }
    public static void main(String[] args) {
        int x =3,y =5;
        TestB obj = new TestB(x,y);
        System.out.println(x+ " "+ y);
    }
}
What is the result?

Explanation

The result is 3 5 because the main method initializes variables x and y with the values 3 and 5 respectively. Then, a new object of the TestB class is created with these values. The initialize method of the TestB class assigns the square of x (9) to the instance variable x and the square of y (25) to the instance variable y. However, the print statement in the main method prints the original values of x and y, which are 3 and 5 respectively.

Submit
12. Given the code fragment:
import java.time.LocalDate;
class Date{
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2012, 01, 32);
        date.plusDays(10);
        System.out.println(date);
    }
}
What is the result?

Explanation

The code attempts to create a LocalDate object with the date 2012-01-32, which is an invalid date. This will result in a DateTimeException being thrown at runtime. The code then calls the plusDays() method on the date object, but since LocalDate objects are immutable, the method does not modify the original date object. Therefore, the output will still be the invalid date 2012-01-32.

Submit
13. Given:
MainTest.java
public class MainTest{
    public static void main(int[] args) {
        System.out.println("int main " + args[0]);
    }
    public static void main(Object[] args) {
        System.out.println("Object main " + args[0]);
    }
    public static void main(String[] args) {
        System.out.println("String main " + args[0]);
    }
}
And commands:
javac MainTest.java
java MainTest 1 2 3
What is the result?

Explanation

The result of the given commands is "String main 1". This is because when the Java program is executed, it looks for a main method with the signature "public static void main(String[] args)". In this case, the main method with the String[] args parameter is present and it is the one that gets executed. The value "1" is passed as the first argument, so it gets printed along with the "String main" message. The other main methods with different parameter types are not considered as the entry point for the program.

Submit
14. Given:
class Product {
    double price;
}

public class Test {

    public void updatePrice(Product product, double price) {
        price = price * 2;
        product.price = product.price + price;
    }

    public static void main(String args[]) {
        Product prt = new Product();
        prt.price = 200;
        double newPrice = 100;
        Test t = new Test();
        t.updatePrice(prt, newPrice);
        System.out.println(prt.price + " : " + newPrice);
    }
}
What is the result?

Explanation

The result is "400.0 : 100.0" because the updatePrice method in the Test class takes a Product object and a double as parameters. Inside the method, the price parameter is multiplied by 2 and then added to the product's price. In the main method, a new Product object is created with a price of 200, and a newPrice variable is set to 100. The updatePrice method is then called with the Product object and newPrice as arguments. This means that the product's price is updated to 200 + (100 * 2) = 400, and the newPrice variable remains unchanged at 100. Therefore, the output is "400.0 : 100.0".

Submit
15. Given the code fragment:
if (aVar++ < 10) {
    System.out.println("Hello World!");
} else {
    System.out.println("Hello Universe!");
}
What is the result if the integer aVar is 9?

Explanation

The code fragment checks if the value of aVar (which is initially 9) is less than 10. Since 9 is less than 10, the condition evaluates to true. The statement inside the if block is executed, which prints "Hello World!" to the console. Therefore, the result is "Hello World!".

Submit
16. Given:
class A{
    public A(){
        System.out.print("A ");
    }
}
class B extends A{
    public B(){ //line n1
        System.out.print("B ");
    }
}
class C extends B{
    public C(){ //line n2
        System.out.print("C ");
    }
    public static void main(String[] args) {
        C c = new C();
    }
}
What is the result?

Explanation

The code will compile successfully and the output will be "A B C". This is because the class C extends class B, which in turn extends class A. When an object of class C is created, the constructor of class A is called first, followed by the constructor of class B, and finally the constructor of class C. Each constructor prints its respective letter, resulting in the output "A B C".

Submit
17. Given the following main method:
public static void main(String[] args) {
    int num = 5;
    do {
        System.out.println(num-- + " ");
    } while (num == 0);
}
What is the result?

Explanation

The given main method starts with the variable "num" initialized to 5. It then enters a do-while loop. Inside the loop, it prints the value of "num" followed by a space and then decrements "num" by 1. The loop continues as long as "num" is equal to 0. However, since "num" is initially 5 and never becomes 0, the loop is not executed and nothing is printed. Therefore, the result is "Nothing is printed".

Submit
18.
Given the code fragment:
public static void main(String[] args) {
    boolean opt = true; //line 5
    switch (opt) {
        case true: // line 7
            System.out.print("True");;
            break; //line 9
        default:
            System.out.print("***");;
    }
    System.out.print("Done");
}
Which modification enables the code fragment to print TrueDone?

Explanation

The code fragment is using a switch statement to check the value of the boolean variable "opt". In order for the code to print "TrueDone", the value of "opt" needs to be a string "true" instead of a boolean true. Therefore, replacing line 5 with String opt = "true" will enable the code fragment to print "TrueDone". Additionally, replacing line 7 with case "true": ensures that the switch case matches the string value of "opt".

Submit
19. Given:
class Vehicle{
    int x;
    Vehicle(){
        this(10); //line n1
    }
    Vehicle(int x){
        this.x = x;
    }
}
class Car extends Vehicle{
    int y;
    Car(){
        super();
        this(20); //line n2
    }
    Car(int y){
        this.y = y; //line n3
    }
    public String toString(){
        return super.x + " : " + this.y;
    }
}
And given the code fragment:
Vehicle y = new Car();
System.out.println(y);
What is the result?

Explanation

The code will fail to compile on line n2 because the constructor in the Car class is calling both the default constructor of the superclass (Vehicle) using the super() keyword and another constructor in the Car class using this(20). This is not allowed as per the Java language rules. The super() call should be the first statement in the constructor.

Submit
20. Which statement is true about Java byte code?

Explanation

Java byte code is a platform-independent code that can be executed on any platform that has the Java Runtime Environment (JRE). The JRE provides the necessary environment for executing Java programs, regardless of the underlying platform. This allows Java byte code to be portable and run on various operating systems and hardware architectures without the need for recompilation. Therefore, the statement "It can run on any platform that has the Java Runtime Environment" is true.

Submit
21. Given the code fragment:
public static void main(String[] args) {
    String myStr = "Hello World ";
    myStr.trim();
    int i1 = myStr.indexOf(" ");
    System.out.println(i1);
}
What is the result?

Explanation

The code fragment initializes a string variable "myStr" with the value "Hello World ". The trim() method is called on "myStr", which removes any leading or trailing whitespace from the string. However, the result of the trim() method is not assigned to any variable, so the original value of "myStr" remains unchanged. The indexOf() method is then called on "myStr" to find the index of the first occurrence of a space character. Since the space character is at index 5 in the original string, the result of the indexOf() method is 5. Therefore, the correct answer is 5.

Submit
22. Given the code fragment:
public class Test{
    public static void main(String[] args) {
        /* line 3*/
        array[0] = 10;
        array[1] = 20;
        System.out.print(array[0]+ ": "+array[1]);
    }
}
Which code fragment, when inserted at line 3, enables the code to print 10:20?

Explanation

The correct answer is "int [] array = new int[2];". This code fragment declares an array named "array" of type int with a size of 2. This allows the code to assign values to array[0] and array[1] and print them correctly as 10 and 20 respectively.

Submit
23. Given the following code:
public static void main(String[] args) {
    String[] planets = {"Mercury", "Venus", "Earth", "Mars"};
    System.out.println(planets.length);
    System.out.println(planets[1].length());
}
What is the output?

Explanation

The code initializes an array named "planets" with four elements: "Mercury", "Venus", "Earth", and "Mars". The first line of output prints the length of the array, which is 4. The second line of output prints the length of the element at index 1 of the array, which is "Venus". The length of "Venus" is 5, so the output is 4 and 5.

Submit
24. Given:
class TestC{
    public static void main(String[] args) {
        TestC ts = new TestC();
        System.out.print(isAvailable + " ");
        isAvailable = ts.doStuff();
        System.out.println(isAvailable);
    }
    public static boolean doStuff(){
        return !isAvailable;
    }
    static boolean isAvailable = false;
}
What is the result?

Explanation

The code will compile successfully. The initial value of isAvailable is false. The first print statement will print false. Then, the doStuff() method is called, which returns the negation of isAvailable, so it returns true. The second print statement will print true. Therefore, the result is "false true".

Submit
25.
Given the code fragment:
public static void main(String[] args) {
    int [][]arr = new int[2][4];
    arr [0] = new int[]{1, 3, 5, 7};
    arr [1] = new int[]{1, 3};
    for (int[] a : arr) {
        for (int i : a) {
            System.out.print(i + " ");
        }
        System.out.println();
    }
}
What is the result?

Explanation

The code creates a 2-dimensional array called "arr" with 2 rows and 4 columns. The first row is initialized with the values 1, 3, 5, and 7, while the second row is initialized with the values 1 and 3.

The nested for loop is used to iterate over each element in the array. The outer loop iterates over each row, and the inner loop iterates over each element in the row.

The print statement prints each element followed by a space. After printing all the elements in a row, a new line is printed.

Therefore, the output will be:
1 3 5 7
1 3

Submit
26. Given:
class Test{
    public static void main(String[] args) {
        int numbers[];
        numbers = new int[2];
        numbers[0] = 10;
        numbers[1] = 20;
        numbers = new int[4];
        numbers[2] = 30;
        numbers[3] = 40;
        for (int x : numbers) {
            System.out.print(" " + x);
        }
    }
}
What is the result?

Explanation

The code creates an array of integers called "numbers" with a length of 2. It then assigns values to the first two elements of the array. However, it then reassigns the "numbers" variable to a new array with a length of 4. This means that the previous values assigned to the array are lost. The code then assigns values to the third and fourth elements of the new array. Finally, it uses a for-each loop to print out the elements of the array. Since the first two elements were not assigned new values, they remain as the default value of 0. Therefore, the result is "0 0 30 40".

Submit
27. Given the code fragment:
public static void main(String[] args) {
    StringBuilder sb = new StringBuilder(5);
    String s = "";
    if (sb.equals(s)) {
        System.out.println("Match 1");
    } else if (sb.toString().equals(s.toString())) {
        System.out.println("Match 2");
    } else {
        System.out.println("No match");
    }
}
What is the result?

Explanation

The code will result in "Match 2" being printed. This is because the StringBuilder object `sb` is not equal to the empty String `s`, so the first condition is false. However, when comparing the String representations of `sb` and `s`, they are both empty Strings, so the second condition is true and "Match 2" is printed.

Submit
28. Given the code fragment:
if (aVar++ < 10) {
    System.out.println(aVar + " Hello World!");
} else {
    System.out.println(aVar + " Hello Universe!");
}
What is the result if the integer aVar is 9?

Explanation

The code fragment uses the post-increment operator (aVar++) on the variable aVar. Since aVar is initially 9, the condition (aVar++

Submit
29. Given the code fragment:
class Z{
    public static void main(String[] args) {
        int ii = 0;
        int jj = 7;
        for ( ii = 0; ii < jj - 1; ii = ii +2) {
            System.out.println(ii + " ");
        }
    }
}
What is the result?

Explanation

The code fragment initializes ii to 0 and jj to 7. The for loop condition checks if ii is less than jj - 1, which is true since 0 is less than 6. Inside the loop, ii is incremented by 2. So, the loop will execute with ii values of 0, 2, and 4. The println statement prints the value of ii followed by a space. Therefore, the result will be "0 2 4".

Submit
30. Given:
class Test{
    public int MIN = 1;
    public static void main(String[] args) {
        Test t = new Test();
        int x = args.length;
        if (t .checkLimit(x)){ //line n1
            System.out.println("Java SE");
        } else{
            System.out.println("Java EE");
        }
    }
    public boolean checkLimit(int x) {
        return (x >= MIN ) ? true : false;
    }
}
And given the commands:
javac Test.java
java Test
What is the result?

Explanation

The code first creates an instance of the Test class. Then, it retrieves the length of the args array and assigns it to the variable x. The checkLimit() method is called with x as the argument. If x is greater than or equal to the MIN variable (which is 1), the method returns true. In this case, since the length of the args array is not specified when running the program, x will be 0. Therefore, the checkLimit() method will return false. As a result, the program will print "Java EE" to the console.

Submit
31. Which three statements describe the object-oriented features of the java language? (Choose three)

Explanation

A subclass can inherit from a superclass: This statement describes one of the key features of object-oriented programming in Java, which is the ability for a subclass (a derived class) to inherit the properties and behaviors of its superclass (a base class).

Object can share behaviors with other objects: This statement highlights another important feature of object-oriented programming, which is the ability for objects to share behaviors through methods and inheritance. This allows for code reuse and promotes modular and organized programming.

Object is the root class of all other objects: This statement refers to the fact that in Java, the Object class is the ultimate parent class of all other classes. Every class in Java is either directly or indirectly derived from the Object class, which provides basic functionalities and methods that are common to all objects.

Submit
32. Given:
MyString.java:
package p1;
class MyString{
    String msg;
    public MyString(String msg) {
        this.msg = msg;
    }
}
And Test.java:
package p1;
class Test{
    public static void main(String[] args) {
        System.out.println("Hello " + new StringBuilder("Java SE 8"));
        System.out.println("Hello " + new MyString("Java SE 8"));
    }
}
What is the result?

Explanation

The first line of the output is "Hello Java SE 8" because when concatenating a string literal with a StringBuilder object, the toString() method of the StringBuilder class is automatically called, which returns the string representation of the StringBuilder object.

The second line of the output is "Hello p1.MyString@>" because when concatenating a string literal with a MyString object, the toString() method of the MyString class is not overridden, so it uses the default toString() method from the Object class, which returns the class name followed by the hashcode of the object.

Submit
33. Given the code fragment:
class CCMask{
    public static String maskCC(String creditCard) {
        String x = "XXXX-XXXX-XXXX-";
        //line n1
    }
    public static void main(String[] args) {
        System.out.println(maskCC("1234-5678-9101-1121"));
    }
}
You must ensure that the maskCC method returns a string that hides all digits of the credit of except the four last digits (and the hyphens that separate each group of the four digits). Which two code fragments should you use at line n1, independently to achieve this required?

Explanation

The first code fragment creates a StringBuilder object with the initial value of "XXXX-XXXX-XXXX-". It then appends a substring of the creditCard string, starting from index 15 and ending at index 19 (which represents the last four digits of the credit card number). Finally, it returns the resulting string.

The second code fragment directly concatenates the "XXXX-XXXX-XXXX-" string with a substring of the creditCard string, starting from index 15 and ending at index 19. It then returns the resulting string.

Both code fragments achieve the required result of hiding all digits of the credit card number except the last four digits.

Submit
34. Given:
import java.util.ArrayList;
import java.util.List;
class Patient{
    String name;
    public Patient(String name) {
        this.name = name;
    }
}
And the code fragment:
class Test{
    public static void main(String[] args) {
        List ps = new ArrayList();
        Patient p2 = new Patient("Mike");
        ps.add(p2);
        //insert code here
        if(f>=0){
            System.out.println("Mike found");
        }
    }
}
Which code fragment, when inserted at line 14, enables the code to print Mike found?

Explanation

The correct answer is "int f = ps.indexOf(p2);" because it assigns the index of the object "p2" in the list "ps" to the variable "f". This allows the code to check if "Mike" is found in the list by checking if "f" is greater than or equal to 0. If "f" is greater than or equal to 0, it means that "Mike" is found in the list and the code will print "Mike found".

Submit
35. Which statement will empty the contents of a StringBuilder variable named sb?

Explanation

The correct answer is sb.delete(0,sb.length()). This statement will delete all the characters in the StringBuilder variable named sb by specifying the range from index 0 to the length of the StringBuilder.

Submit
36. Given:
class T{
    public static void main(String[] args) {
        String ta = "A ";
        ta = ta.concat("B ");
        String tb = "C ";
        ta = ta.concat(tb);
        ta.replace('C', 'D');
        ta = ta.concat(tb);
        System.out.println(ta);
    }
}
What is the result?

Explanation

The code starts by creating a String variable "ta" with the value "A ". It then concatenates "B " to "ta", resulting in "A B ". Next, it creates another String variable "tb" with the value "C ". It concatenates "tb" to "ta", resulting in "A B C ". The code then attempts to replace the character 'C' in "ta" with 'D', but since the replace method returns a new String and does not modify the original String, this change is not reflected in "ta". Finally, it concatenates "tb" to "ta" again, resulting in "A B C C". Therefore, the correct answer is "A B C C".

Submit
37. Given the code fragment:
class Tee{
    public static void main(String[] args) {
        String cs[] = {"US", "UK"};
        int wc = 0;
        while (wc < cs.length) {
            int count = 0;
        do {
            ++count;
        } while (count < cs[wc].length());
            System.out.println(cs[wc] + ": " + count);
            wc++;
        }
    }
}
What is the result?

Explanation

The code fragment initializes an array "cs" with two strings "US" and "UK". It then enters a while loop that iterates until the variable "wc" is less than the length of the array. Inside the loop, a variable "count" is initialized to 0. Then, a do-while loop increments the "count" variable until it is less than the length of the string at index "wc" in the "cs" array. After the do-while loop, it prints the string at index "wc" followed by a colon and the value of "count". Finally, it increments the "wc" variable.

In this case, the length of both strings in the "cs" array is 2. Therefore, the output will be "US: 2" and "UK: 2".

Submit
38. Given the code fragment:
    StringBuilder sb1 = new StringBuilder("Duke");
    String str1 = sb1.toString();
    //line n1
    System.out.print(str1 == str2);
Which code fragment, when inserted at line n1, enables the code to print true?

Explanation

The code fragment "String str2 = str1;" enables the code to print true because it assigns the value of str1 to str2. Since both str1 and str2 refer to the same string object, the comparison "str1 == str2" will evaluate to true.

Submit
39. Given:
public class App{
    int count;
    public static void displayMsg() {
        count++; // line n1
        System.out.println("Welcome "+ "Visit Count: "+count); // line n2
    }
    public static void main(String[] args) {
        App.displayMsg(); // line n3
        App.displayMsg(); // line n4
    }
}
What is the result?

Explanation

The code fails to compile because the variable "count" is not declared as static. The "displayMsg" method is a static method, meaning it can be called without creating an instance of the class. However, the non-static variable "count" cannot be accessed from a static context. To fix this, the "count" variable should be declared as static.

Submit
40. Given the code fragment:
    int wd = 0;
    String days[] = {"sun", "mon", "wed", "sat"};
    for(String s: days){
        switch (s) {
            case "sun":
                wd -= 1;
                break;
            case "mon":
                wd++;
            case "wed":
                wd +=2;
        }
    }
    System.out.println(wd);
What is the result?

Explanation

The code fragment initializes the variable "wd" to 0 and creates an array of strings named "days". It then uses a for-each loop to iterate through each string in the "days" array.

Inside the loop, there is a switch statement that checks the value of each string. If the string is "sun", it subtracts 1 from "wd". If the string is "mon", it adds 1 to "wd" and falls through to the next case. If the string is "wed", it adds 2 to "wd".

Since the loop iterates through all the strings in the "days" array, the switch statement will execute for each string. Therefore, the final value of "wd" will be 4.

Submit
41. Given:
interface Downloadable{
    public void download();
}
interface Readable extends Downloadable{ //line n1
    public void readBook();
}
abstract class Book implements Readable { //line n2
    public void readBook(){
        System.out.println("Read Book");
    }
}
class EBook extends Book{ //line n3
    public void readBook(){
        System.out.println("Read E-Book");
    }
}
And given the code fagment:
Book book1 = new EBook();
book1.readBook();
What is the result?

Explanation

The correct answer is "Compilation fails at line n3." When the code is executed, it tries to create a new object of type EBook and assign it to a variable of type Book. However, the EBook class does not implement the download() method from the Downloadable interface, which is required by the Readable interface. Therefore, the code fails to compile at line n3.

Submit
42. Given the code fragment from three files: SalesMan.java:
package sales;
public class SalesMan { }
Product.java:
package sales.products;
public class Product{ }
Market.java:
package market;
// line n2
public class USMrket {
      SalesMan sm;
      Product p;
}
Which code fragment, when inserted at line n2, enables the code to compile?

Explanation

The code fragment "import sales.*; import sales.products.*;" enables the code to compile because it imports all classes from the "sales" package and all classes from the "sales.products" package, allowing the SalesMan and Product classes to be accessed in the USMarket class.

Submit
43. Given:
class TestString {
    public static int stVar = 100;
    public int var = 200;
    @Override
    public String toString() {
        return var + ": " + stVar;
    }
}
And given the code fragment:
public static void main(String[] args) {
    TestString t1 = new TestString();
    t1.var = 300;
    System.out.println(t1);
    TestString t2 = new TestString();
    t2.stVar = 300;
    System.out.println(t2);
}
What is the result?

Explanation

The code creates two instances of the TestString class, t1 and t2.

In the first instance, t1, the var variable is assigned a value of 300.

When the toString() method is called on t1, it returns the value of var (300) followed by a colon and the value of the static variable stVar (100).

In the second instance, t2, the static variable stVar is assigned a value of 300.

When the toString() method is called on t2, it returns the value of var (200) followed by a colon and the value of the static variable stVar (300).

Therefore, the result is "300: 100" for t1 and "200: 300" for t2.

Submit
44. Given:
class Apps{
    String mystr = "7007";
    public void doStuff(String str){
        int myNum = 0;
        try {
            String myStr = str;
            myNum = Integer.parseInt(myStr);
        } catch (NumberFormatException e) {
            System.err.println("Error");
        }
        System.out.println("myStr: "+ mystr+", myNum: "+ myNum);
    }
    public static void main(String[] args) {
        Apps obj =new Apps();
        obj.doStuff("9009");
    }
}
What is the result?

Explanation

The code will compile successfully. The main method creates an instance of the Apps class and calls the doStuff method with the argument "9009". Inside the doStuff method, a local variable myStr is created and assigned the value of the argument "9009". Then, Integer.parseInt() is used to convert myStr to an integer and assign it to the variable myNum. Since "9009" can be successfully parsed as an integer, the catch block is not executed. Finally, the values of mystr and myNum are printed, which are "7007" and "9009" respectively.

Submit
45. Given the code fragment:
LocalDate date1 = LocalDate.now();
LocalDate date2 = LocalDate.of(2014, 6, 20);
LocalDate date3 = LocalDate.parse("2014-06-20", DateTimeFormatter.ISO_DATE);
System.out.println("date1 = " + date1);
System.out.println("date2 = " + date2);
System.out.println("date3 = " + date3);
Assume that the system date is June 20, 2014. What is the result?

Explanation

The code fragment initializes three LocalDate objects. date1 is assigned the current system date using the LocalDate.now() method. date2 is assigned the specific date June 20, 2014 using the LocalDate.of() method. date3 is assigned the date June 20, 2014 by parsing the string "2014-06-20" using the LocalDate.parse() method with the DateTimeFormatter.ISO_DATE format. The code then prints the values of date1, date2, and date3. Since the system date is June 20, 2014, all three dates will have the same value of "2014-06-20".

Submit
46. Given the code fragment:
public static void main(String[] args) {
    String numStr = "123";
    String boolStr = "TRUE";
    Integer i1 = Integer.parseInt(numStr);
    Boolean b1 = Boolean.parseBoolean(boolStr);
    System.out.println(i1 + ": " + b1);
    int i2 = Integer.valueOf(numStr);
    boolean b2 = Boolean.valueOf(boolStr);
    System.out.println(i2 + ": " + b2);
}
What is the result?

Explanation

The code fragment first uses the `parseInt` method to convert the string "123" to an integer, and then uses the `parseBoolean` method to convert the string "TRUE" to a boolean. The resulting values are then printed.

Next, the `valueOf` method is used to convert the string "123" to an int, and the string "TRUE" to a boolean. The resulting values are printed again.

Since the string "TRUE" is converted to `true` when using `parseBoolean` and `valueOf`, the output will be "123: true" for both print statements.

Submit
47.
Given:
    String stuff = "TV";
    String res = null;
    if(stuff.equals("TV")){
        res = "Walter";
    }else if(stuff.equals("Movie")){
        res = "White";
    }else{
        res = "No Result";
    }
Which code fragment can replace the if block, and it has the same effect?

Explanation

The given code fragment can replace the if block because it uses the ternary operator to achieve the same effect. It checks if "stuff" equals "TV", and if so, assigns "Walter" to "res". If not, it checks if "stuff" equals "Movie", and if so, assigns "White" to "res". Otherwise, it assigns "No Result" to "res". This is the same logic as the original if-else if-else statement.

Submit
48. Given the following code for a Planet object:
public class Planet{
    public String name;
    public int moons;
    public Planet(String name, int moons) {
        this.name = name;
        this.moons = moons;
    }
}
And the following main method:
public static void main(String[] args) {
    Planet[] planets = {
        new Planet("Mercury", 0),
        new Planet("Venus", 0),
        new Planet("Earth", 1),
        new Planet("Mars", 2)
    };
    System.out.println(planets);
    System.out.println(planets[2]);
    System.out.println(planets[2].moons);
}
What is the output?

Explanation

The first line of output, "[LPlanets.Planet;@15db9742", is the default string representation of an array object. The "@" symbol indicates that it is an array, followed by the fully qualified class name "LPlanets.Planet", and the hash code "15db9742" of the array object.

The second line of output, "Planets.Planet@6d06d69c", is the default string representation of a Planet object. The "@" symbol indicates that it is an object, followed by the fully qualified class name "Planets.Planet", and the hash code "6d06d69c" of the Planet object.

The third line of output, "1", is the value of the "moons" variable of the Planet object at index 2 in the "planets" array.

Submit
49. The following grid shows the state of a 2D array: ​​​​​​​ This grid is created with the following code: char[][] grid = new char[3][3]; grid[1][1] = 'x'; grid[0][0] = 'o'; grid[2][1] = 'x'; grid[0][1] = 'o'; grid[2][2] = 'x'; grid[1][2] = 'o'; //line n1 Which line of code, when inserted in place of //line n1, adds an x into the grid so that the grid contains three consecutive x's?

Explanation

The correct answer is grid[2][0] = 'x'; This line of code inserts an 'x' into the grid at position (2, 0), which is the bottom-left corner of the grid. This adds a third consecutive 'x' to the grid, as the other two 'x's are already present at positions (1, 1) and (2, 1).

Submit
50. Given the code fragments:
interface Exportable{
    void export();
}
class Tool implements Exportable{
    protected void export(){ //line n1
        System.out.println("Tool::export");
    }
}
class ReportTool extends Tool implements Exportable{
    public void export(){ //line n2
        System.out.println("Rtool::export");
    }
    public static void main(String[] args) {
        Tool aTool = new ReportTool();
        Tool bTool = new Tool();
        callExport(aTool);
        callExport(bTool);
    }
    public static void callExport(Exportable ex){
        ex.export();
    }
}
What is the result?

Explanation

The code fails to compile at line n1 because the method "export" in the "Tool" class is declared as protected, which means it can only be accessed within the same package or by subclasses. However, in the "ReportTool" class, which is a subclass of "Tool", the "export" method is declared as public. This violates the rule of overriding methods, where the access level of the overridden method must be the same or more accessible than the original method. Therefore, the code fails to compile at line n1.

Submit
51. Given the code fragment:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class D {
    public static void main(String[] args) {
        String[] arr = {"Hi", "How", "Are", "You"};
        List<String> arrList = new ArrayList(Arrays.asList(arr));
        if (arrList.removeIf((String s) -> {return s.length() <= 2;})){
            System.out.println(s + " removed");
        }
    }
}
What is the result?

Explanation

The code fails to compile because the lambda expression used in the `removeIf` method is missing the parameter name. The correct syntax for the lambda expression should be `(String s) -> {return s.length()

Submit
52. Given the code fragment:
class TT{
    public static void main(String[] args) {
        String names[] = {"Thomas", "Peter", "Joseph"};
        String pwd[] = new String[3];
        int idx = 0;
        try {
            for (String n : names) {
                pwd[idx] = n.substring(2, 6);
                idx++;
            }
        } catch (Exception e) {
            System.out.println("Invalid Names");
        }
        for (String p : pwd) {
            System.out.println(p);
        }
    }
}
What is the result?

Explanation

The code attempts to assign substrings of length 4 from each name in the "names" array to corresponding positions in the "pwd" array. However, the substring method is called with indices 2 and 6, which is out of bounds for the names "Thomas" and "Joseph". This causes an exception to be thrown and the catch block is executed, printing "Invalid Names". Since the exception is caught, the code continues to execute and the "pwd" array remains uninitialized, resulting in null values being printed for the remaining elements.

Submit
53. Given:
class Vehicle{
    String type ="4W";
    int maxSpeed = 100;
    Vehicle(String type, int maxSpeed) {
        this.type = type;
        this.maxSpeed = maxSpeed;
    }
}
class Car extends Vehicle{
    String trans;
    Car() { //line n1
        this.trans = trans;
    }
    public Car(String trans) {
        super("4W", 150);
        this.trans = trans;
    }
    Car(String type, int maxSpeed,String trans) {
        super(type, maxSpeed);
        this.trans = trans; //line n2
    }
}
And given the code fragment:
7.  Car c1 = new Car("Auto");
8.  Car c2 = new Car("4W", 150 , "Manual");
9.  System.out.println(c1.type + " " + c1.maxSpeed + " "+ c1.trans);
10. System.out.println(c2.type + " " + c2.maxSpeed + " "+ c2.trans);
What is the result?

Explanation

The code fails to compile at line n1 because the default constructor in the Car class does not initialize the "trans" variable. The "trans" variable is then used in line n1 without being initialized, causing a compilation error.

Submit
54. Given:
public class X {

    static int i;
    int j;

    public static void main(String[] args) {
        X x1 = new X();
        X x2 = new X();
        x1.i = 3;
        x1.j = 4;
        x2.i = 5;
        x2.j = 6;
        System.out.println(
                x1.i + " "
                + x1.j + " "
                + x2.i + " "
                + x2.j);
    }
}
What is the result?

Explanation

The result is 5 4 5 6 because the static variable "i" is shared among all instances of the class X. When x1.i is assigned the value 3, it also changes the value of x2.i to 3. However, the non-static variable "j" is unique to each instance, so x1.j remains 4 and x2.j remains 6. Therefore, the final output is 5 4 5 6.

Submit
55. Given the following classes:
class Employee{
    public int salary;
}
class Manager extends Employee{
    public int budget;
}
class Director extends Manager{
    public int stackOptions;
}
And Given the following main method:
public static void main(String[] args){
    Employee employee = new Employee();
    Manager manager = new Manager();
    Director director = new Director();
    //line n1
}
Which two options fail to compile when placed at line n1 of the main method?

Explanation

The options "employee.stackOptions = 334_323;" and "employee.budget = 200_000;" fail to compile when placed at line n1 of the main method. This is because the variable "employee" is declared as an object of the class Employee, which does not have the properties "stackOptions" and "budget". These properties are only available in the subclasses Manager and Director. Therefore, trying to access these properties on an object of the Employee class will result in a compilation error.

Submit
56. Given the code fragment:
public static void main(String[] args) {
    System.out.println("Result A " + 0 + 1);
    System.out.println("Result B "+ (1) + (2));
}
What is the result?

Explanation

The code fragment is concatenating strings and numbers using the + operator. In the first print statement, the string "Result A " is concatenated with the number 0, which is then concatenated with the number 1. Since the + operator has left-to-right associativity, the concatenation is done from left to right. Therefore, the result is "Result A 01". In the second print statement, the string "Result B " is concatenated with the number 1, which is then concatenated with the number 2. Again, the concatenation is done from left to right, resulting in "Result B 12".

Submit
57.
public static void main(String[] args) {
    int [] arr = {1, 2, 3, 4};
    int i = 0;
    do {
        System.out.print(arr[i] + " ");
        i++;
    } while (i<arr.length -1);
}
Given the code fragment: What is the result?

Explanation

The given code fragment uses a do-while loop to print the elements of the array "arr". The loop iterates until the value of "i" is less than the length of the array minus 1.

In the given array, {1, 2, 3, 4}, the length is 4. The loop starts with "i" as 0 and prints the element at index 0, which is 1. Then, it increments "i" by 1 and checks if it is less than 4-1=3. Since it is, the loop continues and prints the element at index 1, which is 2. This process repeats for the elements at index 2 and 3, resulting in the output "1 2 3".

Therefore, the correct answer is "1 2 3".

Submit
58. Given the code fragment:
1.  public static void main(String[] args) {
2.      int x = 5;
3.      while (isAvailable(x)) {
4.          System.out.print(x);
5.      }
6.  }
7.  public static boolean isAvailable(int x) {
8.      return x-- > 0 ? true : false;
9.  }
Which modification enables the code to print 54321?

Explanation

The correct modification is to replace line 4 with System.out.print(x--). This is because the post-decrement operator (x--) will first use the current value of x in the print statement, and then decrement x by 1. This will result in the code printing the values of x in descending order (5, 4, 3, 2, 1).

Submit
59. Given:
class Test {
    public static void main(String[] args) {
        String[][] chs = new String[2][];
        chs[0] = new String[2];
        chs[1] = new String[5];
        int i = 97;
        for (int a = 0; a < chs.length; a++) {
            for (int b = 0; b < chs.length; b++) {
                chs[a][b] = "" + i;
                i++;
            }
        }
        for (String[] ca : chs) {
            for (String c : ca) {
                System.out.print(c + "");
            }
            System.out.println();
        }
    }
}
What is the result?

Explanation

The code initializes a 2D array of Strings called "chs". The first row of the array has 2 elements and the second row has 5 elements. The variable "i" is initialized to 97. The nested for loop iterates over the rows and columns of the array, assigning consecutive character values to each element starting from 'a'. The resulting array is then printed. The output is "9798" on the first line and "99100nullnullnull" on the second line. This is because the first row of the array has elements "97" and "98", while the second row has elements "99", "100", and null values for the remaining columns.

Submit
60. Given the code fragment:
public static void main(String[] args) {
    String date = LocalDate.parse("2014-05-04").
    format(DateTimeFormatter.ISO_DATE_TIME);
    System.out.println(date);
}
What is the result?

Explanation

The code fragment will throw an exception at runtime because the format() method is being called on a LocalDate object, which does not have a time component. The DateTimeFormatter.ISO_DATE_TIME formatter is expecting a LocalDateTime object, so it will throw an exception.

Submit
61. Which two statements are true?

Explanation

The given answer is correct because Error is a subclass of Throwable, which means it is a type of throwable object that can be thrown and caught in Java. Additionally, the Error class is extendable, meaning it can be subclassed to create new error classes with specific functionalities.

Submit
62. Given the code fragment:
    nums1[] =1. Given the code fragment:
    int nums1[] = new int[3];
    int nums2[] = {1,2,3,4,5};
    nums1 = nums2;
    for (int x : nums1) {
        System.out.print(x + ": ");
    }
    What is the result? new int[3];
    int nums2[] = {1,2,3,4,5};
    nums1 = nums2;
    for (int x : nums1) {
        System.out.print(x + ": ");
    }
What is the result?

Explanation

The result of the code fragment is "1: 2: 3: 4: 5:". The code creates two arrays, nums1 and nums2. nums1 is initially an empty array with a length of 3. nums2 is an array with 5 elements. The line "nums1 = nums2;" assigns the reference of nums2 to nums1, meaning that both arrays now refer to the same memory location. The for-each loop then iterates over the elements of nums1, printing each element followed by a colon and a space. Since nums1 now refers to the elements of nums2, the output is "1: 2: 3: 4: 5:".

Submit
63. Given the code fragment:
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
class R {
    public static void main(String[] args) {
        LocalDateTime dt = LocalDateTime.of(2014, 7, 31, 1, 1);
        dt.plusDays(30);
        dt.plusMonths(1);
        System.out.println(dt.format(DateTimeFormatter.ISO_DATE));
    }
}
What is the result?

Explanation

The code creates a LocalDateTime object with the date and time set to July 31, 2014, 1:01 AM. The code then calls the plusDays(30) and plusMonths(1) methods on the LocalDateTime object, which returns a new LocalDateTime object with the specified number of days and months added. However, the code does not assign the new LocalDateTime objects to any variable, so the original dt object remains unchanged. Finally, the code prints the date in ISO_DATE format, which is "yyyy-MM-dd". Therefore, the result is "2014-07-31".

Submit
64. Given the code fragment:
public static void main(String[] args) {
    Short s1 = 200;
    Integer s2 = 400;
    Long s3 = (long) s1 + s2; // line n1
    String s4 = (String) (s3 * s2 ); // line n2
    System.out.println("Sum is" + s4);
}
What is the result?

Explanation

The code fails to compile at line n2 because it is attempting to cast a result of type Long to a String, which is not possible. The multiplication of a Long and an Integer results in a Long, and therefore cannot be directly cast to a String.

Submit
65. Given the code fragment:
public static void main(String[] args) {
    int [] stack = {10,20,30};
    int size = 3;
    int idx = 0;
    /*line n1*/
    System.out.println("The Top element: "+ stack[idx]);
}
Which code fragment, inserted at line n1, prints the Top element: 30?

Explanation

The code fragment "do { idx++; } while (idx

Submit
66. Given the code fragment:
public static void main(String[] args) {
    double discount = 0;
    int qty= Integer.parseInt(args[0]);
    //line n1
}
And given the requirements: * if the value of the qty variable is greater than or equal to 90 discounts = 0.5 * if the value of the qty variable is between 80 and 90 discounts = 0.2 Which two code fragments can be independently placed at line n1 to meet the requirements?

Explanation

The first code fragment checks if the value of qty is greater than or equal to 90, and if it is, it sets the discount to 0.5. The second code fragment checks if the value of qty is between 80 and 90, and if it is, it sets the discount to 0.2. Both of these code fragments independently meet the requirements specified in the question. The third code fragment is also correct as it uses a ternary operator to set the discount based on the value of qty.

Submit
67. Given the code fragment:
public class Test{
    public static void main(String[] args) {
        //line n1
        switch (x) {
            case 1:
                System.out.println("One");
                break;
            case 2:
                System.out.println("Two");
                break;
        }
    }
}
Which three code fragments can be independently inserted at line n1 to enable the code to print One?

Explanation

not-available-via-ai

Submit
68. Given:
class Equal{
    public static void main(String[] args) {
        String str1 = "Java";
        String [] str2 = {"J", "a", "v", "a"};
        String str3= "";
        for (String str : str2) {
            str3 = str3 + str;
        }
        boolean b1= (str1 == str3);
        boolean b2= (str1.equals(str3));
        System.out.print(b1+ ", "+b2);
    }
}
What is the result?

Explanation

The result of the code is false, true. This is because the == operator in Java compares the references of two objects, not their content. In this case, str1 and str3 are two different objects, even though their content is the same. Therefore, b1 is false. On the other hand, the equals() method compares the content of two objects. Since str1 and str3 have the same content ("Java"), b2 is true.

Submit
69. Given the following class:
public class Rectangle{
    private double length;
    private double height;
    private double area;
    public void setLength(double length) {
        this.length = length;
    }
    public void setHeight(double height) {
        this.height = height;
    }
    public void setArea() {
        this.area = length * height;
    }
}
Which two changes would encapsulate this class and ensure that the area field is always equals to length * height whenever the Rectangle class is used?

Explanation

The correct answer is to call the setArea method at the end of the setLength method and at the end of the setHeight method. This ensures that whenever the length or height of the rectangle is set, the area is automatically updated to be equal to the product of the length and height. By calling the setArea method at the end of both setLength and setHeight, we guarantee that the area is always calculated correctly and encapsulated within the class.

Submit
70. Given the code fragment:
import java.util.ArrayList;
class R{
    public static void main(String[] args) {
        ArrayList<Integer> points = new ArrayList<>();
        points.add(1);
        points.add(2);
        points.add(3);
        points.add(4);
        points.add(null);
        points.remove(2);
        points.remove(null);
        System.out.println(points);
    }
}
What is the result?

Explanation

The code creates an ArrayList called "points" and adds the integers 1, 2, 3, and 4 to it. It then adds a null value to the list. The code then removes the element at index 2, which is the integer 3. Finally, it removes the null value from the list. The resulting ArrayList will contain the integers 1, 2, and 4, so the correct answer is [1, 2, 4].

Submit
71. Given the code fragment:
public static void main(String[] args) {
    int array[] = { 0, 20, 30, 40, 50};
    int x= array.length;
    /*line n1*/
}
Which two code fragments can be independently inserted at line n1 enable the code to print the elements of the array in reverse order? (Choose two)

Explanation

The two code fragments that can be independently inserted at line n1 to print the elements of the array in reverse order are:

1. while(x > 0) {
x--;
System.out.print(array[x]);
}

This code fragment uses a while loop to decrement the value of x and print the element at index x of the array. It continues until x becomes 0.

2. while (x > 0 ) {
System.out.print(array[--x]);
}

This code fragment also uses a while loop, but it decrements the value of x and then immediately uses the updated value to print the element at index x of the array. It continues until x becomes 0.

Submit
72. Given:
default void print() {
}
Which statement is true?

Explanation

The given method is declared with the "default" keyword, which is used to define a default method in an interface. Default methods were introduced in Java 8 to allow adding new methods to existing interfaces without breaking the implementation of classes that implement the interface. Therefore, the statement "This method can be used only in an interface" is true, as default methods can only be declared within an interface.

Submit
73. Given the code fragment:
public static void main(String[] args) {
    int x = 100;
    int a = x++;
    int b = ++x;
    int c = x++;
    int d = (a < b) ? (a < c) ? a : (b < c) ? b : c;
    System.out.println(d);
}
What is the result?

Explanation

not-available-via-ai

Submit
74. Which three are advantages of the Java exception mechanism? (Choose three)

Explanation

The Java exception mechanism provides several advantages. Firstly, it improves the program structure by separating the error handling code from the normal program function. This makes the code more organized and easier to read and maintain. Secondly, it allows the programmer to choose where to handle exceptions, giving them flexibility in deciding how to handle different types of errors. Lastly, it allows the creation of new exceptions that are specifically tailored to the program being created, enabling more precise error handling and customization.

Submit
75. Given the code fragment:
class Student{
    String name;
    int age;
}
And
1.public class Test{
2.  public static void main(String[] args) {
3.      Student s1 = new Student();
4.      Student s2 = new Student();
5.      Student s3 = new Student();
6.      s1 = s3;
7.      s3 = s2;
8.      s2 = null;
9.  }
10.}
Which statement is true?

Explanation

After line 8, one object is eligible for garbage collection. This is because the object that was originally referenced by s2 is set to null, meaning that there are no more references to that object in the code. Therefore, it becomes eligible for garbage collection. The objects referenced by s1 and s3 are still being referenced, so they are not eligible for garbage collection.

Submit
76. Given:
class C2{
    public void displayC2(){
        System.out.print("c2");
    }
}
interface I{
    public void displayI();
}
class C1 extends C2 implements I{
    public void displayI(){
        System.out.println("c1");
    }
}
And given the code fragment:
C2 obj1 = new C1();
I obj2 = new C1();
C2 s = obj2;
I t = obj1;
t.displayI();
s.displayC2();
What is the result?

Explanation

The code will fail to compile because the reference variable 's' of type C2 cannot access the method displayC2() since it is not defined in the interface I.

Submit
77. Given the code fragment:
public static void main(String[] args) {
    int data[] = {2010, 2013, 2014, 2015, 2014};
    int key = 2014;
    int count = 0;
    for (int e : data) {
        if(e!= key){
            continue;
            count++;
        }
    }
    System.out.print(count+ " Found");
}
What is the result?

Explanation

The code will not compile because there is a syntax error in the line "System.out.print(count+ " Found");" The quotation marks are not properly closed, causing a compilation error.

Submit
78.
public class Test{
    void readCard(int cardNo) throws Exception{
        System.out.println("Reading Card");
    }
    void checkCard(int cardNo) throws RuntimeException{ // line n1
        System.out.println("Checking Card");
    }
    public static void main(String[] args) {
        Test ex = new Test();
        int cardNo = 12344;
        ex.checkCard(cardNo); //line n2
        ex.readCard(cardNo); //line n3
    }
}
Given the code fragment: What is the result?

Explanation

The code compiles successfully and there are no syntax errors. The method `checkCard` throws a `RuntimeException`, which is a type of unchecked exception and does not need to be declared in the method signature. However, the method `readCard` throws a checked exception `Exception`, which needs to be declared in the method signature or handled using a try-catch block. Since the method `readCard` does not declare or handle the exception, the code fails to compile at line n3 where the method is called.

Submit
79.
Given:
class Tests2{
    int a1;
    public static void doProduct(int a) {
        a = a * a;
    }
    public static void doString(StringBuilder s) {
        s.append(" "+ s);
    }
    public static void main(String[] args) {
        Tests2 item = new Tests2();
        item.a1 = 11;
        StringBuilder sb = new StringBuilder("Hello");
        Integer i = 10;
        doProduct(i);
        doString(sb);
        doProduct(item.a1);
        System.out.println(i+ " "+ sb + " " +item.a1);
    }
}
What is the result?

Explanation

The code defines a class Tests2 with three methods: doProduct, doString, and main. In the main method, a new instance of Tests2 is created and the variable a1 is assigned the value 11. A StringBuilder object sb is also created with the initial value "Hello". An Integer object i is created with the value 10.

The doProduct method takes an integer parameter and multiplies it by itself, but it does not modify the original value. The doString method takes a StringBuilder object and appends a space and the string representation of the object to itself.

In the main method, the doProduct method is called with the i variable as an argument, but since it is an Integer object, it is passed by value and the original value of i is not modified. The doString method is called with the sb variable, which modifies the sb object by appending a space and itself to it. Finally, the doProduct method is called with the item.a1 variable, which modifies the value of item.a1 by squaring it.

The result of the program is then printed, which is "10 Hello Hello 11".

Submit
80. Given:
public class Test{
    public static void main(String[] args) {
        Test obj = new Test();
        short letter = 97;
        int letter2 = 98;
        System.out.print((char) letter + " ");
        System.out.print((char) letter2);
    }
}
What is the result?

Explanation

The code first creates an instance of the Test class. Then, it assigns the value 97 to the variable "letter" of type short and the value 98 to the variable "letter2" of type int.

In the first print statement, it casts the value of "letter" to a char and prints it, which is 'a'.

In the second print statement, it casts the value of "letter2" to a char and prints it, which is 'b'.

Therefore, the result is "a b".

Submit
81. Given the code fragment:
public static void main(String[] args) {
    int a = 10;
    float b = 10.25f;
    double c = 100;
    a = b; // line 7
    b = a; // line 8
    c = b; // line 9
    c = a; // line 10
}
Which change enables the code fragment to compile successfully?

Explanation

In Java, you cannot assign a value of a larger data type to a variable of a smaller data type without explicit casting. In line 7, the variable 'b' of type float is being assigned to the variable 'a' of type int without casting, which causes a compilation error. To fix this, you need to cast the value of 'b' to an int using (int) before assigning it to 'a'. This will allow the code to compile successfully.

Submit
82. Given:
abstract class Planet{
    protected void revolve(){ //line n1
    }
    abstract void rotate(); //line n2
}
class Earth extends Planet{
    void revolve(){ //line n3
    }
    protected void rotate(){ //line n4
    }
}
Which two modifications, made independently, enable the code to compile?

Explanation

Making the method at line n3 public in the Earth class allows it to override the protected method in the Planet class. This is because the access level of the overridden method must be the same or less restrictive. Making the method at line n3 protected in the Earth class also allows it to override the protected method in the Planet class, as protected access is less restrictive than default access. This ensures that the code compiles without any errors.

Submit
83. Given:
class Student{
    String name;
    public Student(String name) {
        this.name = name;
    }
}
class TestS{
    public static void main(String[] args) {
        Student[] students = new Student[3];
        students[1] = new Student("Richard");
        students[2] = new Student("Donald");
        for (Student s : students) {
            System.out.println("" + s.name);
        }
    }
}
What is the result?

Explanation

The code will throw a NullPointerException at runtime. This is because the array students is declared with a size of 3, but only two elements are initialized. The first element remains null, so when the for loop tries to access the name of the first element, it throws a NullPointerException.

Submit
84.
Given the following class:
class CheckingAccount{
    public int amount;
    //line n1
}
And given the following main method, located in another class:
public static void main (String [] args){
    CheckingAccount acct = new CheckingAccount();
    //line n2
}
Which three pieces of code, when inserted independently, set the value of amount to 100?

Explanation

At line n1, inserting "this.amount = 100;" or "amount = 100;" will set the value of the "amount" variable to 100. This is because both "this.amount" and "amount" refer to the "amount" variable within the current instance of the CheckingAccount class.

At line n2, inserting "acct.amount = 100;" will set the value of the "amount" variable in the "acct" object to 100. This is because "acct" is an instance of the CheckingAccount class and "acct.amount" refers to the "amount" variable within that instance.

Submit
85. Which statement best describes encapsulation?

Explanation

Encapsulation is a concept in object-oriented programming that ensures the encapsulated data within an object is not directly accessible from other objects. Instead, access to the object's fields is only allowed through access methods, such as getters and setters. This helps to maintain data integrity and control how the object's data is manipulated. By restricting direct access to the object's fields, encapsulation promotes encapsulated data to be accessed and modified in a controlled manner, enhancing code security and maintainability.

Submit
86. Given the code fragment:
import java.io.IOException;
class X{
    public void printFileContent(){ //line 2
        /*Code goes here*/
        throw new IOException(); // line 4
    }
}
public class Test{
    public static void main(String[] args) { // line 8
        X xobj = new X();
        xobj.printFileContent(); // line 10
        // line 11
    }
}
Which two modifications should you make so that the code compiles successful?

Explanation

The code compiles successfully when line 8 is modified to include "throws IOException" in the main method signature. This is because the main method calls the printFileContent method, which throws an IOException. Therefore, the main method needs to declare that it throws this exception. Additionally, line 2 needs to be modified to include "throws IOException" in the printFileContent method signature. This is because the method throws an IOException, so it needs to declare this in its signature.

Submit
87. Which two class definitions fail to compile?

Explanation

The first class definition fails to compile because a class cannot be both final and abstract at the same time. The second class definition fails to compile because a final variable must be initialized when it is declared, but the variable "m" is not initialized.

Submit
88. Given the code fragment:
abstract class Toy{
    int price;
    //line n1
}
Which three code fragments are valid at line n1?

Explanation

The three valid code fragments at line n1 are:
1. public abstract int computeDiscount(); - This is valid because it declares an abstract method in the abstract class Toy.
2. public int calculatePrice(){ return price; } - This is valid because it declares a non-abstract method in the abstract class Toy, which returns the price.
3. public static void insertToy(){ /* code goes here*/ } - This is valid because it declares a static method in the abstract class Toy.

Submit
89. Given:
A.java:
class A{
    public void test(){
        System.out.println("A ");
    }
}
B.java:
class B extends A{
    public void test(){
        System.out.println("B ");
    }
}
C.java:
class C extends A{
    public void test(){
        System.out.println("C ");
    }
    public static void main(String[] args) {
        A b1 = new A();
        A b2 = new C();
        b1 = (A) b2; //line n1
        A b3 = (B) b2; //line n2
        b1.test();
        b3.test();
    }
}
What is the result?

Explanation

The code compiles without any errors. However, at line n2, a ClassCastException is thrown at runtime because b2 is an instance of class C and cannot be cast to class B.

Submit
90. Which three statements are true about the structure of a Java class?

Explanation

The first statement is true because a field in a Java class does not need to be initialized before it is used. The second statement is true because methods are indeed mandatory components of a class. The fourth statement is true because a class can have overloaded static methods, which means multiple methods with the same name but different parameters. The fifth statement is true because a method can have the same name as a field, although it is not recommended for clarity and readability.

Submit
91. Given:
interface CanFly {
    String type = "A";
    void fly();
    ____ String getType() {
        return type;
    }
}
Which of the following inserted independently can fill in the ____ blank in this code to make it compile?

Explanation

The correct answer is "static" because interfaces can have static methods, and adding the "static" keyword before the method declaration allows the method to be called without an instance of the interface.

Submit
92. Given the following class:
public class CheckingAccount{
    public int amount;
    public CheckingAccount(int amount){
        this.amount = amount;
    }
    public int getAmount(){
        return amount;
    }
    public void checkingAmount(int x){
        amount += x;
    }
}
And given the following main ethos, located in another class:
public static void main(String[] args) {
    CheckingAccount acct = new CheckingAccount((int)(Math.random()*1000));
    //line n1
    System.out.println(acct.getAmount());
}
Which three lines, when inserted independently at line n1, cause the program to print a 0 balance? (Choose 3)

Explanation

The correct answer choices are acct.checkingAmount(-acct.getAmount()), acct.checkingAmount(-acct.amount), and acct.amount = 0.


- acct.checkingAmount(-acct.getAmount()) subtracts the current amount from itself, resulting in a balance of 0.
- acct.checkingAmount(-acct.amount) subtracts the current amount from itself, resulting in a balance of 0.
- acct.amount = 0 directly sets the amount to 0, resulting in a balance of 0.

Submit
93. Which two statements are true about a Java class?

Explanation

The main method can be overloaded, which means that multiple main methods can exist in a Java class with different parameter lists. This allows for flexibility in how the main method is used.

The Object class is the root of the class hierarchy in Java. This means that all other classes in Java are either directly or indirectly derived from the Object class. This hierarchy allows for the inheritance and polymorphism features in Java.

Submit
94. Which three statements are true about exception handling? (Choose tree)

Explanation

All subclasses of the Exception class except the RuntimeException class are checked exceptions: This statement is true. Checked exceptions are exceptions that must be either caught or declared to be thrown.

The parameter in a catch block is of Throwable type: This statement is true. The catch block can catch exceptions of any type that is a subclass of the Throwable class.

All subclasses of the RuntimeException class are recoverable: This statement is true. RuntimeExceptions are unchecked exceptions that typically occur due to programming errors and are not expected to be recovered from.

Submit
95. Given:
public interface Readable {
    public void readBook();
    public void setBookMark();
}
abstract class Book implements Readable { // line n1
    public void readBook(){
    }
    // line n2
}
class EBook extends Book { // line n3
    public void readBook(){
    }
    // line n4
}
Which two option enables the code to compile?

Explanation

The code needs to be modified in order to compile. At line n3, the code should be replaced with "abstract class EBook extends Book {" to correctly extend the Book class. At line n4, the code should be inserted to implement the setBookMark() method, which is required by the Readable interface. This modification allows the code to compile successfully.

Submit
View My Results

Quiz Review Timeline (Updated): Mar 22, 2023 +

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
  • Aug 09, 2018
    Quiz Created by
    Catherine Halcomb
Cancel
  • All
    All (95)
  • Unanswered
    Unanswered ()
  • Answered
    Answered ()
Given the code fragment: ...
Given the code snippet from a compiled Java source file: ...
What is the name of the Java concept that uses access modifiers to...
You are asked to create a method that accepts an array of integers and...
Given: ...
Given the code from the Greeting.java file: ...
Given: ...
Given: ...
Given the following class declarations: ...
Given the code fragment: ...
Given: ...
Given the code fragment: ...
Given: ...
Given: ...
Given the code fragment: ...
Given: ...
Given the following main method: ...
Given the code fragment:...
Given: ...
Which statement is true about Java byte code?
Given the code fragment: ...
Given the code fragment: ...
Given the following code: ...
Given: ...
Given the code fragment: ...
Given: ...
Given the code fragment: ...
Given the code fragment: ...
Given the code fragment: ...
Given: ...
Which three statements describe the object-oriented features of the...
Given: ...
Given the code fragment: ...
Given: ...
Which statement will empty the contents of a StringBuilder variable...
Given: ...
Given the code fragment: ...
Given the code fragment: ...
Given: ...
Given the code fragment: ...
Given: ...
Given the code fragment from three files: ...
Given: ...
Given: ...
Given the code fragment: ...
Given the code fragment: ...
Given: ...
Given the following code for a Planet object: ...
The following grid shows the state of a 2D array: ...
Given the code fragments: ...
Given the code fragment:...
Given the code fragment: ...
Given: ...
Given: ...
Given the following classes: ...
Given the code fragment: ...
Public static void main(String[] args) { ...
Given the code fragment: ...
Given: ...
Given the code fragment: ...
Which two statements are true?
Given the code fragment: ...
Given the code fragment: ...
Given the code fragment: ...
Given the code fragment: ...
Given the code fragment: ...
Given the code fragment: ...
Given: ...
Given the following class: ...
Given the code fragment: ...
Given the code fragment: ...
Given: default void print() { } Which statement is true?
Given the code fragment: ...
Which three are advantages of the Java exception mechanism? (Choose...
Given the code fragment: ...
Given: ...
Given the code fragment: ...
Public class Test{ ...
Given: ...
Given: ...
Given the code fragment: ...
Given: ...
Given: ...
Given the following class: ...
Which statement best describes encapsulation?
Given the code fragment: ...
Which two class definitions fail to compile?
Given the code fragment: ...
Given: ...
Which three statements are true about the structure of a Java class?
Given: ...
Given the following class: ...
Which two statements are true about a Java class?
Which three statements are true about exception handling? (Choose...
Given:...
Alert!

Advertisement