Java Foundations Certification 1Z0-811 Sample Questions

article:published_time: 2019-04-11T00:01:20-05:30
article:modified_time: 2023-10-11T00:01:20-05:30


The following sample questions are extracted from Enthuware OCAJF Java Foundations Certification Exam Simulator, which contains more than 250 practice questions with detailed explanations.
CLICK HERE TO PURCHASE

Question 1.     Topic: Java Methods     Toughness: Very Tough

Consider the following method...

public int setVar(int a, int b, float c) {
   //valid code not shown
}

Which of the following methods correctly overload the above method ?

Select 2 options:

  1. public int setVar(int a, float b, int c)
    {
      return setVar(a, c, b);
    }
  2. public int setVar(int a, float b, int c)
    {
      return this(a, c, b);
    }
    this( ... ) can only be called in a constructor and that too as a first statement.
  3. public int setVar(int x, int y, float z)
    {
      return x+y;
    }
    It will not compile because it is same as the original method. The name of parameters do not matter while checking method signatures.
  4. public float setVar(int a, int b, float c)
    {
      return c*a;
    }
    It will not compile as it is same as the original method. The return type does not matter.
  5. public float setVar(int a)
    {
      return a;
    }
   Click to see discussion about this Question!
Correct options are: 1, 5
A method is said to be overloaded when there is another method available in the same class with the same name but different the parameter list ( either the number or their order) are different.

Note that method name and parameter type list (parameter names do not matter) together make up a method's signature. Thus, overloaded methods have same method name but different signatures.

Option 2 is not valid because of the line: return this(a, c, b); This is is the syntax of calling a constructor and not a method. It should have been: return this.setVar(a, c, b);

Question 2.     Topic: Working with the String Class     Toughness: Tough

How many string objects are created in the following code fragment?


Sting a, b, c;
a = new String("hello");
b = a;
c = a + b;

Select 1 best option:

  1. 1
  2. 2
  3. 3
    The statement a = new String("hello"); creates not 1 but 2 String objects. The first one containing "hello" is created in the String pool due to the presence of a constant string hello in the code. The second string object is created in the heap area containing the same data as the first one because of the usage of the new keyword.

    The statement b = a; does not create any new String.

    The statement c= a+b; creates a new string in the heap containing hellohello.

    So, a total of three strings are created.
  4. 4
  5. 5
   Click to see discussion about this Question!
Correct option is: 3
Note: String interning is a complex topic with many nuances. It is not mentioned explicitly in exam objectives but a few candidates have reported seeing such questions in the exam. You should remember the following rules about this topic:

The JVM maintains a pool of all the String objects. Whenever you use a String literal (i.e. a string within double quotes), the JVM checks whether that string already exists in the pool or not. If the string exists, then it uses the same String object instead of creating a new one. This is called interning of Strings.

When you create a string using the new operator, interned strings are not used and a new String object is created.

So, for example,
String s1 = "hello"; //new interned string object containing hello is created
String s2 = "hello";  //no new object is created because the same String already exists in the string pool
String s3 = new String("hello"); //new string object is created in the heap area.

In the above code, only two string objects are created (not three).

Question 3.     Topic: Working with the String Class     Toughness: Easy

What will the following statement print?

int marks = 90;
String exam = "OCJA";
System.out.printf("I scored %d marks in the %s exam!",  exam, marks );

Select 1 best option:

  1. I scored 90 marks in the Java Foundations exam!
  2. I scored OCAJF marks in the 90 exam!
  3. Exception will be thrown at run time.
    The first format specifier is %d, so, the first argument should be an integer value. exam is a String and that will cause an exception to be thrown.
  4. Compilation error
   Click to see discussion about this Question!
Correct option is: 3
Tips for String formatting

Question 4.     Topic: Debugging and Exception Handling     Toughness: Tough

Which digits and in what order will be printed when the following program is run?

public class TestClass
{
   public static void main(String args[])
   {
      int k = 0;
      try{
         int i = 5/k;
      }
      catch (ArithmeticException e){
         System.out.println("1");
      }
      catch (RuntimeException e){
         System.out.println("2");
         return ;
      }
      catch (Exception e){
         System.out.println("3");
      }
      finally{
         System.out.println("4");
      }
      System.out.println("5");
   }
}

Select 1 best option:

  1. The program will print 5.
  2. The program will print 1 and 4, in that order.
  3. The program will print 1, 2 and 4, in that order.
  4. The program will print 1, 4 and 5, in that order.
    See explanation.
  5. The program will print 1,2, 4 and 5, in that order.
   Click to see discussion about this Question!
