Java SE 8 Programmer I (OCAJP 8) study materials
Java SE 8 Programmer I (OCAJP 8) study resources

Java SE 8 Programmer I (OCAJP 8) practice questions

One question at a time. Build your Java SE 8 Programmer I (OCAJP 8) understanding.

First 50 of 200 questions. Each one lists the choices, the correct answer, and an explanation. The checker at the top of this page saves progress in this browser when it is available.

Continue in the practice tool above to load more questions, 50 at a time.

Question 1Java Basics

Which declaration correctly defines the entry point the java launcher looks for in a class named App?

  1. public void main(String[] args)
  2. public static int main(String[] args)
  3. public static void main(String[] args) Correct answer.
  4. static void main(String args)

Explanation

The launcher requires a method that is public, static, returns void, is named main, and takes a single String[] parameter. Any legal array syntax such as String... args or String args[] also matches, but the modifiers, return type and parameter type must be exactly as specified.

Question 2Java Basics

Given `int x = 5;` which statement about the identifier `x` is true?

  1. x is a literal value stored in the class file
  2. x must start with an uppercase letter
  3. x is a keyword reserved by the compiler
  4. x is an identifier that refers to a local variable Correct answer.

Explanation

Identifiers are names given to variables, methods, classes and other program elements; here x names a local variable of type int. Java keywords are fixed reserved words such as int and class, and literals are the values themselves, so neither term describes x.

Question 3Java Basics

Which line declares a variable of type `double` initialized with a value that requires no cast?

  1. double d = "3.5";
  2. double d = 3.5f;
  3. double d = 3.5; Correct answer.
  4. double d = true;

Explanation

A floating-point literal without a suffix is a double, so it assigns directly to a double variable. A float literal widens to double, but the string and boolean lines are type errors since neither type converts to double.

Question 4Java Basics

What is printed by the following code? ```java public class T { public static void main(String[] a) { int i = 7, j = 2; System.out.println(i / j + i % j); } } ```

  1. 3
  2. 5
  3. 4.5
  4. 4 Correct answer.

Explanation

Integer division truncates, so 7 / 2 is 3, and the remainder 7 % 2 is 1. The two int results are added to give 4 before printing, and no floating-point promotion occurs because both operands are int.

Question 5Java Basics

Which statement about a variable declared inside a method body is correct?

  1. It is visible to other methods of the same class
  2. It is automatically initialized to the default value for its type
  3. It must be definitely assigned before it is read Correct answer.
  4. It is implicitly static

Explanation

Local variables are not given default values; the compiler enforces definite assignment and rejects any read of a local that might not have been initialized. Only fields (instance and static) receive type defaults such as 0 or null.

Question 6Java Basics

Which is a valid declaration of a constant-style field that cannot be reassigned after construction?

  1. const int MAX = 10;
  2. final int MAX = 10; Correct answer.
  3. static int MAX = 10;
  4. abstract int MAX = 10;

Explanation

The final modifier means a variable may be assigned only once, so a final field cannot be reassigned after it is set. Java has no const keyword, and abstract cannot be applied to a field.

Question 7Java Basics

Given `String s = args[0];` inside main, which exception is thrown when the program is run with no command-line arguments?

  1. NullPointerException
  2. ArrayIndexOutOfBoundsException Correct answer.
  3. ClassCastException
  4. NumberFormatException

Explanation

When no arguments are supplied, the array passed to main has length 0, so index 0 is outside its bounds and an ArrayIndexOutOfBoundsException is thrown. The array reference itself is never null, so a NullPointerException does not apply here.

Question 8Java Basics

Which identifier is legal in Java source code?

  1. 2ndValue
  2. _value Correct answer.
  3. my-value
  4. class

Explanation

An identifier may start with a letter, a currency symbol, or an underscore, and may continue with those plus digits. Underscore alone became a reserved literal in Java 9, but a leading underscore followed by letters is still a legal name in Java 8.

Question 9Java Basics

What is the result of compiling and running this code? ```java public class C { int count; public static void main(String[] a) { C c = new C(); System.out.println(c.count); } } ```

  1. It prints 0 Correct answer.
  2. It throws NullPointerException
  3. It prints null
  4. It fails to compile because count is not initialized

Explanation

An instance field of a numeric primitive type receives the default value 0 when the object is created, so reading count through a valid reference prints 0. Definite-assignment rules apply only to local variables, not to fields.

Question 10Java Basics

