0% found this document useful (0 votes)
674 views43 pages

Java SE 17-1

The document contains a series of questions and answers related to the Oracle 1z0-829 JAVA SE 17 OCP certification exam. Each question presents a code fragment or scenario followed by multiple-choice answers, testing knowledge on Java programming concepts. The questions cover various topics including class definitions, exception handling, stream operations, and module migration.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
674 views43 pages

Java SE 17-1

The document contains a series of questions and answers related to the Oracle 1z0-829 JAVA SE 17 OCP certification exam. Each question presents a code fragment or scenario followed by multiple-choice answers, testing knowledge on Java programming concepts. The questions cover various topics including class definitions, exception handling, stream operations, and module migration.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Oracle 1z0-829

JAVA SE 17
OCP
Real Questions and answers
100% Guaranteed
Given the Product class:

and the Shop class:

What is the result?

• A. Compilation fails.

• B. Cookie 0.0 2.99

• C. Cookie 2.99 2.99

• D. Cookie 3.99 2.99

• E. An exception is produced at runtime.

• F. Cookie 0.0 0.0


Given the code fragment:

What is the result?

• A. Cat -
Dog

• B. Cat -
Cat

• C. Dog -
Dog

• D. A NullPointerException is thrown.

• E. Cat -
null

Given:

What is the result?

• A. runsruns

• B. flipsruns
• C. runsflips

• D. Compilation fails.

• E. flipsflips

Given the code fragments:

and:

Which action prints Wagon : 200?

• A. At line n1, implement the java.io.AutoCloseable interface.

• B. At line n3, replace Car with LuxuryCar.

• C. At line n1, implement the java.io.Serializable interface.

• D. At line n3, replace readObject() with readLine().

• E. At line n2, in the main method signature, add throws IOException,


ClassNotFoundException.

• F. At line n2, in the main method signature, add throws IOException, ClassCastException.

Which statement is true about migration?

• A. Every module is moved to the module path in a bottom-up migration.

• B. Every module is moved to the module path in a top-down migration.


• C. Unnamed modules are automatic modules in a top-down migration.

• D. The required modules migrate before the modules that depend on them in a top-down
migration.

Assume you have an automatic module from the module path display-ascii-0.2.jar.
Which name is given to the automatic module based on the given JAR file?

• A. display-ascii-0

• B. display-ascii

• C. display.ascii

• D. display-ascii-0.2

Given the code fragment:

What is the result?

• A. false 0
true 1

• B. false 1
false 2

• C. true 1
false 2

• D. false 1
true 2
Given:

What is the result?

• A. Compilation fails.

• B. wTablewChair TableChair

• C. TableChair TableChair

• D. A RuntimeException is thrown.

• E. wTableChair TableChair

Given the code fragment:

Which set of class definitions compiles?

• A. interface Story extends SInt {}


interface Art extends SInt {}

• B. public interface Story extends SInt {}


public interface Art extends SInt {}

• C. sealed interface Story extends SInt {}


non-sealed class Art implements SInt {}

• D. non-sealed interface Story extends SInt {}


non-sealed interface Art extends SInt {}

• E. non-sealed interface Story extends SInt {}


class Art implements SInt {}
Given:

What is the result?

• A. 4

• B. 2

• C. 6

• D. Compilation fails.

• E. A runtime exception is thrown.

• F. Nothing is printed because of an indefinite loop.

• G. 5

• H. 3

Given the content of the in.txt file:


0123456789
and the code fragment:

What is the content of the out.txt file?

• A. 012345678

• B. 01234567801234

• C. 01234567
• D. 0123456789

• E. 012345678901234

• F. 0123456789234567

Given:

What is the result?

• A. B A D

• B. D A D

• C. B A C

• D. D D D

Given:

What is the result?


• A. mA

• B. mB
mA

• C. mB

• D. mB
mC

Given:

What is the result?

• A. Compilation fails.

• B. there

• C. hello

• D. A NumberFormatException is thrown.

Given:

What is the result?

• A. Compilation fails.
• B. there