Correct option is: 4
Division by 0 throws an ArithmeticException. This is caught by the first catch clause since it is the first block that can handle arithmetic exceptions. This prints 1. Now, as the exception is already handled, control goes to finally which prints 4 and then the try/catch/finally ends and 5 is printed.
Remember : finally is always executed even if try or catch return; The only exception to this rule is System.exit().

Question 5.     Topic: Java Methods     Toughness: Easy

Given:

class Node{
    static final int TYPE = 100;
    public static void print(){
        System.out.println(TYPE); //1    
    }
}

public class Test{
    public static void main(String[] args) {
       //INSERT CODE HERE //2
    }
}

What may be done to the above code to make it print 100?

Select 1 best option:

  1. Change the statement at //1 to System.out.println(None.TYPE);
    and
    insert Node.print(); at //2
    It is not required to use Node.TYPE at //1 because the TYPE variable is accessible directly within the Node class. But it is not an error to do so.
  2. insert new Node().print(); at //2
    Since print() is a static method of Node, an instance of Node is not required to access this method. However, it is not an error to access a static method of a class through an instance. It is definitely a bad coding practice though.
    Ideally, Node.print(); should be used.
  3. insert new Node.print(); at //2
    Observe the missing brackets after Node. "new Node" is syntactically incorrect and will not compile.
  4. insert Node().print(); at //2
    Node() is the syntax for calling a method named Node. But there is no Node() method in class Test.
  5. insert print(); at //2.
    print method is in the Node class. It is not directly accessible in the Test class. Therefore, Node.print(); is required.
   Click to see discussion about this Question!
Correct option is: 1

Question 6.     Topic: Working with Java Data Types     Toughness: Tough

Given:

String str = "hello\r\n" + "world";
System.out.println(str.length);    

Select 1 best option:

  1. 12
  2. 13
  3. 14
  4. Compilation error
  5. Exception at run time
   Click to see discussion about this Question!
Correct option is: 4
1. \r and \n are valid escape sequences for carriage return and new line characters respectively.

2. String class does not have a field named length. It has a method named length. So, str.length will not compile. But str.length() will return 12.

Question 7.     Topic: Working with Java Data Types     Toughness: Easy

Which of the following can be valid declarations of an integer variable?

Select 2 options:

  1. global int x = 10;
    global is an invalid modifier. There is nothing like global in java. The closest you can get is static.
  2. final int x = 10;
  3. public Int x = 10;
    Int with a capital I is invalid.
  4. Int x = 10;
    Int with a capital I is invalid.
  5. static int x = 10;
   Click to see discussion about this Question!
Correct options are: 2, 5

Question 8.     Topic: Working with the Random and Math Classes     Toughness: Very Tough

What can you do to make the following code print a number between 0 and 10?
(Assume appropriate import statements.)

int x = 10;
//insert code here
System.out.println(d);

Select 3 options:

  1. Random r = new Random(x);
    int d = r.nextInt();
  2. Random r = new Random();
    int d = r.nextInt(x);
  3. Random r = new Random(x);
    int d = r.nextInt(x);
  4. Random r = new Random(x);
    int d = (int) r.next()*10;
  5. Random r = new Random();
    r.setSeed(x);
    int d = (int) r.next()*10;
  6. Random r = new Random(x);
    r.setSeed(x);
    int d = r.nextInt(x);
   Click to see discussion about this Question!
Correct options are: 2, 3, 6
java.util.Random class has two constructors:

Random(): Creates a new random number generator.
Random(long seed): Creates a new random number generator using a single long seed.

The Random(long seed) constructor is equivatent to doing Random r = new Random(); r.setSeed(long seed);

Random class has the following two methods that return an int:

int nextInt():
Returns the next pseudorandom, uniformly distributed int value from this random number generator's sequence.  All 2^32 possible int values are produced with (approximately) equal probability.

int nextInt(int bound)
Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.


Please go through JavaDoc API description of java.util.Random class.

Question 9.     Topic: Basic Java Elements     Toughness: Tough

Which of the following are reserved words in Java?

Select 2 options:

  1. goto
  2. package
    Do not get confused between reserved words and keywords. As per section 3.9 of JLS there is no distinction between the two. It says, "50 character sequences, formed from ASCII letters, are reserved for use as keywords and cannot be used as identifiers." It lists const and goto among the list of those 50 keywords. It also says, "The keywords const and goto are reserved, even though they are not currently used."    
  3. export
  4. array
  5. hash
   Click to see discussion about this Question!