Which statement correctly describes a class declared with the `public` modifier in a file named Report.java?

  1. The class must be named Report and may be stored in any file name
  2. The class must be named Report and the file must be named Report.java Correct answer.
  3. The class may have any name as long as the file is Report.java
  4. The class must be declared abstract if the file is public

Explanation

A top-level public class must be stored in a file whose name matches the class name plus the .java extension, so Report must live in Report.java. A file may hold other non-public classes with different names.

Question 11Java Basics

Which statement about the `static` modifier on a method is correct?

  1. A static method must be declared final
  2. A static method cannot be overloaded
  3. A static method is invoked on the class rather than on an instance Correct answer.
  4. A static method can directly use instance fields of its class

Explanation

A static method belongs to the class itself and is called through the class name, without any object. Because no instance is bound to the call, it cannot access instance fields or methods directly.

Question 12Java Basics

Which line causes a compile-time error? ```java byte b = 10; short s = b; int i = s; char c = i; ```

  1. short s = b;
  2. char c = i; Correct answer.
  3. byte b = 10;
  4. int i = s;

Explanation

Widening conversions from byte to short and short to int happen automatically. Converting an int to char is a narrowing conversion even though both are 16-bit or wider, so an explicit cast is required.

Question 13Java Basics

What does this code print? ```java int a = 5; int b = a++ + ++a; System.out.println(a + " " + b); ```

  1. 6 12
  2. 7 13
  3. 7 11
  4. 7 12 Correct answer.

Explanation

The postfix a++ yields 5 and then increments a to 6; the prefix ++a first increments a to 7 and yields 7. The sum is 12 and the final value of a is 7.

Question 14Java Basics

Which declaration creates a single-dimensional array of five int elements initialized to zero?

  1. int a[5] = new int[];
  2. int[] a = new int[5]; Correct answer.
  3. int a = new int[5];
  4. int[] a = new int(5);

Explanation

The form new int[5] allocates an array of length 5, and every element of a primitive int array is initialized to 0. The brackets belong to the type or the variable name, and the length is given in brackets, not parentheses.

Question 15Java Basics

Given `int[] nums = {3, 6, 9};` what is printed by `System.out.println(nums.length + nums[1]);`?

  1. 9 Correct answer.
  2. An exception is thrown
  3. 6
  4. 12

Explanation

For an array, length is a final field holding the number of elements, here 3, and index 1 holds 6. Adding them gives 9; note that length is a field, whereas String uses the length() method.

Question 16Java Basics

Which statement about the default package and import declarations is correct?

  1. The java.lang package must always be imported explicitly
  2. A class in the default package can be imported by name
  3. Importing a package imports all of its subpackages
  4. The import statement must appear before any class declaration Correct answer.

Explanation

Import declarations, like package declarations, must precede all type declarations in a compilation unit. Types in the unnamed package cannot be imported, and importing a package never includes its subpackages.

Question 17Java Basics

Which pair of statements about `String` objects is correct?

  1. Strings are immutable, and == compares their contents
  2. Strings are mutable, and == compares their contents
  3. Strings are mutable, and equals compares their references
  4. Strings are immutable, and equals compares their contents Correct answer.

Explanation

A String's character content never changes after creation, so operations like concat return new objects. The == operator compares references, while equals on String compares the actual character sequences.

Question 18Java Basics

What is printed by the following code? ```java String s = "Java"; s.concat(" SE"); System.out.println(s); ```

  1. null
  2. Java Correct answer.
  3. SE
  4. Java SE

Explanation

String objects are immutable, so concat returns a new String and leaves the original untouched. Because the returned value is discarded, s still refers to "Java" when printed.

Question 19Java Basics

Which statement correctly compares two String references `s1` and `s2` for identical character content?

  1. s1.equals(s2) Correct answer.
  2. s1.hashCode() == s2.hashCode()
  3. s1 == s2
  4. s1.compareTo(s2)

Explanation

String overrides equals to compare the characters of the two strings, which is the reliable content check. The == operator tests reference identity, and compareTo returns an int ordering rather than a boolean.

Question 20Java Basics

What is the result of running this code? ```java public class Loop { public static void main(String[] a) { int sum = 0; for (int i = 0; i < 5; i++) { if (i == 3) continue; sum += i; } System.out.println(sum); } } ```

  1. 6
  2. 7 Correct answer.
  3. 10
  4. 3

Explanation

The loop adds 0, 1, 2 and 4 while skipping 3 because continue jumps to the update expression. The total is 7, and the loop still terminates normally after i reaches 5.

Question 21Java Basics

