0% found this document useful (0 votes)
52 views28 pages

mock-4 verified

The document contains a series of programming questions and code snippets related to Java, covering topics such as annotations, exception handling, serialization, threading, and streams. It includes multiple-choice questions and code fragments that require understanding of Java syntax and behavior. The questions test knowledge on various Java concepts, including class inheritance, method overriding, and data structures.

Uploaded by

pepesheet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views28 pages

mock-4 verified

The document contains a series of programming questions and code snippets related to Java, covering topics such as annotations, exception handling, serialization, threading, and streams. It includes multiple-choice questions and code fragments that require understanding of Java syntax and behavior. The questions test knowledge on various Java concepts, including class inheritance, method overriding, and data structures.

Uploaded by

pepesheet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

public class Point {

@JsonField(type=JsonField.Type.STRING, name="name")
private String _name;

@JsonField(type=JsonField.Type.INT)
private int x;

@JsonField(type=JsonField.Type.INT)
private int y;
}

What is the correct definition of the JsonField annotation that makes the Point class c
ompile?
A)
@Target (ElementType.FIELD)
@interface JsonField {
String name() default "";
enum Type {
INT, STRING, BOOLEAN
};
Type type();

B)
@interface JsonField {
String name ();
enum Type {
INT, STRING, BOOLEAN
};
Type type();
}
C)
@Retention(RetentionPolicy.RUNTIME)
@Target (ElementType.METHOD)
@interface JsonField {
String name() default "";
enum Type {
INT, STRING, BOOLEAN
};
Type type();

Option
A
Option
B
Option
C
Which module is required for any application using Swing or AWT?

java.prefs
java.deskto
p
Java.se
java.rmi
Java.loggin
g

Given:
public class Test {
class L extends Exception { }
class M extends L { }
class N extends RuntimeException { }
public void p() throws L { throw new M(); }
public void q() throws N { throw new N(); }
public static void main(String{] args) {
try {
Test t = new Test();
t.p();
t.q():
} /*line 1*/ {
System.out.println("Exception caught");
}
}
}

What change on line 1 will make this code compile?

Add catch (N | L | M e
).
Add catch (L |N e).
Add catch (L |M N e).
Add catch (L e).
Add catch (M |L e).
Given:

public class Confidential implements Serializable{


private String data;

publick Confidential(String data) {


this.data = data;
}
}

Which two are secure serialization of these objects? (Choose two.)

Define the serialPersistentFields array field.


Declare fields transient.
Implement only readResolve to replace the instance with a serial proxy and not wr
iteReplace.
Make the class abstract.
Implement only writeReplace to replace the instance with a serial proxy and not re
adResolve

Which two can be considered good practices for serializing Java objects? (Choose two
.)

Implement serialization for long-term data storage.


Always override the readObject/writeObject methods from the java.io.Serializable i
nterface.
Implement secure serialization by generating secure object hash or using encrypti
on.
Ensure that the class definition used is the same as the class definition used by Jav
a runtime at the time when the object was serialized.
Assign null value by default while serializing and deserializing a transient variable.

?Given :
class Separators {
public static String separator = "/";
public static String pathSeparator = ":";
}
To secure this code ,you want to make sure that the client code cannot modify the fi
elds .

enum Separators {
separator,
pathSeparator
}
class Separators {
private static String separator ="/";
private static String pathSeparator
= ":";
}
abstract class Separators {
public static String separator = "/";
public static String pathSeparator =
":";
}
class Separators {
private static String separator ="/";
private static String pathSeparator
= ":";
}
interface Separators {
String separator = "/";
String pathSeparator = ":",
}

Given :
int i = 10;
do {
for (int j = i / 2; j > 0; j--) {
System.out.print(j + " ");
}
i -= 2;
} while (i > 0);

What is the result?

5432143213212
11
54321
5
Nothing
Given:
public class DNASynth {
int aCount;
int tCount;
int cCount;
int gCount;

int getACount (int aCount) {


return aCount;
}
int getTCount (int tCount) {
return this.tCount;
}
int getCCount () {
return getTotalCount () - this.aCount - getTCount (0) - gCount;
}
int getGCount () {
return getGCount () ;
}
int getTotalCount ( ) {
return aCount + getTCount (0) + this. cCount + this.gCount;
}
}

Which two methods facilitate valid ways to read instance fields? (Choose two.)

getGCount
getACount
getTCount
getTotalCou
nt
getCCount

Given:
public interface TestInterface {
default void samplingProbeProcedure () {
probeProcedure () ;
System.out.println ("Collect Sample");
System.out.println ("Leave Asteroid");
System.out.println ("Dock with Main Craft");
}
default void explosionProbeProcedure () {
probeProcedure () ;
System.out.println ("Explode");
}
}

Examine these requirements:

Eliminate code duplication.


Keep constant the number of methods other classes may implement from this interfa
ce.

Which method can be added to meet these requirements

A. private default void probeProcedure () {


System.out.printIn("Launch Probe");
System.out.printIn("Land on Asteroid");
}

B. static void probeProcedure () {


System.out.println ("Launch Probe");
System.out.println ("Land on Asteroid");
}

C.private void probeProcedure () {


System.out.println ("Launch Probe");
System.out.println ("Land on Asteroid");
}

D.default void probeProcedure () {


System.out.println ("Launch Probe");
System.out.println ("Land on Asteroid");
}

Option A
Option
D
Option C
Option B

Consider this method declaration:


void setSessionUser(Connection conn, String user)throws SQLException {
Statement stmt = conn.createStatement();
String sql = <EXPRESSION>;
stmt .execute();
}

A) “SET SESSION AUTHORIZATION “ + user