Correct options are: 1, 2
Keywords, Reserved Words, and Literals

Question 10.     Topic: Java Basics     Toughness: Easy

You are writing a class named AccountManager. This class is the starting point of your application and is to be executing from the command line. What should be the name of the file containing this class's source code?

Select 1 best option:

  1. accountmanager.java
  2. AccountManager.java
  3. main.java
  4. Main.java
  5. The name of the file doesn't matter because after compilation, the class file will be named AccountManager.class anyway.
    Name of the source file is important. If the source code of the public class is not defined in file by same name, the source file will not compile. Therefore, the name of the file must be AccountManager.java.
   Click to see discussion about this Question!
Correct option is: 2

Question 11.     Topic: Arrays and ArrayLists     Toughness: Very Tough

Given:

public class Account {
    int id;
    public Account(int id){
        this.id = id;
    }
    
    public static void main(String[] args) {
        List<Account> list = new ArrayList<Account>();
        list.add(new Account(111));
        list.add(new Account(222));

        //insert code here
    }
}


Which of the following options, when inserted in the above code, will print 111 222 ?

Select 1 best option:

  1. for(int id : list.id) System.out.print(id+" ");
    This will not compile because list does not have a field named id.

    Note that a foreach loop requires an object of a class that implements java.lang.Iterable interface.
    It is possible to iterate over the elements of a List and ArrayList because they do implement Iterable.
  2. for(Account id : list) System.out.print(id+" ");
    The loop variable id refers to an object of type Account. So, this will print the String generated by the toString method inherited from the Object class by the Account class. Something like:
    Account@5e2de80c Account@1d44bcfa

    It should be:
    for(Account id : list) System.out.print(id.id+" ");

    Of course, the loop variable is inappropriately named, which causes the confusion. It should ideally be named as acct.
  3. Iterator<Account> it = list.iterator();
    while(it.hasNext()) System.out.println(it.next()+" ");
    This is a valid loop but it.next() will return an Account object, whereas, you want the id field of an Account object to be printed.  
    This will print the String generated by the toString method inherited from the Object class by the Account class. Something like:
    Account@5e2de80c Account@1d44bcfa
  4. for(int i = 0; i<list.size(); i++) System.out.print(list.id+" ");
    The list variable points to an ArrayList object and not to an Account object. So, list.id is invalid and will not compile.
    It should be:
    for(int i = 0; i<list.size(); i++) System.out.print(list.get(i).id+" ");
  5. None of the above.
   Click to see discussion about this Question!
Correct option is: 5

Question 12.     Topic: Using Looping Statements     Toughness: Easy

What is the effect of compiling and running this class ?

public class TestClass
{
   public static void main (String args [])
   {
      int sum = 0;
      for (int i = 0, j = 10; sum > 20; ++i, --j)      // 1
      {
         sum = sum+ i + j;
      }
      System.out.println("Sum = " + sum);
   }
}


Select 1 best option:

  1. Compile time error at line 1.
  2. It will print Sum = 0
    Note that the loop condition is sum >20 and not sum <20. Thus, the loop will not execute even once.
  3. It will print Sum = 20
  4. Runtime error.
  5. None of the above.
   Click to see discussion about this Question!
Correct option is: 2

Question 13.     Topic: Using Decision Statements     Toughness: Very Tough

What will the following code print?
        int x = 1;
        int y = 2;
        int z = x++;
        int a = --y;
        int b = z--;
        b += ++z;

        int answ = x>a?y>b?y:b:x>z?x:z;
        System.out.println(answ);

Select 1 best option:

  1. 0
  2. 1
  3. 2
  4. -1
  5. -2
  6. 3
   Click to see discussion about this Question!
Correct option is: 3
This is a simple but frustratingly time consuming question. Expect such questions in the exam.
For such questions, it is best to keep track of each variable on the notepad after executing each line of code.

You also need to be clear about how prefix and postfix increment/decrement operators works. The basic principle is that in case of the prefix operator, the variable is updated and then its value is used in the expression, while in case of the postfix operator, the current value of the variable is used in the expression and then the variable is update.

For example,

int z = x++;
Here, the current value of x is 1 (as given in the code). So, 1 will be the resulting value of the expression x++. Next, x is incremented to 2. Therefore, after this statement, z will be 1 but x will be 2.