Which statement about `switch` on an int expression is correct for Java 8?

  1. Case labels may be any int expression evaluated at run time
  2. Fall-through between cases is prevented automatically by break statements inserted by the compiler
  3. A switch on int requires a default label
  4. Case labels must be compile-time constant expressions compatible with the switch type Correct answer.

Explanation

Each case label must be a constant expression assignable to the switch type, such as a literal or a final constant variable. A default label is optional, and the compiler never inserts break statements, so fall-through happens unless the programmer breaks.

Question 22Java Basics

Given `Integer x = null;` what happens when `int y = x;` executes?

  1. A compile-time error occurs because Integer cannot be assigned to int
  2. A NullPointerException is thrown Correct answer.
  3. y is set to -1
  4. y is set to 0

Explanation

Assigning an Integer to an int triggers automatic unboxing through intValue(). When the wrapper reference is null, that method call fails at run time with a NullPointerException.

Question 23Java Basics

Which statement about passing an array reference to a method is correct?

  1. Arrays cannot be passed to methods without wrapping them in an object
  2. The method receives the array by reference, so reassigning the parameter changes the caller's variable
  3. The method receives a copy of the reference, so element changes affect the caller's array Correct answer.
  4. The method receives a copy of the array, so element changes do not affect the caller

Explanation

Java is always pass-by-value; for an array the value passed is a copy of the reference, which points to the same array object. Modifying elements through that reference is visible to the caller, but reassigning the parameter only changes the local copy.

Question 24Working With Java Data Types

Which declaration correctly defines a constant of type int that can be used anywhere in the program and cannot be reassigned?

  1. final static int MAX = 100;
  2. public static final int MAX = 100; Correct answer.
  3. public int final MAX = 100;
  4. static final int MAX = 100;

Explanation

A true program-wide constant needs public visibility, static so it belongs to the class, and final so it cannot be reassigned. Options 0 and 1 are legal declarations but package-private, so they are not accessible anywhere in the program. Option 3 is a syntax error because the modifier final cannot follow the type.

Question 25Working With Java Data Types

Given `byte b = 10;` and `short s = 20;`, which expression compiles without a cast when assigned to a variable of type int?

  1. int r = b + 300;
  2. int r = b + s; Correct answer.
  3. int r = b * s * 100000;
  4. int r = (int) b + s;

Explanation

When a byte and a short are combined with a binary operator, both are promoted to int, so the result is an int and assigns to int without a cast. Mixing in a literal that does not fit int, or a computation whose result overflows int, breaks compilation or changes the type. The explicit cast in option 3 is legal but unnecessary, making option 0 the clean no-cast case.

Question 26Working With Java Data Types

What is printed by the following code? ```java int x = 5; int y = x++ + ++x; System.out.println(x + " " + y); ```

  1. 6 11
  2. 6 12
  3. 7 11
  4. 7 12 Correct answer.

Explanation

The postfix x++ yields 5 and then increments x to 6; the prefix ++x increments x to 7 and yields 7. So y becomes 5 + 7 = 12 and x ends at 7, printing "7 12".

Question 27Working With Java Data Types

Which statement about the default values of instance fields is correct?

  1. A boolean instance field defaults to false. Correct answer.
  2. An object reference instance field defaults to a new instance of its type.
  3. An int instance field defaults to 1.
  4. A char instance field defaults to the space character.

Explanation

Instance fields that are not explicitly initialized receive type defaults: false for boolean, '\u0000' for char, 0 for numeric types, and null for references. Local variables receive no default and must be assigned before use.

Question 28Working With Java Data Types

Which line correctly declares and initializes a two-dimensional array of int with 3 rows and 4 columns?

  1. int[][] a = new int[3,4];
  2. int a[][] = new int[4][3]{};
  3. int[][] a = new int[3][4]; Correct answer.
  4. int[][] a = new int[][4];

Explanation

The standard syntax allocates the outer dimension first and the inner dimension second, so new int[3][4] creates 3 rows of 4 columns. Commas inside the brackets and empty leading dimensions are not legal in an array creation expression.

Question 29Working With Java Data Types

What is the result of compiling and running this code? ```java String s = "Java"; s.concat(" SE"); System.out.println(s); ```

  1. Java SE
  2. A compile-time error
  3. Java Correct answer.
  4. SE

Explanation

String is immutable, and concat returns a new String rather than modifying the receiver. Since the returned value is discarded, s still refers to "Java" and that is printed.

Question 30Working With Java Data Types