• C. hello

• D. A NumberFormatException is thrown.

Given the code fragment:

What is the result?

• A. 0 1 1 0

• B. false true true Optional[NewYear]

• C. 0 1 0 Optional[NewYear]

• D. true true false NewYear

Given:

What is the result?

• A. 0 CLOUDY

• B. 1 SNOWY

• C. 0 SNOWY

• D. 1 RAINY

• E. Compilation fails
Given the code fragment:

Which action enables the code to compile?

• A. Replace record with void.

• B. Replace record with class.

• C. Remove the regNo initialization statement.

• D. Make the regNo variable public.

• E. Make the regNo variable static.

Given the code fragment:

What is the result?

• A. PT5000SPT60MP6D

• B. PT5SPT1MP6D

• C. 5S1M6D

• D. 5000S60M6D
Given the code fragment:

What is the result?

• A. Can't logout

• B. Logged out at: 2021-01-12T21:58:00z

• C. A compilation error occurs at line n1.

• D. Logged out at: 2021-01-12T21:58:19.880z

Daylight Saving Time (DST) is the practice of advancing clocks at the start of spring by one hour and
adjusting them backward by one hour in autumn.
Considering that in 2021, DST in Chicago (Illinois) ended on November 7th at 2 AM, and given the
fragment:

What is the output?

• A. true
true

• B. false
true

• C. true
false

• D. false
false
Given the code fragment:

and

Which is true?

• A. The program prints t1 : 1 : t2 : 1: t1 : 2 : t2 : 2 : in random order.

• B. The program prints t1 : 1 : t2 : 1: t1 : 2 : t2 : 2 :

• C. The program prints t1 : 1 : t2 : 1: t1 : 1 : t2 : 1 : indefinitely.

• D. The program prints an exception.

Given the code fragment:

What is the result?

• A. true:true:false:false

• B. true:false:true:false

• C. true:false:true:true
• D. true:false:false:false

Given:

What is the result?

• A. {bicycle=7, car=7, motorcycle=7, truck=7}

• B. {3:bicycle, 0:car, 6:motorcycle, 5:truck}

• C. Compilation fails.

• D. {bicycle=1, car=3, motorcycle=1, truck=2}

• E. {bicycle, car, motorcycle, truck}

Which statement is true?

• A. IllegalStateException is thrown if a thread in waiting state is moved back to runnable.

• B. A thread in waiting state consumes CPU cycles.

• C. After the timed wait expires, the waited thread moves to the terminated state.

• D. A thread in waiting state must handle InterruptedException.

Given:

Which two modifications enable the code to print Open Close?

• A. Replace line n1 with:


class Folder extends Closeable {
• B. Replace line n1 with:
class Folder implements AutoCloseable {

• C. At line n2, insert:

• D. Replace line n1 with:


class Folder extends Exception {

• E. At line n2, insert:

Given the code fragment:

Which code at line n1, obtains the java.io.Console object?

• A. Console console = Console.getInstance();

• B. Console console = System.console();

• C. Console console = new Console(System.in);

• D. Console console = new Console(new InputStreamReader(System.in));

• E. Console console = System.console(System.in);

Given the course table:

Given the code fragment:


What is the result?

• A. 2

• B. true

• C. false

• D. 1

Given the code fragment:

Which action sorts the book list?

• A. At Line n2, replace books.sort() with books.stream().sort().

• B. At Line n1, convert books type to mutable ArrayList type.

• C. At Line n2, replace compareTo() with compare().

• D. At Line n1, convert books type to mutable array type.


Given:

Which two method invocations execute? (Choose two.)

• A. new MyC().m2();

• B. IFace.m4();

• C. IFace myClassObj = new MyC();


myClassObj.m3();

• D. IFace myClassObj = new MyC();


myClassObj.m4();

• E. IFace.m3();

• F. IFace.m2();

Given:

and the code fragment:

What is the result?


• A. Marketing

• B. Marketing -

Finance -
Technical

• C. Marketing -
UnDefined

• D. UnDefined

Assuming that the data.txt file exists and has the following content: text1 text2 text3
Given the code fragment:

What is the result?

• A. text1-
text2-
text3-
text3

• B. text1-text2-text3
A java.lang.IndexOutOfBoundsException is thrown.

• C. text1-text2-text3
text1
text2
text3

• D. text1-text2-text3
text3
Given the code fragment:

What is the result?

• A. 1
2
-4

• B. 2
-2

• C. 1
1
1

• D. 2
2
0

Given the code fragment:


List<Integer> listOfNumbers = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Which code fragment returns different values?

• A. int sum = listOfNumbers.stream().reduce(0, Integer::sum) + 5;

• B. int sum = listOfNumbers.parallelStream().reduce(0, Integer::sum) + 5 ;

• C. int sum = listOfNumbers.parallelStream().reduce((m, n) -> m + n).orElse(5) + 5;

• D. int sum = listOfNumbers.parallelStream().reduce(5, Integer::sum);

• E. int sum = listOfNumbers.stream().reduce(5, (a, b) -> a+ b);


Given the code fragment:

What is the result?

• A. Range1 -

Range2 -

Range3 -
Range1 -
Not a valid rank.

• B. Range1 -
Not a valid rank.

• C. Range1 -

Range2 -
Range3

• D. Range1

Given the code fragment:

What is the result?

• A. 888

• B. 8109

• C. 7107

• D. 777

• E. 71010

• F. 81111
Given:

and the code fragment:

Which statement is true?

• A. The program throws ClassCastException.

• B. The program fails to compile.

• C. The program throws StockException.

• D. The program throws OutofStockException.


Given:

What is the result?

• A. Software Game read error

• B. Software Game Chess 0

• C. Software Game Software Game Chess 2

• D. Software Game Chess 2

• E. Software Game write error

• F. Software Game Software Game Chess 0

Which two code fragments compile? (Choose two.)


• A. Class A {} class B extends A{}

• B. Class L3 {

• C. class L5 {
• D. Class l1{

• E. Class L6

• F.

Which statement is true about modules?

• A. Only unnamed modules are on the module path.

• B. Automatic and named modules are on the module path.

• C. Only automatic modules are on the module path.

• D. Only named modules are on the module path.

• E. Automatic and unnamed modules are on the module path.


Given the code fragment:

Which two statements at Line n1 independently enable you to print 1250? (Choose two.)

• A. Integer res = 250 + Integer.parseInt(s);

• B. Integer res = 250 + Integer.valueOf(s);

• C. Integer res = 250 + s2;

• D. Integer res = 250;


res =+ s2;

• E. Integer res = 250 + s;

• F. Integer res = 250 + Integer(s2);

Given:

What is the result?

• A. 100
100
1000

• B. 101
101
1000

• C. 1001
100
1000
• D. 1001
1001
1000

Given:

and the code fragment:

What is the result?

• A. 100.00
CellPhone,ToyCar,Motor,Fan

• B. 100.00
CellPhone,ToyCar

• C. 300.00
CellPhone,ToyCar

• D. 300.00
CellPhone,ToyCar,Motor,Fan

Given:
Captions.properties file:
user = UserName
Captions_en.properties file:
user = User name (EN)
Captions_US.properties file:
message = User name (US)
Captions_en_US.properties file:
message = User name (EN - US)
and the code fragment:

What is the result?

• A. User name (EN - US)

• B. The program throws a MissingResourceException.

• C. UserName

• D. User name (EN)

• E. User name (US)

Given the code fragment:

Which code fragment invokes all callable objects in the workers set?

• A.

• B. executorService.submit(cThreads);
• C.

• D.

Given the code fragment:

What is the result?

• A. ABBCDE // the order of elements is unpredictable

• B. ABCDE

• C. ABCDE // the order of elements is unpredictable

• D. ADEABCB // the order of elements is unpredictable

Given the directory structure:

Given the definition of the Doc class:

Which two are valid definitions of the WordDoc class? (Choose two.)

• A. package p1.p2;
public non-sealed class WordDoc extends Doc { }
• B. package p1;
public final class WordDoc extends Doc {}

• C. package p1;
non-sealed abstract class WordDoc extends Doc {}

• D. package p1.p2:
public sealed class WordDoc extends Doc { }

• E. package p1;
public class WordDoc extends Doc {}

• F. package p1;
public non-sealed class WordDoc extends Doc {}

Given:

Which action enables the code to compile?

• A. Replace 2 with static String name;

• B. Replace 7 with public static void display(String design) {

• C. Replace 3 with private static void display() {

• D. Replace 15 with Item.display("Flower");

Which statement is true?

• A. The lock() method returns a boolean indicator immediately regardless if it has or has not
managed to acquire the lock.

• B. The lock() method returns a boolean indicator immediately if it has managed to acquire
the lock, otherwise it waits for the lock acquisition.
• C. The tryLock() method returns a boolean indicator immediately if it has managed to
acquire the lock, otherwise it waits for the lock acquisition.

• D. The tryLock() method returns a boolean indicator immediately regardless if it has or has
not managed to acquire the lock.

import java.text.NumberFormat;

import java.util.Locale;

public class Main {

public static void main(String[] args) {

int saleAmount = 10000;

NumberFormat format1 = NumberFormat.getCurrencyInstance(Locale.US);

NumberFormat format2 = NumberFormat.getCompactNumberInstance(Locale.US,


NumberFormat.Style.SHORT);

String res = format1.format(saleAmount);

System.out.println(res);

format2.format(Integer.valueOf(res));

System.out.println(saleAmount);

$10,000.00

An Exception is thrown

public class Main {


public static void main(String[] args) {
try {
myMethod();
}
// line n1
}
public static void myMethod() throws
NumberFormatException,ArrayIndexOutOfBoundsException,Exception{
int a[] = new int[2];
a[2] = 0;}}
catch (Exception e){
e.printStackTrace();
}

try (Connection con = DriverManager.getConnection(connectionString, username, password)) {


con.setAutoCommit(false);
Statement stmt = con.createStatement();

Savepoint spl = con.setSavepoint("p1");


String qry = "UPDATE course SET course_fee = 1000 WHERE COURSE_ID = 1";
stmt.execute(qry);

Savepoint sp2 = con.setSavepoint("p2");


String qry2 = "UPDATE course SET course_fee = 800 WHERE COURSE_ID = 3";
stmt.execute(qry2);

con.rollback(spl); // Rolls back to savepoint p1


} catch (SQLException sqlException) {
System.out.println("SQL Exception: " + sqlException);
}

The program executes and the rows of the table are not updated

Which three local variable initialization statements are correct ?

var var = 9.99;


String [] data = { “””
Line 1
Line 2”””,”Line3”};

Stream.of(3, 6, 9, 12, 15, 18,21,24,27).takeWhile(s -> s % 3 == 0)


.dropWhile (s -> s % 2 == 0)
.limit (3).forEach (s -> System.out.print(s+ " "));

369

Integer grade = 5;
switch(grade){
case 1,2,3 -> System.out.print("Region 1");
case 4,6 -> System.out.print("Region 1");
case 7,9 -> System.out.print("Region 1");
default -> System.out.println("Invalid grade");
}
Invalid grade
int c = 0;
x:
for(int a = 3;a>0;a--){
for (int b = 0 ;b<3 ;b++,c--){
if(b==1) continue x; else if (a==1) break ; c+=a+b;
}
}
System.out.println(c);

Instant loginTime = Instant.now();


Thread.sleep(1000);

Instant logoutTime = Instant.now();


loginTime = loginTime.truncatedTo(ChronoUnit.MINUTES);
logoutTime = logoutTime.truncatedTo(ChronoUnit.MINUTES);

if(logoutTime.isAfter(loginTime))
System.out.println("Logged out at : "+logoutTime);
else
System.out.println("Can't logout ");

Can't logout

var list = new CopyOnWriteArrayList<>(List.of("Java","Duke","Cafe","Babe"));


Thread t1 = new Thread(()->{
try{
Thread.sleep(150);
}catch (InterruptedException e){
}
int i =0;
for(var s: list ){
list.set(i++,s.toUpperCase());
}
System.out.print(list + " ");
});
Thread t2 = new Thread(()->{
for(var s : list){
try{
Thread.sleep(50);
}catch (InterruptedException e){
}
System.out.print(s+ " ");
}});
t1.start();
t2.start();
Java Duke [JAVA, DUKE, CAFE, BABE] Cafe Babe is printed and order of elements is unpredictable
package p1; public abstract sealed class Doc permits WordDoc{ String docName; public abstract
void printDoc(); public String getName() { return docName; } }

which statement is true ?


The getName() method should be abstract.
The WordDoc class should exist within p1 of module1 .
The Doc class must declare non-abstract.
The WordDoc class could exist within another package,p2, od module1.

1. class App {
String name;
public App(String name)
{ this.name = name; }
public static void main(String args[]){
App t1 = new App("t1");
App t2 = new App("t2");
t1 = t1;
t1 = null;
System.out.println("GC");
}
}
which statement is true while the program print GC?
1 * Only the object referenced by t2 is eligible for garbage collection
2* Both th objects previously referenced by t1 are eligible for garbage collection
3 * Only on of the objects previously referenced by t1 is eligible for garbage collection
4 * None of the bojects are eligible for garbage collection
which two statements are true about the reentrant mutual exclusion lock in java
1 *it favors the longest-waiting thread to acquire the lock first, by default
2 * it favors the longest-waiting thread to acquire the lock first only if optional fairness parameter
set to true
3 * it enables asynchronization execution of java threads while accessing shared resources
4 * it makes a thread to acquire a lock only once
5 * it allows thread to enter into the lock on a resource more than once

Which two interface definitions compile?

1* Public abstract sealed interface SealedInterface permits Story, Art{


Default String getTitle(){
Return “Book Title”;
}
Class Story implements Book{}
Class Story implements Book{}

2* interface IFace1{
Public static final String sname = “House and mouse”;
Private voice readStory(){}
}

3* interface IFace2{
public default int getCounter(){
return 10;}
Public static void displayTitle();
Public void shareFile();
}

4* interface IFace3 {
Public default int getCounter(){
Return 10;}
Public final void displayTitle(){System.out.println(“Displayed.”)};
}

5* interface IFace4 {
Public default int getCounter1(){return 10;}
Public void displayTitle1();
}
int newE, e =4;
newE = switch (e){
case 1,2 ->e+5;
case 3,4 ->e+3;
case 5,6 ->e+1;
};
System.out.println(newE);

what is the result?

The code fails to compile

public static int findSq(int x){


var x1 = 10;
return x1 * x;
}

public static void main(String[] args) throws Exception {


var n =9;
var s = findSq(n);
System.out.println(s);
n=8;
s = findSq(n);
System.out.println(" "+s);
}

at line n3 replace var x with int x


record Item(int id, String name){
static{
if (name.length() < 3){
throw new IllegalArgumentException();
}
String qualityCode;
}

record Item(int id, String name){


public Item{
if (name.length()<3){
throw new IllegalArgumentException();
}
}
static String qualityCode;
}

record Item (int id, String name){


public Item{
if(name.length()<3){
throw new IllegalArgumentException();
}
}
String qualityCode;
}

record Item(int id, String name){


public Item{
if(name.length()<3){
throw new IllegalArgumentException();
}
}
}

record Item(int id, String name){


public void Item(String n){
this.name = n;
if (name.length()<3){
throw new IllegalArgumentException();
}
}

record Item(int id, String name){


String name = "ho";
public void Item(){
if (name.length()<3){
throw new IllegalArgumentException();
}
}
}
LocalDate d1 = LocalDate.of(2021, Month.JANUARY, 1);
LocalDate d2 = d1.plus(Period.ofDays(-10)).withMonth(1);
LocalDateTime ldt = d2.atTime(LocalTime.of(11, 11));
if (d1.isAfter(d2) ^! d1.getMonth().equals(ldt.getMonth())){
System.out.println(d1.isAfter(d2));
System.out.println(d1.getMonth().equals(ldt.getMonth()));
System.out.println(d1.isAfter(d2) ^! d1.getMonth().equals(ldt.getMonth()));
ldt = d2.atTime(LocalTime.of(12, 12));
}
System.out.println(ldt.format(DateTimeFormatter.ofPattern("HHMM")));

What is the result

1201

LocalDate now = LocalDate.of(2021, Month.AUGUST, 17);


LocalDate this_laborDay = LocalDate.of(2021, Month.MAY, 1);
LocalDate next_labourDay = this_laborDay.plusYears(1);
LocalDate add_week = next_labourDay.plusDays(7);
Period p = now.until(add_week);
System.out.println(p);

P8M21D
String username = "root";
String password = "";
try (Connection con =
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/course?createDatabaseIfNotExist=tru
e", username, password)) {

try (
Statement st1 = con.createStatement();
PreparedStatement st2 = con.prepareStatement("INSERT INTO course VALUES (?,?,?)")) {
st2.setInt(1, 1022);
st2.setString(2, "JAVA ARCHITECT");
st2.setDouble(3, 600);
st2.executeUpdate();
try (ResultSet rs = st1.executeQuery("Select sum(course_fees) from course")) {
rs.next();
System.out.println(rs.getDouble(1));
} catch (Exception e) {
System.err.println("1");
System.out.println(e);
}
}
} catch (Exception e) {
System.err.println("2");
System.out.println(e);
}
1000.0
which statement is true?

1* the --add-requires option is allowed but not recommended in a java command

2* the --add-requires option in not allowed in a java command

3* the --add-exports option is always recommended in a java command

4* the --add-exports option is not allowed in a java command

Hello

Java 17.0.0

Which code fragment leads to its display?


String str = "Hello";
String blk5= str+
"""

Java 17.0.0""";
System.out.println(blk5);

Given: public enum Designation{

CEO('A'),CMO('B'),CTO('C'),CFO('D');

char c;

private Designation(char c){

this.c =c;

public static void main(String[] args) {

System.out.println(Designation.valueOf("CMO"));

System.out.println(Designation.values()[0].name());

CMO

CEO
Path p1 = Paths.get("fldr1\\fldr2\\file1.txt");

Path p2 = Paths.get("fldr3\\file1.txt");

System.out.println(p1.resolve(p2));

System.out.println(p1.relativize(p2));

fldr1\fldr2\file1.txt\fldr3\file1.txt

..\..\..\fldr3\file1.txt

Which code fragment at Line n1 copies the content from dataSrc.txt to dataBkup.txt?

try(
FileInputStream fis = new FileInputStream("dataSrc.txt");
FileOutputStream fos = new FileOutputStream("dataBkup.txt")
){
//line 1

} catch (IOException e) {
e.printStackTrace();
}

fis.transferTo(fos);

public static void main(String[] args) throws InterruptedException {


Locale.setDefault(new Locale("en","GB"));
ResourceBundle rb = ResourceBundle.getBundle("msg",new Locale("fr"));
NumberFormat nf = NumberFormat.getCurrencyInstance();
String result = MessageFormat.format(rb.getString("product"),"Tea",nf.format(1.99));
System.out.println(result);
}

Tea, le prix £1.99


package com.transport.vehicle.cars;

public interface Car {


int getSpeed();
}

and

package com.transport.vehicle.cars.impl;
import com.transport.vehicle.cars. Car;

public class CarImpl implements Car {


private int speed;
public CarImpl() {
this (10);
}
public CarImpl (int speed) {
this.speed = speed;
}

@Override
public int getSpeed() {
return speed;
}
}

requires com.transport.vehicle.cars;

provides com.transport.vehicle.cars.Car with com.transport.vehicle.cars.impl.CarImpl

You might also like