B) “SET SESSION AUTHORIZATION “ + stmt.enquoteIdentifier(user)
Is A or B the correct replacement for <EXPRESSION> and why?

A, because it sends exactly the value of user provided by the calling cod
e
B, because enquoting values provided by the calling code prevents SQL i
njection.
B, because all values provided by the calling code should be enquoted.
A, because it is unnecessary to enclose identifiers in quotes.
A and B are functionally equivalent.

Given :

public class Sportscar extends Automobile {


private float turbo;
....
public void setTurbo (float turbo) {
this.turbo = turbo;
}
}

What is known about the Sportscar class?

The Sportscar class is a superclass that has more functionality than the Automo
bile class.
The Sportscar class is a subclass of Automobile and inherits its methods.
The Sportscar subclass cannot override setTurbo method from the superclass A
utomobile.

The Sportscar class inherits the setTurbo method from the superclass Automobil
e.

Given:
char[] characters = new char[100];
try (FileReader reader = new FileReader("path to file")) {
// line 1
System.out.println(String.valueOf(characters));
} catch(IOException e) {
e.printStackTrace();
}
You want to read data through the reader object.
Which statement inserted on line 1 will accomplish this?
System.in.read(character
s);
reader.readline();
reader.read(characters);
characters.read(0,29);

Your organization provides a cloud server to your customer to run their Java trini
changes for the next release and you see this change in one of the config files:
old: JAVA_OPTS-"SJAVA_OPTS -Xms8g -Xmx8g"
new: JAVA OPTS-"SJAVA OPTS -Xms8g -Xix8g -noverify"
Which is correct?

You reject the change because whiskey is a critical security risk;


You accept the change because noverify is necessary for your code to run with the
Version of Java.

You reject the change because Xmasg Xmxla uses too much system memory,
You accept the change because hoverity is a standard option that has been suppaJ
ava 1.0.

Given the code fragment:

module citizen {
exports com.name to greeting;
}
And

module greeting {
}

Which statement is true?

public members in the com.name package are accessible to all modules.


All members of com.name are accessible only to the citizen and greeting modules.

All members in the com.name package are accessible only to the greeting module.
public members in the com. name package are accessible only to the greeting mo
dule.
Inserting "requires citizen;" at greeting's module-Info.java, enables com.name me
mbers accessible to the greeting module.

?Givem :

public class A {
int a = 0;
int b = 0;
int c = 0;

public void foo (int i) {


a += b * i;
c -=b*i;
}
public void setB (int i) {
b = i;
}
}
Which makes class A thread safe?

Make setB synchronized.


Make A synchronized.
Class A is thread safe.
Make foo synchronized.
Make foo and setB synchroni
zed.