int a = --y;
Here, the current value of y is 2 (as given in the code). So, y will be decremented to 1 and then its new value i.e. 1 will be the result of the expression --y. Therefore, after this statement, a will be 1 and y will also be 1.

Similarly, after the execution of int b = z--;, b will be 1 but z will be 0.

Expand b += ++z; to b = b + ++z; Thus, b = 1 + (++z). Since z is 0, this will reduce to b = 1 + 1 (applying the prefix rule explained above). Thus, b will be 2 and z will 1.


The final values of the variables are as follows -
x=2 y=1 z=1 a=1 b=2

The expression x>a?y>b?y:b:x>z?x:z; should be grouped as -
x > a  ? (y>b ? y : b)  :  (x>z ? x : z);

It will, therefore, assign 2 to answ.

Question 14.     Topic: What is Java     Toughness: Tough

Which of the following are features of Java?

Select 2 options:

  1. It is strongly typed
    Java is a strongly typed (or statically typed) langague because a variable cannot be declared without specifying its type. Further, once a variable is declared, its type cannot change.

    Some languages such as JavaScript are loosely typed (or dynamically typed). They let a variable to refer to any type of object at runtime. The type of the variable is determined at runtime based on the type of the value it is holding.
  2. It offers direct memory management.
    Direct memory management means a programmer can access the program memory directly (such as through pointers). Java does not allow that. Memory is managed by the JVM itself.
  3. It allows multithreaded programming.
  4. It is a distributed lanaguage.
    This option doesnt make any sense and is, therefore, incorrect.
    It is possible to make distributed applications in Java though.
   Click to see discussion about this Question!
Correct options are: 1, 3

Question 15.     Topic: Debugging and Exception Handling     Toughness: Easy

Given:

public class Test
{
    public int div(int a, int b) throws Exception {
        try{
            return a/b;
        }catch(ArithmeticException ae){
            System.out.println("exception in div");
            return 0;
        }
    }
    
   public static void main(String args[])
   {
      Test test = new Test();
      try{
          System.out.println(test.div(5, 0));
      }catch(Exception e){
          System.out.println("exception in main");
      }
   }
}

What is the output?

Select 1 best option:

  1. exception in div
    exception in main
  2. exception in div
  3. exception in main
  4. exception in div
    0
  5. Compilation failure
   Click to see discussion about this Question!
Correct option is: 4
Division by zero causes an ArithmeticException to be thrown in the div method. This exception is caught by the catch block in div method. The catch block prints "exception in div" and return 0. The method ends here. Observe that the exception is not thrown to the caller of the div method because the exception is caught within the method itself. As far as the caller is concerned, the call to div returns normally without any exception.

Therefore, the print statement in main prints 0. The control does not go to the catch block in main and the program ends.

Question 16.     Topic: Java Methods     Toughness: Very Tough

Given:

public class Test
{
    static int a;
    int b;

    public void incr(){
       int c = a++;
       b++;
       c++;
       System.out.println(a+" "+b+" "+c);
    }
   public static void main(String args[])
   {
      Test test = new Test();
      test.incr();
      a++;
      test = new Test();
      test.incr();
   }
}


What will be the output?

Select 1 best option:

  1. Compilation failure.
    There is no problem with the code.
  2. 1 1 1
    2 1 2
  3. 1 1 1
    3 1 3
  4. 1 2 1
    2 3 3
  5. 1 2 1
    3 3 3
   Click to see discussion about this Question!
Correct option is: 3
You need to remember the following points to answer this question:

1. static fields belong to the class and not to the instance of a class. Therefore, there is only 1 copy of the field 'a' irrespective of the number of objects of class Test that are created.

2. Every instance of a class gets its own copy of the instance fields. Therefore, every Test instance gets its own copy of the field 'b'.

3. The postfix increment operation increments the value of the variable after the expression is evaluated. Therefore, in the statement int c = a++; first, the existing value of a is assigned to c and then a is incremented.

Based on the above, it is easy to see the following:

1. in the first call to incr(), c is set to 0, then a is incremented to 1, then b is incremented to 1, and then c is incremented to 1.
Therefore, it prints 1 1 1.

2. Next, a is incremented to 2 in the main method.

3. Next, the second call to incr() is invoked on a different instance of Test. Therefore, in this new instance, a is 2 (because a is static) and b is 0.
Now, c gets 2, then a is incremented to 3. then b is incremented to 1, then c is incremented to 3.

Therefore, 3 1 3 is printed.