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: 1442 | Total Attempts: 6,630,300
| Attempts: 866
SettingsSettings
Please wait...
  • 1/95 Questions

    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?

    • Int e = 0; e
    • Int e = 0; e < 5; e += 2
    • Int e = 1; e
    • Int e = 1; e < 5; e += 2
Please wait...
About This 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 the 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 See moreto sit for the test or need more study hours.

Java Certification Test! Programming Trivia Questions Quiz - Quiz

Quiz Preview

  • 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

    • Java MyFile 0 1 2 3

    • Java MyFile 1 3 2 2

    • Java MyFile 1 2 2 3 4

    • Java MyFile 2 2 2

    Correct Answer
    A. Java MyFile 1 3 2 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.

    Rate this question:

  • 3. 

    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?

    • Static int[] findMax(int max)

    • Static int findMax(int[] numbers)

    • Final int[] findMax(int [] a)

    • Public int findMax(int[] numbers)

    Correct Answer
    A. Static int findMax(int[] numbers)
    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".

    Rate this question:

  • 4. 

    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?

    • ArrayList<Tiger> myList = new ArrayList<>(); myList.add(new Cat());

    • ArrayList<Hunter> myList = new ArrayList<>(); myList.add(new Cat());

    • ArrayList<Animal> myList = new ArrayList<>(); myList.add(new Tiger());

    • ArrayList<Hunter> myList = new ArrayList<>(); myList.add(new Tiger());

    • ArrayList<Animal> myList = new ArrayList<>(); myList.add(new Cat());

    Correct Answer
    A. ArrayList<Tiger> myList = new ArrayList<>(); myList.add(new Cat());
    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.

    Rate this question:

  • 5. 

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

    • Polymorphism.

    • Instantiation.

    • Encapsulation.

    • Inheritance.

    • Abstraction.

    Correct Answer
    A. Encapsulation.
    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.

    Rate this question:

  • 6. 

    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?

    • Welcome Log 1: 0

    • Welcome Log 2: 1

    • Hello Log 2: 1

    • Hello Log 1: 0

    Correct Answer
    A. Welcome Log 2: 1
    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.

    Rate this question:

  • 7. 

    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?

    • Javac Greeting java Greeting Duke

    • Javac Greeting.java Duke java Greeting

    • Javac Greeting.java java Greeting Duke

    • Javac Greeting.java java Greeting.class Duke

    Correct Answer
    A. Javac Greeting.java java Greeting Duke
    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.

    Rate this question:

  • 8. 

    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?

    • 3 5

    • 9 25

    • 0 0

    • Compilation fails.

    Correct Answer
    A. 3 5
    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.

    Rate this question:

  • 9. 

    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?

    • 10 : 0

    • 0 : 0

    • Compilation fails on line n1.

    • Compilation fails on line n2.

    • Compilation fails on line n3.

    Correct Answer
    A. Compilation fails on line n2.
    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.

    Rate this question:

  • 10. 

    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?

    • Super.r=r; this.c=c;

    • Super(r); this(c);

    • Super(r); this.c=c;

    • This.c=r; super(c);

    Correct Answer
    A. Super(r); this.c=c;
    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.

    Rate this question:

  • 11. 

    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?

    • 10 : 30 : 5

    • 10 : 22 : 22

    • 10 : 22 : 20

    • 10 : 22 : 5

    Correct Answer
    A. 10 : 22 : 22
    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".

    Rate this question:

  • 12. 

    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?

    • String main 1

    • Int main 1

    • Object main 1

    • Compilation fails.

    • An exception is thrown at runtime.

    Correct Answer
    A. String main 1
    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.

    Rate this question:

  • 13. 

    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?

    • A DateTimeException is thrown at runtime.

    • Compilation fails.

    • 2012-02-10

    • 2012-02-11

    Correct Answer
    A. A DateTimeException is thrown at runtime.
    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.

    Rate this question:

  • 14. 

    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?

    • 5 : 5

    • 10 : 10

    • 5: 10

    • Compilation fails.

    Correct Answer
    A. 10 : 10
    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.

    Rate this question:

  • 15. 

    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?

    • Replace line 5 with String opt = "true"; Replace line 7 with case "true":

    • Replace line 5 with String opt = 1; Replace line 7 with case 1:

    • At line 9, remove the break statement.

    • Remove the default section.

    Correct Answer
    A. Replace line 5 with String opt = "true"; Replace line 7 with case "true":
    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".

    Rate this question:

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

    • Compilation fails at line n1 and line n2.

    • A B C

    • C

    • C B A

    Correct Answer
    A. A B C
    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".

    Rate this question:

  • 17. 

    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?

    • An exception is thrown at runtime.

    • -1

    • 5

    • 0

    Correct Answer
    A. 5
    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.

    Rate this question:

  • 18. 

    Which statement is true about Java byte code?

    • It can run on any platform only if that platform has both the Java Runtime Environment and the compiler.

    • It can run on any platform that has a Java compiler.

    • It can run on any platform that has the Java Runtime Environment.

    • It can run on any platform only if it was compiled for the platform.

    • It can run on any platform.

    Correct Answer
    A. It can run on any platform that has the Java Runtime Environment.
    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.

    Rate this question:

  • 19. 

    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?

    • Int [] array = new int[2];

    • Int [] array; array = int[2];

    • Int array = new int[2];

    • Int array[2];

    Correct Answer
    A. Int [] array = new int[2];
    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.

    Rate this question:

  • 20. 

    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?

    • 200.0 : 100.0

    • 400.0 : 200.0

    • 400.0 : 100.0

    • Compilation fails.

    Correct Answer
    A. 400.0 : 100.0
    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".

    Rate this question:

  • 21. 

    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?

    • Hello World!

    • Hello Universe!

    • An exception is thrown at runtime.

    • Compilation fails.

    Correct Answer
    A. Hello World!
    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!".

    Rate this question:

  • 22. 

    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?

    • 5 4 3 2 1 0

    • 5 4 3 2 1

    • 4 2 1

    • 5

    • Nothing is printed

    Correct Answer
    A. 5
    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".

    Rate this question:

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

    • 4 21

    • 4 5

    • 5 4

    • 3 5

    • 4 4

    • 4 4

    • 4 7

    • 4 7

    Correct Answer
    A. 4 5
    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.

    Rate this question:

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

    • Compilation fails.

    • False true

    • True true

    • True false

    Correct Answer
    A. False true
    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".

    Rate this question:

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

    • 1 3 5 7 1 3

    • 1 3 1 3

    • 1 3 1 3 0 0

    • Compilation fails.

    • 1 3 Followed by an ArrayIndexOutOfBoundsException.

    Correct Answer
    A. 1 3 5 7 1 3
    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

    Rate this question:

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

    • Compilation fails.

    • 10 20 30 40

    • 0 0 30 40

    • An exception is thrown at runtime.

    Correct Answer
    A. 0 0 30 40
    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".

    Rate this question:

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

    • Match 1

    • Match 2

    • No Match

    • A NullPointerException is thrown at runtime.

    Correct Answer
    A. Match 2
    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.

    Rate this question:

  • 28. 

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

    • A main method must be declared in every class.

    • A package must contain more than one class.

    • A subclass can inherit from a superclass.

    • Objects cannot be reused.

    • Object can share behaviors with other objects.

    • Object is the root class of all other objects.

    Correct Answer(s)
    A. A subclass can inherit from a superclass.
    A. Object can share behaviors with other objects.
    A. Object is the root class of all other objects.
    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.

    Rate this question:

  • 29. 

    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?

    • A NullPointerException is thrown at runtime.

    • Java EE

    • Java SE

    • Compilation fails at line n1.

    Correct Answer
    A. Java EE
    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.

    Rate this question:

  • 30. 

    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?

    • Int f = ps.indexOf(new Patient("Mike"));

    • Int f = ps.indexOf(Patient("Mike"));

    • Patietn p = new Patient("Mike"); int f = ps.indexOf(p);

    • Int f = ps.indexOf(p2);

    Correct Answer
    A. Int f = ps.indexOf(p2);
    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".

    Rate this question:

  • 31. 

    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?

    • 10 Hello World!

    • 10 Hello Universe!

    • 9 Hello World!

    • Compilation fails.

    Correct Answer
    A. 10 Hello World!
    Explanation
    The code fragment uses the post-increment operator (aVar++) on the variable aVar. Since aVar is initially 9, the condition (aVar++ < 10) evaluates to true. Therefore, the code inside the if statement is executed, and the value of aVar is incremented to 10. The output statement prints "10 Hello World!" as the result.

    Rate this question:

  • 32. 

    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?

    • Stuff.equals("TV") ? res = "Walter" : stuff.equals("Movie") ? res = "White": res = "No Result";

    • Res = stuff.equals("TV") ? "Walter" else stuff.equals("Movie") ? "White": "No Result";

    • Res = stuff.equals("TV") ? stuff.equals("Movie") ? "Walter" : "No Result";

    • Res = stuff.equals("TV") ? "Walter" : stuff.equals("Movie") ? "White": "No Result";

    Correct Answer
    A. Res = stuff.equals("TV") ? "Walter" : stuff.equals("Movie") ? "White": "No Result";
    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.

    Rate this question:

  • 33. 

    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?

    • 2 4

    • 0 2 4 6

    • 0 2 4

    • Compilations fails.

    Correct Answer
    A. 0 2 4
    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".

    Rate this question:

  • 34. 

    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?

    • Hello Java SE 8 Hello Java SE 8

    • Hello java.lang.StringBuilder@<<hashcode>> Hello p1.MyString@<<hashcode2>>

    • Hello Java SE 8 Hello p1.MyString@<<>hashcode>

    • Compilation fails at the Test class.

    Correct Answer
    A. Hello Java SE 8 Hello p1.MyString@<<>hashcode>
    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.

    Rate this question:

  • 35. 

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

    • Sb.deleteAll();

    • Sb.delete(0,sb.length());

    • Sb.delete(0,sb.size());

    • Sb.removeAll();

    Correct Answer
    A. Sb.delete(0,sb.length());
    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.

    Rate this question:

  • 36. 

    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?

    • 200: 300 200: 300

    • 300: 0 0: 300

    • 300: 300 200: 300

    • 300: 100 200: 300

    Correct Answer
    A. 300: 100 200: 300
    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.

    Rate this question:

  • 37. 

    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?

    • Welcome Visit Count: 1 Welcome Visit Count: 2

    • Welcome Visit Count: 1 Welcome Visit Count: 1

    • Compilation fails at line n1 and line n1 and line n2.

    • Compilation fails at line n3 and line n3 and line n4.

    Correct Answer
    A. Compilation fails at line n1 and line n1 and line n2.
    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.

    Rate this question:

  • 38. 

    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?

    • US: 2 UK: 2

    • US: 3 UK: 3

    • US: 2 UK: 4

    • An ArrayIndexOutOfBoundsException is thrown at runtime.

    Correct Answer
    A. US: 2 UK: 2
    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".

    Rate this question:

  • 39. 

    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?

    • String str2 = "Duke";

    • String str2 = sb1.toString();

    • String str2 = str1;

    • String str2 = new String(str1);

    Correct Answer
    A. String str2 = str1;
    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.

    Rate this question:

  • 40. 

    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?

    • Compilation fails at line n2.

    • Read E-Book

    • Read Book

    • Compilation fails at line n3.

    • Compilation fails at line n1.

    Correct Answer
    A. Compilation fails at line n3.
    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.

    Rate this question:

  • 41. 

    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?

    • A B C C

    • A B C D

    • A C D

    • A B D

    • A B D C

    • A B D D

    Correct Answer
    A. A B C C
    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".

    Rate this question:

  • 42. 

    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?

    • Date1 = 2014-06-20 date2 = 2014-06-20 date3 = 2014-06-20

    • Date1 = 06/20/2014 date2 = 2014-06-20 date3 = Jun 20, 2014

    • Compilation fails.

    • A DateParseException is thrown at runtime.

    Correct Answer
    A. Date1 = 2014-06-20 date2 = 2014-06-20 date3 = 2014-06-20
    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".

    Rate this question:

  • 43. 

    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?

    • Import sales.*;

    • Import java.sales.products.*;

    • Import sales; import sales.products;

    • Import sales.*; import products.*;

    • Import sales.*; import sales.products.*;

    Correct Answer
    A. Import sales.*; import sales.products.*;
    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.

    Rate this question:

  • 44. 

    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?

    • An UnsupportedOperationException is thrown at runtime.

    • Hi removed

    • Compilation fails.

    • The program compiles, but it prints nothing.

    Correct Answer
    A. Compilation fails.
    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()

    Rate this question:

  • 45. 

    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?

    • StringBuilder sb = new StringBuilder(x); sb.append(creditCard, 15, 19); return sb.toString();

    • StringBuilder sb = new StringBuilder(creditCard); sb.subString(creditCard, 15, 19); return x + sb;

    • return x + creditCard.substring(15, 19);

    • StringBuilder sb = new StringBuilder(creditCard); StringBuilder s = sb.insert(0, x); return s.toString();

    Correct Answer(s)
    A. StringBuilder sb = new StringBuilder(x); sb.append(creditCard, 15, 19); return sb.toString();
    A. return x + creditCard.substring(15, 19);
    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.

    Rate this question:

  • 46. 

    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?

    • Invalid Names omas null null

    • Invalid Names

    • Invalid Names omas

    • Omas

    Correct Answer
    A. Invalid Names omas null null
    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.

    Rate this question:

  • 47. 

    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?

    • Compilation fails.

    • -1

    • 4

    • 3

    Correct Answer
    A. 4
    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.

    Rate this question:

  • 48. 

    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?

    • 123: false 123: false

    • 123: true 123: true

    • 123: false 123: true

    • Compilations fails.

    Correct Answer
    A. 123: true 123: true
    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.

    Rate this question:

  • 49. 

    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?

    • Result A 1 Result B 3

    • Result A 01 Result B 3

    • Result A 01 Result B 12

    • Result A 1 Result B 12

    Correct Answer
    A. Result A 01 Result B 12
    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".

    Rate this question:

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
Back to Top Back to top
Advertisement
×

Wait!
Here's an interesting quiz for you.

We have other quizzes matching your interest.