Given :

package A ;
class Test {
String name;
public Test (String name) {
this. name = name;
}
public String tostring()
return name;
}
}
and
package B;
import A.Test;
public class Main {
public static void main (String [ ] args) {
Test test = new Test ("Student");
System.out.printin (test);
}
}

What is the result?

nothing
It fails to compil
e.
name
Student
null

Given:
public class Test {

private static class Greet


{

private void print()


{
System.out.println("Hello World");

}
}

public static void main(String[] args) {

Test.Greet i= new Greet();


i.print();

}
}

The compilation fails at line


8.
Hello World
The compilation fails at line
9.
The compilation fails at line
2.

Given :

static StringBuilder sb1 = new StringBuilder("yo ");


static StringBuilder sb2=new StringBuilder("hi ");

public static void main(String[] args) {

sb1 = sb1.append(new StrBldr2().foo(new StringBuilder("hey")));


System.out.println(sb1);

}
StringBuilder foo(StringBuilder s)
{
sb2=sb2.append(s+ "oh" );
return sb2;
}
}
What is true ?

hey hi hey oh
yo hi
A compile time error occu
rs
yo hi hey oh
hey oh yo hi

var c = new CopyOnWriteArrayList<>(List.of("1", "2", "3", "4"));

Runnable r = () -> {
try {
Thread.sleep(150);
} catch (InterruptedException e) {
System.out.println(e);
}
c.set(3, "four");
System.out.print(c + " ");
};

Thread t = new Thread(r);


t.start();
for (var s : c) {
System.out.print(s + " ");
Thread.sleep(100);
}
What is the output?

1 2 [1, 2, 3, 4] 3 4
1 2 [1, 2, 3, 4] 3 four
1 2 [1, 2, 3, four] 3 4
1 2 [1, 2, 3, four] 3 fo
ur

Given:
List<String> longList = List.of(“Hello”,”World”,”Beat”);
List<String> shortList = new ArrayList<>();
Which code fragment will not forms a short list of words containing the letter “e”?

A. longList.stream()
.filter(w-> w.indexOf('e') != -1)
.parallel()
.forEach(w-> shortList.add(w));
B. longList.parallelStream()
.filter(w-> w.indexOf('e') != -1)
.forEach(w-> shortList.add(w));
C. shortList = longList.stream()
.filter(w-> w.indexOf('e') != -1)
.parallel()
.collect(Collectors.toList());
D. longList.stream()
.filter(w-> w.indexOf('e') != -1)
.parallel()
.collect(shortList);

Option
A
Option
B
Option
D
Option
C

Which interface in the java.util.function package can return a primitive type?


ToDoubleFuncti
on
LongConsumer
Supplier
BiFunction

?Given :
public class StrBldr {
static StringBuilder sbl = new StringBuilder("yo ");
StringBuilder sb2=new StringBuilder("hi ");
StringBuilder foo(StringBuilder s)
{
System.out.print (s + " oh " + sb2);
return new StringBuilder("ey");
}
public static void main(String[] args) {
sbl = sbl.append(new StrBldr().foo(new StringBuilder("hey")));
System.out.println(sbl);
}
}
What is the result ?

A compile time error occu


rs.
hey oh hi
oh hi hey
hey oh hi yo ey
yo ey

?Given :