Which declaration creates a StringBuilder with initial content "Hi"?

  1. StringBuilder sb = StringBuilder.valueOf("Hi");
  2. StringBuilder sb = new StringBuilder('H','i');
  3. StringBuilder sb = "Hi";
  4. StringBuilder sb = new StringBuilder("Hi"); Correct answer.

Explanation

StringBuilder has a constructor that accepts a String and copies its characters into the buffer. There is no constructor taking two char arguments, and StringBuilder cannot be assigned directly from a String literal.

Question 31Working With Java Data Types

What is printed by the following code? ```java int i = 10; long l = 3L; System.out.println(i / l); ```

  1. A compile-time error
  2. 3 Correct answer.
  3. 3.3333333333333335
  4. 3.0

Explanation

When an int and a long are combined, the int is promoted to long and the division is integer division, producing the long value 3. Printing a long shows no decimal point, so the output is 3.

Question 32Working With Java Data Types

Which assignment requires an explicit cast to compile?

  1. int i = 5L; Correct answer.
  2. double d = 5;
  3. long l = 5;
  4. float f = 5;

Explanation

A long literal cannot be narrowed to int without a cast because the value might not fit, even though 5 does. Widening conversions such as int to double, int to long, and int to float happen automatically.

Question 33Working With Java Data Types

What is the output of this code? ```java char c = 'A'; c += 2; System.out.println(c); ```

  1. 67
  2. A compile-time error
  3. A2
  4. C Correct answer.

Explanation

The compound assignment c += 2 implicitly casts the int result back to char, so the character advances from 'A' to 'C'. Compound assignment operators include an implicit narrowing cast that a plain c = c + 2 would not.

Question 34Working With Java Data Types

Which statement about local variables and instance variables is correct?

  1. Instance variables declared final receive a default value and need no explicit assignment.
  2. Instance variables must be initialized before the class is compiled.
  3. Local variables are automatically initialized to type defaults.
  4. Local variables must be definitely assigned before they are read. Correct answer.

Explanation

The compiler enforces definite assignment for local variables, so reading one before assignment is a compile error. Instance fields, including final fields, receive type defaults initially, but blank final instance fields must also be definitely assigned before construction completes normally.

Question 35Working With Java Data Types

Given `String s = null;`, which expression throws a NullPointerException at runtime?

  1. System.out.println(s);
  2. boolean b = s.equals("x"); Correct answer.
  3. boolean b = "x".equals(s);
  4. boolean b = (s == null);

Explanation

Calling an instance method on a null reference dereferences it, which throws NullPointerException. Comparing with == against null, calling equals on a non-null literal, and printing null are all safe.

Question 36Working With Java Data Types

What is printed by the following code? ```java int[] a = {1, 2, 3}; int[] b = a; b[1] = 20; System.out.println(a[1]); ```

  1. 2
  2. 0
  3. 20 Correct answer.
  4. A compile-time error

Explanation

Array variables hold references, so b = a makes both variables point to the same array object. Modifying b[1] therefore changes the single shared array, and reading a[1] shows 20.

Question 37Working With Java Data Types

Which declaration correctly creates an array of 5 String elements where every element is null?

  1. String[] s = new String[];
  2. String[] s = new String(5);
  3. String[5] s = new String[];
  4. String[] s = new String[5]; Correct answer.

Explanation

Creating an array with new String[5] allocates 5 slots, and reference elements are initialized to null. The size belongs inside the brackets of the creation expression, not as a constructor argument or in the declaration's brackets.

Question 38Working With Java Data Types

What is the result of `System.out.println(0.1 + 0.2 == 0.3);`?

  1. A runtime exception
  2. false Correct answer.
  3. true
  4. A compile-time error

Explanation

Binary floating-point cannot represent 0.1, 0.2, or 0.3 exactly, so their sum differs slightly from the literal 0.3. The comparison therefore yields false; exact decimal arithmetic should use BigDecimal.

Question 39Working With Java Data Types

Which line compiles without error?

  1. byte b = 200;
  2. float f = 1.0;
  3. double d = 1.0f; Correct answer.
  4. int i = 1.0;

Explanation

A float literal widens to double automatically, so assigning 1.0f to a double is fine. A bare decimal literal is a double and cannot narrow to float or int without a cast, and 200 is outside the byte range.

Question 40Working With Java Data Types

What is printed? ```java String s = "5"; int i = 2; System.out.println(s + i + 1); ```

  1. 521
  2. 8
  3. A compile-time error
  4. 53 Correct answer.

Explanation

