The following are not 1z0-819 dumps but are sample questions extracted from Enthuware OCP Java 11 Exam Simulator, which contains more than 1000 practice questions with detailed explanations packaged in 20 practice tests. Stay away from sites offering Java certification dumps because they are highly unreliable.
Which of the given options if put at //1 will correctly instantiate objects of various classes defined in the following code?
public class TestClass
{
public class A{
}
public static class B {
}
public static void main(String args[]){
class C{
}
//1
}
}
Click to see discussion about this Question!
class A is not static inner class of TestClass. So it cannot exist without an outer instance of TestClass. So, option 1 is the right way to instantiate it.
class B is static inner class and can be instantiated like this: new TestClass.B(). But new TestClass().new B() is not correct.
Although not related to this question, unlike popular belief, anonymous class can never be static. Even if created in a static method.
What will the following code print when compiled and run?
public class TestClass{
public static int operate(IntUnaryOperator iuo){
return iuo.applyAsInt(5);
}
public static void main(String[] args) {
IntFunction<IntUnaryOperator> fo = a->b->a-b; //1
var x = operate(fo.apply(20)); //2
System.out.println(x);
}
}
Click to see discussion about this Question!
The lambda expression a->b->a-b looks complicated but it is actually simple if you group it like this:
a->(b->a-b);
1. IntFunction is a functional interface that takes an int and returns whatever it is typed to. Here, the IntFunction is typed to IntUnaryOperator. Therefore, IntFunction<IntUnaryOperator> will take in an int and return IntUnaryOperator.
The general form of a lambda expression that captures IntFunction would be x->line of code that returns the correct return type i.e. IntUnaryOperator, in this case; where x is an int.
Now, if you look at fo = a->b->a-b;, a is the argument variable of type int (because it is being used to capture IntFunction) and b->a-b forms the method body of the IntFunction. b->a-b must somehow return an IntUnaryOperator for fo = a->b->a-b; to work.
2. IntUnaryOperator is a functional interface that takes in an int and returns another int. It cannot be typed to anything else because both the input and the output are already defined to be int.
The general form of a lambda expression that captures IntUnaryOperator would be y->line of code that returns an int; where y is an int.
Now, in the case of b->a-b; you can see that b is the argument variable and a-b is the method body. For a-b to capture IntUnaryOperator, a must already be defined and it must be an int. Only then will a-b return an int (which is required to capture IntUnaryOperator). That is indeed the case because a is already defined as the argument variable of the encompassing lambda expression and is available for use within the method body of that expression.
3. So basically, when you call fo.apply(20), you are setting a to 20. Therefore, fo.apply(20) returns an IntUnaryFunction that returns 20-b, where b is the argument passed to the IntUnaryFunction. When you call iuo.applyAsInt(5); b is being set to 5. Therefore iuo.applyAsInt(5) will return 20-5 i.e. 15.
Given:
public class Student {
public static enum Grade{ A, B , C, D, F}
private String name;
private Grade grade;
public Student(String name, Grade grade){
this.name = name;
this.grade = grade;
}
public String toString(){
return name+":"+grade;
}
//getters and setters not shown
}
What can be inserted in the code below so that it will print:
{C=[S3], A=[S1, S2]}
List<Student> ls = Arrays.asList(new Student("S1", Student.Grade.A), new Student("S2", Student.Grade.A), new Student("S3", Student.Grade.C));
//INSERT CODE HERE
System.out.println(grouping);
Click to see discussion about this Question!
The developer of a method that accesses the file system wants to ensure that the caller has appropriate permissions. She has written the following code:
public class FileOps {
public static void doOps() {
return AccessController.doPrivileged(
new PrivilegedAction<String>() {
public String run() {
//do File operations here
}
}, AccessController.getContext()
);
}
}
What, if anything, is wrong with this code from a security perspective?
Click to see discussion about this Question!
What will the following code print if file test1.txt exists but test2.txt doesn't exist?
public class FileCopier {
public static void copy1(Path p1, Path p2) throws Exception {
Files.copy(p1, p2, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING);
}
public static void main(String[] args) throws Exception {
var p1 = Paths.get("c:\\temp\\test1.txt");
var p2 = Paths.get("c:\\temp\\test2.txt");
copy1(p1, p2);
if(Files.isSameFile(p1, p2)){
System.out.println("file copied");
}else{
System.out.println("unable to copy file");
}
}
}
Click to see discussion about this Question!
Files.copy method will copy the file test1.txt into test2.txt. If test2.txt doesn't exist, it will be created. However, Files.isSameFile method doesn't check the contents of the file. It is meant to check if the two path objects resolve to the same file or not. In this case, they are not, and so, it will return false.
The following is a brief JavaDoc description for both the methods:
public static Path copy(Path source, Path target, CopyOption... options)
throws IOException
Copy a file to a target file.
This method copies a file to the target file with the options parameter specifying how the copy is performed. By default, the copy fails if the target file already exists or is a symbolic link, except if the source and target are the same file, in which case the method completes without copying the file. File attributes are not required to be copied to the target file. If symbolic links are supported, and the file is a symbolic link, then the final target of the link is copied. If the file is a directory then it creates an empty directory in the target location (entries in the directory are not copied).
The options parameter may include any of the following:
REPLACE_EXISTING If the target file exists, then the target file is replaced if it is not a non-empty directory. If the target file exists and is a symbolic link, then the symbolic link itself, not the target of the link, is replaced.
COPY_ATTRIBUTES Attempts to copy the file attributes associated with this file to the target file. The exact file attributes that are copied is platform and file system dependent and therefore unspecified. Minimally, the last-modified-time is copied to the target file if supported by both the source and target file store. Copying of file timestamps may result in precision loss.
NOFOLLOW_LINKS Symbolic links are not followed. If the file is a symbolic link, then the symbolic link itself, not the target of the link, is copied. It is implementation specific if file attributes can be copied to the new link. In other words, the COPY_ATTRIBUTES option may be ignored when copying a symbolic link.
An implementation of this interface may support additional implementation specific options.
Copying a file is not an atomic operation. If an IOException is thrown then it possible that the target file is incomplete or some of its file attributes have not been copied from the source file. When the REPLACE_EXISTING option is specified and the target file exists, then the target file is replaced. The check for the existence of the file and the creation of the new file may not be atomic with respect to other file system activities.
public static boolean isSameFile(Path path, Path path2)
throws IOException
Tests if two paths locate the same file.
If both Path objects are equal then this method returns true without checking if the file exists. If the two Path objects are associated with different providers then this method returns false. Otherwise, this method checks if both Path objects locate the same file, and depending on the implementation, may require to open or access both files.
Which of the following lines will cause the compilation to fail??
public enum EnumA{ A, AA, AAA}; //1
public class TestClass //2
{
public enum EnumB{ B, BB, BBB }; //3
public static enum EnumC{ C, CC, CCC }; //4
public TestClass()
{
enum EnumD{ D, DD, DDD } //5
}
public void methodX()
{
public enum EnumE{ E, EE, EEE } //6
}
public static void main(String[] args) //7
{
enum EnumF{ F, FF, FFF}; //8
}
}
Click to see discussion about this Question!
Given:
var qr = "insert into USERINFO values( ?, ?, ?)";
try(PreparedStatement ps = c.prepareStatement(qr);)
{
ps.setObject(1, 1, JDBCType.INTEGER);
ps.setObject(2, "Ally A", JDBCType.VARCHAR);
ps.setObject(3, "101 main str", JDBCType.VARCHAR);
var i = ps.executeUpdate(); //1
ps.setObject(1, 2, JDBCType.INTEGER);
ps.setObject(2, "Bob B", JDBCType.VARCHAR);
i = ps.executeUpdate(); //2
}
What will be the result?
Click to see discussion about this Question!
This question is based on the fact that a PreparedStatement remembers the values that you set for every parameter until you close that PreparedStatement object (by calling close() on it). So, if you execute the same query multiple times with same values for some columns, you don't need to set the values for those columns again and again. Setting them once is fine. You need to set values for only those columns that require a change.
Given the following module-info:
module book{
requires org.pdf;
uses org.pdf.Print;
}
Which of the following statements are correct?
Click to see discussion about this Question!
Consider the classes shown below:
class A{ public A() { } public A(int i) { System.out.println(i ); } } class B{ static A s1 = new A(1); A a = new A(2); public static void main(String[] args){ var b = new B(); var a = new A(3); } static A s2 = new A(4); }Which is the correct sequence of the digits that will be printed when B is run? Select 1 best option:
Click to see discussion about this Question!
1. All static constants, variables, and blocks. Among themselves the order is the order in which they appear in the code. This step is actually a part of "class initialization" rather than "instance initialization". Class initialization happens only if the class is being used for the first time while being instantiated. For example, if you have invoked a static method of a class or accessed a static field of that class earlier in the code, you have already used the class and the JVM would have performed initialization of this class at that time. Thus, there wouldn't be any need to initialize the class if you instantiate an object of this class now.
Further, if the class has a superclass, then the JVM performs this step for the superclass first (if the superclass hasn't been initialized already) and only after the superclass is initialized and static blocks are executed, does the JVM proceed with this class. This process is followed recursively up to the java.lang.Object class.
2. All non static constants, variables, and blocks. Among themselves the order is the order in which they appear in the code.
3. Constructor.
Just like the class initialization, instance initialization also happens for the superclass first. That is, if the class has a superclass, then the JVM takes steps 2 and 3 given above for the superclass first and only after the superclass's instance members are initialized, does the JVM proceed with this class. This process is also followed recursively up to the java.lang.Object class.
Given the following class:
class Person{
private String name;
private java.time.LocalDate dob;
public Person(String name, java.time.LocalDate dob){
this.name = name;
this.dob = dob;
}
//public getters and setters for name and dob
}
and the following method appearing in some other class:
public List<Person> getEligiblePersons(List<Person> people){
var pl = new ArrayList<Person>();
for(var p : people){
if(p.getDob().isBefore(cutoff)){
pl.add(p);
}
}
return pl;
}
Click to see discussion about this Question!
Given :
//1
public class TestClass {
//2
public static void main(String[] args) throws Exception{
var al = new ArrayList<Integer>();
printElements(al);
}
//3
static void printElements(List<Integer>... la) {
for(List<Integer> l : la){
System.out.println(l);
}
}
}
Which option(s) will get rid of compilation warning(s) for the above code?
Click to see discussion about this Question!
Which of the following statements are correct regarding abstract classes and interfaces?
Select 2 options:Click to see discussion about this Question!
Given:
//assume appropriate imports
public class Calculator{
public static void main(String[] args) {
double principle = 100;
int interestrate = 5;
double amount = compute(principle, x->x*interestrate);
}
INSERT CODE HERE
}
Which of the following methods can be inserted in the above code so that it will compile and run without any error/exception?
Click to see discussion about this Question!
The lambda expression x->x*interestrate basically takes an input value, modifies it, and return the new value. It is, therefore, acting as a Function.
Therefore, you need a method named compute that takes two arguments - an double value and a Function instance. Option 1 and 4 provide just such a method.
Consider the following code:
class Account{
private String id; private double balance;
ReentrantLock lock = new ReentrantLock();
public void withdraw(double amt){
try{
lock.lock();
if(balance > amt) balance = balance - amt;
}finally{
lock.unlock();
}
}
}
What can be done to make the above code thread safe?
Click to see discussion about this Question!
Your 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:Click to see discussion about this Question!
Please go through the documentation for jdeps given here: https://docs.oracle.com/en/java/javase/11/tools/jdeps.html
jdeps can analyze one or multiple class file(s) or jar file(s). If a given target file depends on a module, then that module must be specified on --module-path (or -p). If the given target file depends on a non-modular jar file (or a class ), then that jar (or class) must be specified on -classpath (or --class-path or -cp).
Consider the following piece of code:
Locale.setDefault(new Locale("fr", "CA")); //Set default to French Canada
Locale l = new Locale("jp", "JP");
ResourceBundle rb = ResourceBundle.getBundle("appmessages", l);
String msg = rb.getString("greetings");
System.out.println(msg);
You have created two resource bundle files with the following contents:
#In appmessages.properties:
greetings=Hello
#In appmessages_fr_FR.properties:
greetings=bonjour
Given that this code is run on machines all over the world. Which of the following statements are correct?
Click to see discussion about this Question!
While retrieving a message bundle, you are passing a locale explicitly (jp/JP). Therefore, it will first try to load appmessages_jp_JP.properties. Since this file is not present, it will look for a resource bundle for default locale. Since you are changing the default locale to "fr", "CA", it will look for appmessages_fr_CA.properties, which is also not present.
Remember that when a resource bundle is not found for a given locale, the default locale is used to load the resource bundle. Every effort is made to load a resource bundle if one is not found and there are several fall back options (in absence of appmessages_fr_CA.properties, it will look for appmessages_fr.properties). As a last resort, it will try to load a resource bundle with no locale information i.e. appmessages.properties in this case. (An exception is thrown when even this resource bundle is not found.)
Since appmessages.properties is available, the code will never throw an exception in any locale.
You need to understand this aspect for the purpose of the exam. Please go through http://docs.oracle.com/javase/7/docs/api/java/util/ResourceBundle.html#getBundle(java.lang.String,%20java.util.Locale,%20java.lang.ClassLoader) for further details.