public class Main (


public static void main(String[] args) {
List<String> fruits = List.of("banana", "orange", "apple", "lemon");
Stream<String> s1 = fruits.stream();
Stream<String> s2 = s1.peek(i -> System.out.print(i + " "));
System.out.println(" -----");
Stream<String> s3 = s2.sorted();
Stream<String> s4 = s3.peek (i -> System.out.print(i + " "));
System.out.println(" -----");
String strFruits = s4.collect(Collectors.joining (","));

What is the output?


-----
-----
-----
banana orange apple lemon
-----
apple banana lemon orange
-----
-----
banana orange apple lemon apple banana lemon
orange

banana orange apple lemon


-----
apple banana lemon orange
-----
banana orange apple lemon apple banana lemon o
range
-----
-----

Given :

import java.util.*;
public class Foo {
public List<Number> Foo (Set<CharSequence> m) { . . . }
}
and
import java.util.*;
public class Bar extends Foo {
//line 1
}

Which two statements can be added at line 1 in Bar to override compile it? (Choose t
wo.)

public List<Integer> Foo(Set<CharSequence> m) { ..


.}
public List<Integer> Foo(Set<String> m) { ... }
public ArrayList<Number> Foo(Set<CharSequence>
m) { ... }
public List<Integer> Foo(TreeSet<String> m) { ... }
public List<Object> Foo(Set<CharSequence> m) { ...
}
Given the code fragment:

public static void main (String [ ] args) {


List<Integer> even = List.of () ;
even. add (0, -1);
even.add (0, -2);
even. add (0, -3);
System.out.println (even);
}

What is the output?

[-3, -2, -1]


A runtime exception is thro
wn
The compilation fails.
[-1, -2, -3]

Given:
public static void main(String[] args) {
final List <String> fruits =
List.of("Orange", "Apple", "Lemon", "Raspberry");
final List<String> types =
List.of("Juice", "Pie", "Ice", "Tart");
final vatream = IntStream.range(0, Math.min(fruits.size(), types.size()))
.mapToObj((i)->fruits.get(i) +" " +types.get(i));
stream. forEach(System.out::printIn);
}

What is the result?

The compilation fails.


Orange Juice
The program prints nothing.
Orange Juice Apple Pie Lemmon Ice Raspberr
y Tart

Which two statements compile?


Integer i=11;
Double e = Double.parseDoubl
e(i);

double d=i;

Double c=(Double)i;

Double b=Double.valueof(i);

public class Main {

static Map<String, String> map = new HashMap<>();


static List<String> keys = new ArrayList<>(List.of("A", "B", "C", "D"));
static String[] values = { "one", "two", "three", "four" };

static {
for (var i = 0; i < keys.size(); i++) {
map.put(keys.get(i), values[i]);
}
}

public static void main(String[] args) {


keys.clear();
values = new String[0];
System.out.println("Map: " + map.size() + "Keys: " + keys.size() + " Values: " + val
ues.length);
}
}

What is the result?

Map: 0 Keys: 0 Values


:0
Map: 4 Keys: 4 Values
:4
Map: 4 Keys: 0 Values
:0
The compilation fails.
Map: 0 Keys: 4 Values
:4
Given this enum declaration:
1. enum Alphabet {
2. A, B, C
3.
4. }

Examine this code:

System.out.printIn(Alphabet. getFirstLetter());

What code should be written at line 3 to make this code print A?

static String getFirstLetter() { return A.toString(); }

String getFirstLetter() { return A.toString(); }


final String getFirstLetter() { return A.toString(); }
static String getFirstLetter() { return Alphabet.values()
[1].toString(); }

Given :

List<String> list = ... ;


list.forEach ( x -> ( System.out.printin (x); } ):

What is the type of x?

String
List<Characte
r>
char
List<String>

public class Plant { }


and

public class Tulip extends Plant { }


and

public class Garden {


private static Plant plant;
public static void main(String[] args) {
plant = new Tulip();
feed (plant);
feed(plant) ;

public static void feed(Plant p) {


if (p instanceof Tulip) {
System.out.println("Take extra care");
}
p = null;
}
}
What is the result?

The program prints nothing.


Take extra care
Take extra care
Take extra care
An exception is thrown at runti
me

Which 2 var declaration are correct?

var y = null;
var var = "hello";
var a;
var names = new ArrayList<
>();
var _ = 100;

public class Menu {


enum Machine{
AUTO("Truck"), MEDICAL ("Scanner") ;
private String type;
private Machine(String type) {
this.type = type;
}
private void setType(String type) {
this.type = type; // line 1
}
private String getType() {
return type;
}
}
public static void main(String[] args) {
Machine.AUTO.setType ("Sedan") ; //line 2
for (Machine p : Machine.values()) {
System.out.printin(p + ": " + p.getType()); // line 3

}
}
}
A)An exception is thrown at run time.
B)Auto:Sedan
Medical: Scanner
C)The compilation fails due to an error on line 2.
D)The compilation fails due to an error on line 1.
E)The compilation fails due to an error on line 3.