Evaluation is left to right: s + i concatenates to "52", then + 1 appends to give "53". Once a String operand appears, the remaining + operators perform concatenation rather than addition.

Question 41Working With Java Data Types

Which statement about wrapper classes and autoboxing is correct?

  1. Autoboxing converts a String to an Integer automatically.
  2. Integer i = 5; performs autoboxing of the int literal. Correct answer.
  3. int i = new Integer(5); requires an explicit cast.
  4. Integer.valueOf("5") returns a primitive int.

Explanation

Assigning a primitive int to an Integer variable triggers autoboxing, which calls Integer.valueOf behind the scenes. Unboxing handles the reverse direction, and parsing a String requires an explicit method call.

Question 42Working With Java Data Types

What is printed by this code? ```java Integer a = 127; Integer b = 127; Integer c = 128; Integer d = 128; System.out.println((a == b) + " " + (c == d)); ```

  1. true false Correct answer.
  2. false true
  3. false false
  4. true true

Explanation

Autoboxing uses Integer.valueOf, which caches values from -128 to 127, so a and b share the same cached object and == is true. The value 128 is outside the cache, so c and d are different objects and == is false; equals would compare values.

Question 43Working With Java Data Types

Which literal represents the char value for a newline?

  1. '\n' Correct answer.
  2. '\r'
  3. "\n"
  4. '\t'

Explanation

A char literal uses single quotes, and the escape sequence \n denotes the line feed character. Double quotes create a String, \r is carriage return, and \t is a tab.

Question 44Working With Java Data Types

What happens when this code runs? ```java int[] a = new int[3]; System.out.println(a[3]); ```

  1. It throws ArrayIndexOutOfBoundsException. Correct answer.
  2. It fails to compile.
  3. It prints 0.
  4. It throws NullPointerException.

Explanation

A new int[3] has valid indices 0, 1, and 2 only. Accessing index 3 is out of range, so the JVM throws ArrayIndexOutOfBoundsException at runtime; the code itself compiles.

Question 45Working With Java Data Types

Which statement about the default value of a char field is correct?

  1. It is '0', the digit zero character.
  2. It is '\u0000', whose numeric value is 0. Correct answer.
  3. It is ' ', the space character.
  4. A char field cannot have a default value.

Explanation

An uninitialized char field holds the null character '\u0000', which has the numeric value 0. This differs from the space character and from the digit character '0', whose code is 48.

Question 46Working With Java Data Types

Which expression correctly parses the String "42" into an int?

  1. Integer.valueOf("42").intValue()
  2. new Integer("42")
  3. Integer.parseInt("42") Correct answer.
  4. Integer.toString(42)

Explanation

Integer.parseInt is the standard static method that returns a primitive int from a numeric String. The other options either return an Integer object, are deprecated, or convert in the wrong direction.

Question 47Using Operators and Decision Constructs

Which operator has the highest precedence among the following?

  1. ++ (prefix) Correct answer.
  2. +
  3. &&
  4. ==

Explanation

Prefix increment is a unary operator and binds tighter than any binary operator. In the Java precedence table unary operators come above multiplicative, additive, relational, and logical operators. Therefore ++ is evaluated before +, ==, and &&.

Question 48Using Operators and Decision Constructs

What is the result of evaluating 7 % -3 in Java?

  1. -1
  2. 1 Correct answer.
  3. 2
  4. -2

Explanation

In Java the remainder operator returns a value whose sign matches the left operand (the dividend). Here 7 divided by -3 gives -2 with remainder 1, so the result is 1. The sign of the divisor does not affect the sign of the remainder.

Question 49Using Operators and Decision Constructs

Given int a = 5; int b = a++ + ++a; what is the value of b after these statements execute?

  1. 10
  2. 13
  3. 12 Correct answer.
  4. 11

Explanation

The postfix a++ yields 5 and then increments a to 6. The prefix ++a then increments a to 7 and yields 7. The sum is 5 + 7 = 12, and a ends at 7.

Question 50Using Operators and Decision Constructs

Which statement about the short-circuit operators && and & is correct when both operands are boolean?

  1. && evaluates the right operand only when the left is true, while & always evaluates it. Correct answer.
  2. Both evaluate the right operand only when the left is true.
  3. & evaluates the right operand only when the left is true, while && always evaluates it.
  4. Both always evaluate the right operand.

Explanation

&& is the short-circuit AND: if the left operand is false, the result is already known and the right operand is skipped. The single & on booleans is the non-short-circuit logical AND and always evaluates both sides. This distinction matters when the right operand has side effects.