Option
B
Option
E
Option
A
Option
C
Option
D

Given TripleThis.java:
6. import java.util.function.*;
7. public class TripleThis {
8. public static void main(String[] args) {
9. Function tripler = x -> { return (Integer) x * 3; };
10. TripleThis.printValue(tripler, 4);
11. }
12. public static <T> void printValue(Function f, T num) {
13. System.out.println(f.apply(num));
14. }
15. }

Compiling TripleThis.java gives this compiler warning:


Note: TripleThis.java uses unchecked or unsafe operations.
Which two replacements done together remove this compiler warning?
Replace line 12 with public static <T> void printValue(Function<T, Integer> f
, T num) {
Replace line 12 with public static int printValue (Function f, T num) {.
Replace line 9 with Function<Integer, Integer> tripler = x-> { return (Integer
) X * 3 ; }.
Replace line 12 with public static void printValue (Function f, int num) {.

Given:
class Animal {}
class Dog extends Animal {}
class Petdog extends Dog {}
//and
1. class House<A extends Animal> {}
2. public House<? super Dog> build (A a) {
3. // insert code here
4.}
5. }

Which two statements inserted independently on line 3 will make this code compile?

return new House<?>();


return new House<Petdog
>();
return new House<A>();
return new House<Animal
>();
return new House<Dog>();

class Box implements Serializable {


private int box1d;
private String size;
private List items;
}

// Given the code fragment from Item.java:


class Item {
private int id;
private String name;
}
Given the information
The classes Box and Items are encapsulated with getters and setter method:
The classes Box and Items contains required constructors source code.

public static void main(String[] args) {

List items1 = new ArrayList<>();


items1.add(new Item(1, "Pen"));
items1.add(new Item(2, "Ruler"));
Box bl = new Box(123, "s", items1);

try (FileOutputStream fout = new FileOutputStream("boxser.txt");


ObjectOutputStream out = new ObjectOutputStream(fout);) {

out.writeObject(bl);
out.flush();
out.close();
} catch (Exception e) {
System.out.println("Unable to Serialize");
}
}

Which actionserialize the b1 object?

Add SerialVersionUID to the Box and Item class.

Implement the Serializable interface in the Item class.


Override readObject() and writeObject() methods in the Book class.
Remove out.flush() method invocation.
Handle NotSerializableException in the try clause or throw in the main () method d
efinition.

Given :
public class Main {
public static void main(String[] args) {
List<player> players = List.of (new Player ("Scott", 115), new Player ("John", 70), ne
w Player ("Jelly", 105));
double average = // line 1
System.out.println("The average is: " + average);
}
}
class Player {
public String name;
public int score;
public Player (String name, int score) {
this.name = name;
this.score = score;
}
}

You want to calculate the average of the Player’s score.


Which statement inserted on line 1 will accomplish this?

players.stream().mapToInt(a -> a.score).average().orEls


e(0.0);
players.stream().average().orElse(0.0);
players.stream().map(a -> a.score).average();
players.stream().mapToDouble(a -> a.score).average();

our application uses one modular jar (a.jar), which, in turn, uses one non-modular jar
(b.jar). Which of the following commands will cause jdeps to include the non-modular
jar in its analysis?
Select 1 best option:

jdeps --module-path lib\a.jar; lib\b.jar


jdeps --class-path lib\a.jar; lib\b.jar
jdeps -cp lib\b.jar lib\a.jar

jdeps -cp lib\b.jar;lib\a.jar


jdeps -module-path lib\a.jar; -classpath lib\
b.jar

Given :

public interface A {
public Iterable a ();
}
public interface B extends A {
public Collection a ();
}
public interface C extends A {
public Path a ();
}
public interface D extends B, C {
}

Why does D cause a compilation error?

D extends more than one interface.


D inherits a() from B and C but the return types are incomp
atible.
D inherits a() only from C.
D does not define any method.

Which statement about access modifiers is correct?

An instance variable can be declared with the static mo


difier.
An inner class cannot be declared with the public modifi
er.
A local variable can be declared with the final modifier.
An interface can be declared with the protected modifier
.
An abstract method can be declared with the private mo
difier.

A company has an existing Java app that includes two Java 8 jar files, sales-3.10. jar
and clients10.2.jar.
The jar file ,sales -8, 10, jar reference packages in clients -10.2 jar,
but clients-10.2 jar does not reference packages in sales -8.10, jar.
They have decided to modularize clients-10.2.jar.
Which module-info. Java file would work for the new library version clients-10.3 jar?

module com.company.clients{
exports com.company.clients;
}
module com.company.clients{
exports com.company.clients.Cli
ent;
}

module com.company.clients{
requires com.company.clients;
}

module com.company.clients{
uses com.company.clients;
}
Given :
public class Test {
private int sum;

public int compute() {


int x = 0;
while (x < 3) {
sum += x++;
}
return sum;
}

public static void main(String[] args) {


Test t = new Test();
int sum = t.compute();
t.compute();
System.out.println(sum);
}
}

9
An exception to be thrown at runt
ime
6
3

What is the result ?


class Foo {
public void foo(Collection arg) {
System.out.println("Bonjour le monde!");
}
}
class Bar extends Foo {
public void foo(Collection arg) {
System.out.println("Hello World");
}
public void foo(List arg) {
System.out.println("Ola Mundo!");
}
}
public class Test {
public static void main(String[] args) {
Foo f1 = new Foo();
Foo f2 = new Bar();
Bar b1 = new Bar();
List<String> c =new ArrayList<>();
f1.foo(c);
f2.foo(c);
b1.foo(c);
}
}

f2.foo(c) prints Olá Mundo!


f2.foo(c) prints Hello world!
b1.foo(c) prints Hello world!
f1.foo(c) prints Bonjour le mon
de!
f1.foo(c) prints Olá Mundo!

Given:
public class Person {
private String name;
public void setName(String name) {
String title = "Dr. ";
name = title+name;
}
public String toString () {
return name;
}
}

and

public class Test {


public static void main (String args [] ) {
Person p = new Person () ;
p.setName ("Who") ;
System.out.printIn (p) ;
}
}

What is the result?

An exception is thrown at runti


me.
null
Dr. Who
Dr. Null

Given :
Automobile.java
public abstract class Automobile { //line 1
abstract void wheels ();
}

Car.iava
public class Car extends Automobile {
/ / line 2
// line 3
void wheels (int i) {
System.out.print (4);
}
public static void main (String[] args) {
Automobile ob = new Car (); // line
ob.wheels () ;
}
}

What must you do so that the code prints 4?

Remove abstract keyword in line 1.


. Add @Override annotation in line
2
Add @Override annotation in line 2
Add public before wheel method of
Car
Remove the int I argument

Given :
Locale l = new Locale("en", "US");
LocalDate today = LocalDate.of(2018, 12, 17);
String mDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM));
System.out.println(mDate);
String sDate = today.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.SHORT));
System.out.println(sDate);

What is the result?

December 17, 2018


12/17/18

Friday, December 17, 2


018
December 17, 2018
12/17/18
Dec 17, 2018
Dec 17, 2018
12/17/18
What makes Java dynamic?

The runtime can process machine language sources as well as executables from di
fferent
language compilers
At runtime, classes are loaded as needed, and new code modules can be loaded o
n demand.
The runtime can process machine language sources as well as executables from di
fferent
language compilers
The Java compiler preprocesses classes to run on specific target platforms.

Given :

List<String> list = ... ;


list.forEach ( x -> ( System.out.printin (x); } ):

What is the type of x?

String
List<Characte
r>
char
List<String>

public class DogClass {


public static void main(String[] args) {
String s = "";
switch(s) {
case "41": s += "41";
default: s += "def ";
case "42": s+="42";
}
System.out.println(s);
}
}
What is the output?

41 def 42
def 42
An exception is thrown at runti
me.
null

var i = 1;
var result = IntStream.generate (() -> { return i; })
.limit (100). sum();
System.out.println(result);
Which statement prints the same value of result?

System.out.println(IntStream.rangeClosed (0, 100).map(x -> x).c


ount());
System.out.println(IntStream.range (1, 100).count());
System.out.println(IntStream.range (0, 99).count());
System.out.println(IntStream.rangeClosed (1, 100).count());

You might also like