Java Oca Test 1 Neticeler
Java Oca Test 1 Neticeler
Java Oca Test 1 Neticeler
Doğru
____________ uses access modifiers to protect variables and hide them within a class.
Inheritances
Abstraction
Encapsulation
(Doğru)
Polymorphism
Açıklama
Encapsulation is all about having private instance variable and providing public getter
and setter methods.
Soru 2: Yanlış
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. int [] arr = {2, 1, 0};
6. for(int i : arr) {
7. System.out.println(arr[i]);
8. }
9. }
10. }
0
1
2
(Doğru)
2
1
0
(Yanlış)
Compilation error
ArrayIndexOutOfBoundsException is thrown at runtime
Açıklama
Inside enhanced for loop, System.out.println(arr[i]); is used instead of
System.out.println(i);
When loop executes 1st time, i stores the first array element, which is 2 but
System.out.println statement prints arr[2] which is 0. Loop executes in this manner and
prints 0 1 2 on to the console.
Soru 3: Doğru
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.util.ArrayList;
5. import java.util.List;
6.
7. public class Test {
8. public static void main(String[] args) {
9. String s = new String("Hello");
10. List<String> list = new ArrayList<>();
11. list.add(s);
12. list.add(new String("Hello"));
13. list.add(s);
14. s.replace("l", "L");
15.
16. System.out.println(list);
17. }
18. }
[HeLLo, Hello, HeLLo]
[HeLLo, HeLLo, HeLLo]
[HeLLo, Hello, Hello]
Açıklama
ArrayList's 1st and 3rd items are referring to same String instance referred by s [s -->
"Hello"] and 2nd item is referring to another instance of String.
String is immutable, which means s.replace("l", "L"); creates another String instance
"HeLLo" but s still refers to "Hello" [s --> "Hello"].
[Hello, Hello, Hello] is printed in the output.
Soru 4: Yanlış
For the class Test, which options, if used to replace /*INSERT*/, will print "Lucky no. 7"
on to the console? Select 3 options.
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. /*INSERT*/
6. switch(var) {
7. case 7:
8. System.out.println("Lucky no. 7");
9. break;
10. default:
11. System.out.println("DEFAULT");
12. }
13. }
14. }
char var = '7';
(Yanlış)
Integer var = 7;
(Doğru)
Character var = '7';
(Yanlış)
Character var = 7;
(Doğru)
char var = 7;
(Doğru)
Açıklama
switch can accept primitive types: byte, short, int, char; wrapper types: Byte, Short,
Integer, Character; String and enums.
In this case, all are valid values but only 3 executes "case 7:". case is comparing integer
value 7.
NOTE: character seven, '7' is different from integer value seven, 7. So "char var = '7';"
and "Character var = '7';" will print DEFAULT on to the console.
Soru 5: Doğru
What will be the result of compiling and executing the Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. int grade = 60;
6. if(grade = 60)
7. System.out.println("You passed...");
8. else
9. System.out.println("You failed...");
10. }
11. }
You passed…
Produces no output
Compilation error
(Doğru)
You failed…
Açıklama
Following are allowed in boolean expression of if statement:
1. Any expression whose result is either true or false. e.g. age > 20
boolean expression in this case is: (grade = 60), which is an int assignment and not
boolean assignment. Hence Compilation error.
Soru 6: Doğru
Which of the following statement is correct about below code?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. do {
6. System.out.println(100);
7. } while (false);
8. System.out.println("Bye");
9. }
10. }
Unreachable code compilation error
100
Bye
(Doğru)
Compiles successfully and prints 100 in infinite loop
Compiles successfully and prints "Bye"
Açıklama
As do-while loop executes at least once, hence none of the code is unreachable in this
case.
Java runtime prints 100 to the console, then it checks boolean expression, which is false.
Hence control goes out of do-while block. Java runtime executes 2nd System.out.println
statement to print "Bye" on to the console.
Soru 7: Yanlış
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. m1(); //Line 3
6. }
7.
8. private static void m1() throws Exception { //Line 6
9. System.out.println("NOT THROWING ANY EXCEPTION"); //Line 7
10. }
11. }
NOT THROWING ANY EXCEPTION
(Yanlış)
Compilation error at Line 6
Compilation error at Line 3
(Doğru)
Compilation error at Line 7
Açıklama
If a method declares to throw Exception or its sub-type other than RuntimeException
types, then calling method should follow handle or declare rule. In this case, as method
m1() declares to throw Exception, so main method should either declare the same
exception or its super type in its throws clause OR m1(); should be surrounded by try-
catch block.
Soru 8: Yanlış
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String [] args) {
5. int a = 100;
6. System.out.println(-a++);
7. }
8. }
-99
-100
(Doğru)
-101
99
Compilation error
(Yanlış)
Açıklama
First add parenthesis (round brackets) to the given expression: -a++.
There are 2 operators involved. unary minus and Postfix operator. Let's start with
expression and value of a.
-a++; [a = 100].
-(a++); [a = 100] Postfix operator has got higher precedence than unary operator.
-(100); [a = 101] Use the value of a (100) in the expression and after that increase the
value of a to 101.
Soru 9: Atlandı
Fill in the blanks for the definition of java.lang.Error class:
RuntimeException
Exception
Throwable
(Doğru)
Açıklama
An Error is a subclass of Throwable class.
Soru 10: Atlandı
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.time.LocalDate;
5. import java.time.LocalTime;
6.
7. public class Test {
8. public static void main(String [] args) {
9. LocalDate date = LocalDate.parse("1947-08-14");
10. LocalTime time = LocalTime.MAX;
11. System.out.println(date.atTime(time));
12. }
13. }
1947-08-14T23:59:59
1947-08-14T23:59:59.0
1947-08-14T23:59:59.999
Açıklama
LocalTime.MIN --> {00:00}, LocalTime.MAX --> {23:59:59.999999999},
LocalTime.MIDNIGHT --> {00:00}, LocalTime.NOON --> {12:00}.
toString() method of LocalDateTime class prints the date and time parts separated by T
in upper case.
Soru 11: Doğru
Given code:
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. /*INSERT*/
6. arr[1] = 5;
7. arr[2] = 10;
8. System.out.println("[" + arr[1] + ", " + arr[2] + "]"); //Line n1
9. }
10. }
How many above statements can be used to replace /*INSERT*/, such that on execution,
code will print [5, 10] on to the console?
Only two options
Only three options
(Doğru)
More than four options
None of the given options
Only four options
Only one option
Açıklama
Let's check all the statements one by one:
You can declare one-dimensional array by using either "short arr []" or "short [] arr". 'arr'
refers to a short array object of 2 elements. arr[2] will throw
ArrayIndexOutOfBoundsException at runtime.
You can create an array object in the same statement or next statement. 'arr' refers to a
short array object of 3 elements, where 0 is assigned to each array element. Later on
element at 1st and 2nd indexes have been re-initialized. Line n1 successfully prints [5,
10] on to the console.
Array size cannot be specified at the time of declaration, so short [2] arr; causes
compilation error.
Array size cannot be specified at the time of declaration, so short [3] arr; causes
compilation error.
'arr' refers to an int array object of size 2 and both array elements have value 100. arr[2]
will throw ArrayIndexOutOfBoundsException at runtime.
'arr' refers to an int array object of size 4 and all array elements have value 0. Later on
element at 1st and 2nd indexes have been re-initialized. Line n1 successfully prints [5,
10] on to the console.
Array's size can't be specified, if you use {} to assign values to array elements.
Hence, out of the given 9 statements, only 3 will print [5, 10] on to the console.
Soru 12: Yanlış
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.util.ArrayList;
5. import java.util.List;
6.
7. class Student {
8. private String name;
9. private int age;
10.
11. Student(String name, int age) {
12. this.name = name;
13. this.age = age;
14. }
15.
16. public String toString() {
17. return "Student[" + name + ", " + age + "]";
18. }
19. }
20.
21. public class Test {
22. public static void main(String[] args) {
23. List<Student> students = new ArrayList<>();
24. students.add(new Student("James", 25));
25. students.add(new Student("James", 27));
26. students.add(new Student("James", 25));
27. students.add(new Student("James", 25));
28.
29. students.remove(new Student("James", 25));
30.
31. for(Student stud : students) {
32. System.out.println(stud);
33. }
34. }
35. }
Student[James, 27]
Student[James, 25]
Student[James, 25]
Student[James, 25]
Student[James, 27]
Student[James, 25]
Student[James, 25]
Student[James, 27]
Student[James, 25]
Student[James, 25]
(Doğru)
Açıklama
Before you answer this, you must know that there are 5 different Student object created
in the memory (4 at the time of adding to the list and 1 at the time of removing from
the list). This means these 5 Student objects will be stored at different memory
addresses.
Nothing is removed from the students list, all the 4 Student objects are printed in the
insertion order.
Soru 13: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. double [] arr = new int[2]; //Line 3
6. System.out.println(arr[0]); //Line 4
7. }
8. }
0
0.0
Line 3 causes compilation error
(Doğru)
Line 4 causes runtime exception
Açıklama
int variable can easily be assigned to double type but double [] and int [] are not
compatible. In fact, both are siblings and can't be assigned to each other, so Line 3
causes compilation failure.
Soru 14: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. double price = 90000;
6. String model;
7. if(price > 100000) {
8. model = "Tesla Model X";
9. } else if(price <= 100000) {
10. model = "Tesla Model S";
11. }
12. System.out.println(model);
13. }
14. }
Tesla Model S
Compilation Error
(Doğru)
Tesla Model X
null
Açıklama
In this case "if - else if" block is used and not "if - else" block.
90000 is assigned to variable 'price' but you can assign parameter value or call some
method returning double value, such as:
'double price = currentTemp();'.
In these cases compiler will not know the exact value until runtime, hence Java Compiler
is not sure which boolean expression will be evaluated to true and so variable model
may not be initialized.
Usage of LOCAL variable, 'model' without initialization gives compilation error. Hence,
System.out.println(model); gives compilation error.
Soru 15: Doğru
Consider below code fragment:
1. interface Printable {
2. public void setMargin();
3. public void setOrientation();
4. }
5.
6. abstract class Paper implements Printable { //Line 7
7. public void setMargin() {}
8. //Line 9
9. }
10.
11. class NewsPaper extends Paper { //Line 12
12. public void setMargin() {}
13. //Line 14
14. }
Replace the code at Line 12 with: abstract class NewsPaper extends Paper {
(Doğru)
Insert at Line 9: public abstract void setOrientation();
Insert at Line 14: public void setOrientation() {}
(Doğru)
Açıklama
First you should find out the reason for compilation error. Methods declared in Printable
interface are implicitly abstract, no issues with Printable interface.
class Paper is declared abstract and it implements Printable interface, it overrides
setMargin() method but setOrientation() method is still abstract. No issues with class
Paper as it is an abstract class and can have 0 or more abstract methods.
class NewsPaper is concrete class and it extends Paper class (which is abstract). So class
NewsPaper must override setOrientation() method OR it must be declared abstract.
Replacing Line 9 with 'public abstract void setOrientation();' is not necessary and it will
not resolve the compilation error in NewsPaper class.
Replacing Line 7 with 'class Paper implements Printable {' will cause compilation failure
of Paper class as it inherits abstract method 'setOrientation'.
Soru 16: Yanlış
Consider code of Test.java file:
1. package com.udayan.oca;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5.
6. public class Test {
7. public static void main(String[] args) {
8. List<Character> list = new ArrayList<>();
9. list.add(0, 'V');
10. list.add('T');
11. list.add(1, 'E');
12. list.add(3, 'O');
13.
14. if(list.contains('O')) {
15. list.remove('O');
16. }
17.
18. for(char ch : list) {
19. System.out.print(ch);
20. }
21. }
22. }
Runtime exception
(Doğru)
VETO
VTEO
VET
VTE
Açıklama
list.add(0, 'V'); => char 'V' is converted to Character object and stored as the first
element in the list. list --> [V].
list.add('T'); => char 'T' is auto-boxed to Character object and stored at the end of the
list. list --> [V,T].
list.add(1, 'E'); => char 'E' is auto-boxed to Character object and inserted at index 1 of
the list, this shifts T to the right. list --> [V,E,T].
list.add(3, 'O'); => char 'O' is auto-boxed to Character object and added at index 3 of
the list. list --> [V,E,T,O].
list.contains('O') => char 'O' is auto-boxed to Character object and as Character class
overrides equals(String) method this expression returns true. Control goes inside if-
block and executes: list.remove('O');.
list.remove('O') throws runtime exception, as it tries to remove an item from the index
greater than 65 but allowed index is 0 to 3 only.
Soru 17: Yanlış
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. class SpecialString {
5. String str;
6. SpecialString(String str) {
7. this.str = str;
8. }
9. }
10.
11. public class Test {
12. public static void main(String[] args) {
13. Object [] arr = new Object[4];
14. for(int i = 1; i <=3; i++) {
15. switch(i) {
16. case 1:
17. arr[i] = new String("Java");
18. break;
19. case 2:
20. arr[i] = new StringBuilder("Java");
21. break;
22. case 3:
23. arr[i] = new SpecialString("Java");
24. break;
25. }
26. }
27. for(Object obj : arr) {
28. System.out.println(obj);
29. }
30. }
31. }
null
Java
Java
Java
Java
Java
<Some text containing @ symbol>
null
(Yanlış)
Java
Java
Java
Java
Java
<Some text containing @ symbol>
Java
<Some text containing @ symbol>
<Some text containing @ symbol>
null
Java
<Some text containing @ symbol>
<Some text containing @ symbol>
null
Java
Java
<Some text containing @ symbol>
(Doğru)
Java
<Some text containing @ symbol>
<Some text containing @ symbol>
null
Java
Java
Java
null
Açıklama
Variable 'arr' refers to an Object array of size 4 and null is assigned to all 4 elements of
this array.
for-loop starts with i = 1, which means at 1st index String instance is stored, at 2nd
index StringBuiler instance is stored and at 3rd index SpecialString instance is stored.
null is stored at 0th index.
String and StringBuilder classes override toString() method, which prints the text stored
in these classes. SpecialString class doesn't override toString() method and hence when
instance of SpecialString is printed on to the console, you get: <fully qualified name of
SpecialString class>@<hexadecimal representation of hashcode>.
null
Java
Java
Soru 18: Doğru
Which of the following is not a valid array declaration?
int [][] arr2 = new int[8][8];
int arr4[][] = new int[][8];
(Doğru)
int [] arr3 [] = new int[8][];
int [] arr1 = new int[8];
Açıklama
1st array dimension must be specified at the time of declaration. new int[][8]; gives
compilation error as 1st dimension is not specified.
Soru 19: Doğru
Consider below code:
1. //Guest.java
2. class Message {
3. static void main(String [] args) {
4. System.out.println("Welcome " + args[2] + "!");
5. }
6. }
7.
8. public class Guest {
9. public static void main(String [] args) {
10. Message.main(args);
11. }
12. }
ArrayIndexOutOfBoundsException is thrown at runtime
Some other error as main method can't be invoked manually
Welcome Keller!
(Doğru)
Compilation error as main method is not public in Message class
Welcome Clare!
Welcome Waight!
Açıklama
Class Guest has special main method but main method defined in Message class is not
public and hence it can't be called by JVM. But there is no issue with the syntax hence
no compilation error.
java Guest Clare Waight Keller passes new String [] {"Clare", "Waight", "Keller"} to args
of Guest.main method.
Guest.main method invokes Message.main method with the same argument: new String
[] {"Clare", "Waight", "Keller"}. args[2] is "Keller" hence "Welcome Keller!" gets printed on
to the console.
Soru 20: Yanlış
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. Double [] arr = new Double[2];
6. System.out.println(arr[0] + arr[1]);
7. }
8. }
ClassCastException is thrown at runtime
Compilation error
NullPointerException is thrown at runtime
(Doğru)
0.0
(Yanlış)
Açıklama
Array elements are initialized to their default values. arr is referring to an array of Double
type, which is reference type and hence both the array elements are initialized to null.
Soru 21: Yanlış
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. String str = "java";
6. StringBuilder sb = new StringBuilder("java");
7.
8. System.out.println(str.equals(sb) + ":" + sb.equals(str));
9. }
10. }
false:false
(Doğru)
true:false
false:true
Compilation error
(Yanlış)
true:true
Açıklama
equals method declared in Object class has the declaration: public boolean
equals(Object). Generally, equals method is used to compare different instances of same
class but if you pass any other object, there is no compilation error. Parameter type is
Object so it can accept any Java object.
Soru 22: Yanlış
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. try {
6. main(args);
7. } catch (Exception ex) {
8. System.out.println("CATCH-");
9. }
10. System.out.println("OUT");
11. }
12. }
Compilation error
None of the System.out.println statements are executed
(Doğru)
OUT
CATCH-OUT
(Yanlış)
Açıklama
main(args) method is invoked recursively without specifying any exit condition, so this
code ultimately throws java.lang.StackOverflowError. StackOverflowError is a subclass of
Error type and not Exception type, hence it is not handled. Stack trace is printed to the
console and program ends abruptly.
Java doesn't allow to catch specific checked exceptions if these are not thrown by the
statements inside try block.
A
ab
Aa
aba
Abab
(Doğru)
Compilation error
Runtime exception
A
Aa
Abab
ab
aba
Açıklama
Let us suppose test string is "aba".
Soru 24: Atlandı
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.time.LocalDate;
5.
6. public class Test {
7. public static void main(String [] args) {
8. LocalDate newYear = LocalDate.of(2018, 1, 1);
9. LocalDate christmas = LocalDate.of(2018, 12, 25);
10. boolean flag1 = newYear.isAfter(christmas);
11. boolean flag2 = newYear.isBefore(christmas);
12. System.out.println(flag1 + ":" + flag2);
13. }
14. }
true:false
An exception is thrown at runtime
false:true
(Doğru)
Açıklama
isAfter and isBefore method can be interpreted as:
Does 1st Jan 2018 come after 25th Dec 2018? No, false.
Does 1st Jan 2018 come before 25th Dec 2018? Yes, true.
Soru 25: Doğru
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. public class Test {
5. public static void main(String[] args) {
6. StringBuilder sb = new StringBuilder(100);
7. System.out.println(sb.length() + ":" + sb.toString().length());
8. }
9. }
What will be the result of compiling and executing Test class?
100:100
100:0
16:16
16:0
0:0
(Doğru)
Açıklama
`new StringBuilder(100);` creates a StringBuilder instance, whose internal char array's
length is 100 but length() method of StringBuilder object returns the number of
characters stored in the internal array and in this case it is 0. So, `sb.length()` returns 0.
Output is 0:0.
Soru 26: Doğru
Consider the code of Test.java file:
1. package com.udayan.oca;
2.
3. class Student {
4. String name;
5. int age;
6.
7. void Student() {
8. Student("James", 25);
9. }
10.
11. void Student(String name, int age) {
12. this.name = name;
13. this.age = age;
14. }
15. }
16.
17. public class Test {
18. public static void main(String[] args) {
19. Student s = new Student();
20. System.out.println(s.name + ":" + s.age);
21. }
22. }
James:25
Compilation error
null:0
(Doğru)
Açıklama
Methods can have same name as the class. Student() and Student(String, int) are
methods and not constructors of the class, note the void return type of these methods.
As no constructors are provided in the Student class, java compiler adds default no-arg
constructor. That is why the statement Student s = new Student(); doesn't give any
compilation error.
Default values are assigned to instance variables, hence null is assigned to name and 0 is
assigned to age.
Soru 27: Doğru
For the given code snippet:
Select 2 options.
ArrayList<>
(Doğru)
List<String>
List<>
ArrayList<String>
(Doğru)
Açıklama
List is an interface so its instance can't be created using new keyword. List<String> and
List<> will cause compilation failure.
Starting with JDK 7, Java allows to not specify type while initializing the ArrayList. Type is
inferred from the left side of the statement.
Soru 28: Yanlış
How many objects of Pen class are eligible for Garbage Collection at Line 4?
1. package com.udayan.oca;
2.
3. class Pen {
4.
5. }
6.
7. public class TestPen {
8. public static void main(String[] args) {
9. new Pen(); //Line 1
10. Pen p = new Pen(); // Line 2
11. change(p); //Line 3
12. System.out.println("About to end."); //Line 4
13. }
14.
15. public static void change(Pen pen) { //Line 5
16. pen = new Pen(); //Line 6
17. }
18. }
2
(Doğru)
1
(Yanlış)
3
0
Açıklama
Object created at Line 1 becomes eligible for Garbage collection after Line 1 only, as
there are no references to it. So We have one object marked for GC.
Object created at Line 6 becomes unreachable after change(Pen) method pops out of
the STACK, and this happens after Line 3.
So at Line 4, we have two Pen objects eligible for Garbage collection: Created at Line 1
and Created at Line 6.
Soru 29: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringBuilder sb = new StringBuilder("Java");
6. String s1 = sb.toString();
7. String s2 = sb.toString();
8.
9. System.out.println(s1 == s2);
10. }
11. }
Compilation error
An exception is thrown at runtime
false
(Doğru)
true
Açıklama
toString() method defined in StringBuilder class doesn't use String literal rather uses the
constructor of String class to create the instance of String class.
So both s1 and s2 refer to different String instances even though their contents are
same. s1 == s2 returns false.
Soru 30: Yanlış
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. char var1;
5. double var2;
6. float var3;
7.
8. public static void main(String[] args) {
9. Test obj = new Test();
10. System.out.println(">" + obj.var1);
11. System.out.println(">" + obj.var2);
12. System.out.println(">" + obj.var3);
13. }
14. }
1. >null
2. >0.0
3. >0.0f
1. >null
2. >0.0
3. >0.0
1. >
2. >0.0
3. >0.0
(Doğru)
1. >
2. >0.0
3. >0.0f
(Yanlış)
Açıklama
Primitive type instance variables are initialized to respective zeros (byte: 0, short: 0, int: 0,
long: 0L, float: 0.0f, double: 0.0, boolean: false, char: \u0000).
When printed on the console; byte, short, int & long prints 0, float & double print 0.0,
boolean prints false and char prints nothing or non-printable character (whitespace).
Soru 31: Doğru
Consider the following class:
1. package com.udayan.oca;
2.
3. public class Employee {
4. public int passportNo; //line 2
5. }
Which of the following is the correct way to make the variable 'passportNo' read only
for any other class?
Make 'passportNo' private.
Make 'passportNo' private and provide a public method getPassportNo() which will return
its value.
(Doğru)
Remove 'public' from the 'passportNo' declaration. i.e., change line 2 to int passportNo;
Make 'passportNo' static and provide a public static method getPassportNo() which will
return its value.
Açıklama
'passportNo' should be read-only for any other class.
This means make 'passportNo' private and provide public getter method. Don't provide
public setter as then 'passportNo' will be read-write property.
If passportNo is declared with default scope, then other classes in the same package will
be able to access passportNo for read-write operation.
Soru 32: Yanlış
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. System.out.println("Output is: " + 10 != 5);
6. }
7. }
Output is: 10 != 5
Output is: false
(Yanlış)
Output is: true
Compilation error
(Doğru)
Açıklama
Binary plus (+) has got higher precedence than != operator. Let us group the
expression.
[!= is binary operator, so we have to evaluate the left side first. + operator behaves as
concatenation operator.]
Left side of above expression is String, and right side is int. But String can't be compared
to int, hence compilation error.
Soru 33: Atlandı
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.util.ArrayList;
5. import java.util.Iterator;
6. import java.util.List;
7. import java.util.function.Predicate;
8.
9. class Employee {
10. private String name;
11. private int age;
12. private double salary;
13.
14. public Employee(String name, int age, double salary) {
15. this.name = name;
16. this.age = age;
17. this.salary = salary;
18. }
19.
20. public String getName() {
21. return name;
22. }
23.
24. public int getAge() {
25. return age;
26. }
27.
28. public double getSalary() {
29. return salary;
30. }
31.
32. public String toString() {
33. return name;
34. }
35. }
36.
37. public class Test {
38. public static void main(String [] args) {
39. List<Employee> list = new ArrayList<>();
40. list.add(new Employee("James", 25, 15000));
41. list.add(new Employee("Lucy", 23, 12000));
42. list.add(new Employee("Bill", 27, 10000));
43. list.add(new Employee("Jack", 19, 5000));
44. list.add(new Employee("Liya", 20, 8000));
45.
46. process(list, /*INSERT*/);
47.
48. System.out.println(list);
49. }
50.
51. private static void process(List<Employee> list, Predicate<Employee> predicate) {
52. Iterator<Employee> iterator = list.iterator();
53. while(iterator.hasNext()) {
54. if(predicate.test(iterator.next()))
55. iterator.remove();
56. }
57. }
58. }
Which of the following lambda expressions, if used to replace /*INSERT*/, prints [Jack,
Liya] on to the console?
Select 2 options.
e - > e.getSalary() >= 10000
e -> e.getSalary() >= 10000
(Doğru)
e -> { e.getSalary() >= 10000 }
(Employee e) -> { return e.getSalary() >= 10000; }
(Doğru)
(e) -> { e.getSalary() >= 10000; }
Açıklama
Jack's salary is 5000 and Liya's salary is 8000. If Employee's salary is >= 10000 then that
Employee object is removed from the list.
Allowed lambda expression is:
Can be simplified to: (e) -> { return e.getSalary() >= 10000; } => type can be removed
from left side of the expression.
Further simplified to: e -> { return e.getSalary() >= 10000; } => if there is only one
parameter in left part, then round brackets (parenthesis) can be removed.
Further simplified to: e -> e.getSalary() >= 10000 => if there is only one statement in
the right side then semicolon inside the body, curly brackets and return statement can
be removed. But all 3 [return, {}, ;] must be removed together.
NOTE: there should not be any space between - and > of arrow operator.
Soru 34: Doğru
35-60
25-25
25-60
(Doğru)
35-25
Açıklama
In below statements: student<main> means student inside main method.
On execution of review method: stud<review> --> {"James", 25} (same object referred
by student<main>), marks<review> = 25 (this marks is different from the marks defined
in main method). marks<review> = 35 and stud.marks = 60. So at the end of review
method: stud<review> --> {"James", 60}, marks<review> = 35.
Control goes back to main method: student<main> --> {"James", 60}, marks<main> =
25. Changes done to reference variable are visible in main method but changes done to
primitive variable are not reflected in main method.
Soru 35: Yanlış
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. public class Test {
5. public static void main(String[] args) {
6. String s1 = "OCAJP";
7. String s2 = "OCAJP" + "";
8. System.out.println(s1 == s2);
9. }
10. }
OCAJP
true
(Doğru)
Compilation error
Açıklama
Please note that Strings computed by concatenation at compile time, will be referred by
String Pool during execution. Compile time String concatenation happens when both of
the operands are compile time constants, such as literal, final variable etc.
For the statement, String s2 = "OCAJP" + ""; , `"OCAJP" + ""` is a constant expression
as both the operands "OCAJP" and "" are String literals, which means the expression
`"OCAJP" + ""` is computed at compile-time and results in String literal "OCAJP".
to
String s2 = "OCAJP";
s1 and s2 both refer to the same String object and that is why s1 == s2 returns true.
Please note that Strings computed by concatenation at run time (if the resultant
expression is not constant expression) are newly created and therefore distinct.
String s1 = "OCAJP";
String s2 = s1 + "";
System.out.println(s1 == s2);
Output is false, as s1 is a variable and `s1 + ""` is not a constant expression, therefore
this expression is computed only at runtime and a new non-pool String object is
created.
Soru 36: Doğru
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.util.ArrayList;
5. import java.util.List;
6.
7. public class Test {
8. public static void main(String[] args) {
9. List<String> list1 = new ArrayList<>();
10. list1.add("A");
11. list1.add("D");
12.
13. List<String> list2 = new ArrayList<>();
14. list2.add("B");
15. list2.add("C");
16.
17. list1.addAll(1, list2);
18.
19. System.out.println(list1);
20. }
21. }
[A, D]
[A, B, C, D]
(Doğru)
[A, B, C]
Açıklama
list1 --> [A, D],
list1.addAll(1, list2); is almost equal to list1.add(1, [B, C]); => Inserts B at index 1, C takes
index 2 and D is moved to index 3. list1 --> [A, B, C, D]
Soru 37: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5.
6. public class Test {
7. public static void main(String[] args) {
8. List<Integer> list = new ArrayList<>();
9. list.add(100);
10. list.add(200);
11. list.add(100);
12. list.add(200);
13. list.remove(100);
14.
15. System.out.println(list);
16. }
17. }
Compilation error
[100, 200, 200]
[200, 100, 200]
[200]
[200, 200]
Exception is thrown at runtime
(Doğru)
Açıklama
List cannot accept primitives, it can accept objects only. So, when 100 and 200 are
added to the list, then auto-boxing feature converts these to wrapper objects of Integer
type.
So, 4 items gets added to the list. One can expect the same behavior with remove
method as well that 100 will be auto-boxed to Integer object.
But remove method is overloaded in List interface: remove(int) => Removes the element
from the specified position in this list
and remove(Object) => Removes the first occurrence of the specified element from the
list.
As remove(int) version is available, which perfectly matches with the call remove(100);
hence compiler does not do auto-boxing in this case.
But at runtime remove(100) tries to remove the element at 100th index and this throws
IndexOutOfBoundsException.
Soru 38: Yanlış
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.util.ArrayList;
5. import java.util.Iterator;
6. import java.util.List;
7.
8. public class Test {
9. public static void main(String[] args) {
10. List<String> dryFruits = new ArrayList<>();
11. dryFruits.add("Walnut");
12. dryFruits.add("Apricot");
13. dryFruits.add("Almond");
14. dryFruits.add("Date");
15.
16. Iterator<String> iterator = dryFruits.iterator();
17. while(iterator.hasNext()) {
18. String dryFruit = iterator.next();
19. if(dryFruit.startsWith("A")) {
20. dryFruits.remove(dryFruit);
21. }
22. }
23.
24. System.out.println(dryFruits);
25. }
26. }
[Walnut, Apricot, Almond, Date]
An exception is thrown at runtime
(Doğru)
[Walnut, Date]
Açıklama
ConcurrentModificationException exception may be thrown for following condition:
And
1st Iteration: cursor = 0, size = 4, hasNext() returns true. iterator.next() increments the
cursor by 1 and returns "Walnut".
2nd Iteration: cursor = 1, size = 4, hasNext() returns true. iterator.next() increments the
cursor by 1 and returns "Apricot". As "Apricot" starts with "A", hence
dryFruits.remove(dryFruit) removes "Apricot" from the list and hence reducing the list's
size by 1, size becomes 3.
3rd Iteration: cursor = 2, size = 3, hasNext() returns true. iterator.next() method throws
java.util.ConcurrentModificationException.
If you want to remove the items from ArrayList, while using Iterator or ListIterator, then
use Iterator.remove() or ListIterator.remove() method and NOT List.remove(...) method.
Using List.remove(...) method while iterating the list (using the Iterator/ListIterator or
for-each) may throw java.util.ConcurrentModificationException.
Soru 39: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5.
6. public class Test {
7. public static void main(String[] args) {
8. String[] names = { "Smith", "Brown", "Thomas", "Taylor", "Jones" };
9. List<String> list = new ArrayList<>();
10. for (int x = 0; x < names.length; x++) {
11. list.add(names[x]);
12. switch (x) {
13. case 2:
14. continue;
15. }
16. break;
17. }
18. System.out.println(list.size());
19. }
20. }
2
None of the other options
1
(Doğru)
0
3
4
5
Açıklama
break; and continue; are used inside for-loop, hence no compilation error.
In 1st iteration, x = 0. "Smith" is added to the list. There is no matching case found,
hence control just goes after the switch-case block and executes break; statement,
which takes the control out of the for loop. `System.out.println(list.size());` is executed
and this prints 1 on to the console.
Soru 40: Atlandı
A bank's swift code is generally of 11 characters and used in international money
transfers.
An example of swift code: ICICINBBRT4
ICIC: First 4 letters for bank code
IN: Next 2 letters for Country code
BB: Next 2 letters for Location code
RT4: Next 3 letters for Branch code
Which of the following code correctly extracts country code from the swift code referred
by String reference variable swiftCode?
swiftCode.substring(4, 6);
(Doğru)
swiftCode.substring(4, 5);
swiftCode.substring(5, 6);
swiftCode.substring(5, 7);
Açıklama
substring(int beginIndex, int endIndex) is used to extract the substring. The substring
begins at "beginIndex" and extends till "endIndex - 1".
Country code information is stored at index 4 and 5, so the correct substring method to
extract country code is: swiftCode.substring(4, 6);
Soru 41: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. class Message {
4. String msg = "Happy New Year!";
5.
6. public void print() {
7. System.out.println(msg);
8. }
9. }
10.
11. public class Test {
12. public static void change(Message m) { //Line n5
13. m = new Message(); //Line n6
14. m.msg = "Happy Holidays!"; //Line n7
15. }
16.
17. public static void main(String[] args) {
18. Message obj = new Message(); //Line n1
19. obj.print(); //Line n2
20. change(obj); //Line n3
21. obj.print(); //Line n4
22. }
23. }
Happy Holidays!
Happy Holidays!
Happy New Year!
Happy New Year!
(Doğru)
Happy New Year!
Happy Holidays!
null
Happy New Year!
Açıklama
It is pass-by-reference scheme.
Call to method change(Message) doesn't modify the msg property of passed object
rather it creates another Message object and modifies the msg property of new object
to "Happy Holidays!"
Soru 42: Doğru
Replace /*INSERT-1*/ with:
this.type = type;
super(capacity);
Replace /*INSERT-2*/ with:
super(128);
None of the other options
Replace /*INSERT-1*/ with:
super(capacity);
this.type = type;
Replace /*INSERT-2*/ with:
super(0);
(Doğru)
Replace /*INSERT-1*/ with:
super(capacity);
Replace /*INSERT-2*/ with:
super(128);
Replace /*INSERT-1*/ with:
super.capacity = capacity;
this.type = type;
Replace /*INSERT-2*/ with:
super(128);
Açıklama
Java compiler adds super(); as the first statement inside constructor, if call to another
constructor using this(...) or super(...) is not available.
Compiler adds super(); as the first line in OTG's constructor: OTG(int capacity, String
type) { super(); } but PenDrive class doesn't have a no-arg constructor and that is why
OTG's constructor causes compilation error.
For the same reason, OTG(String make) constructor also causes compilation error.
To correct these compilation errors, parent class constructor should be invoked by using
super(int); This would resolve compilation error.
Remember: Constructor call using this(...) or super(...) must be the first statement inside
the constructor.
We have to make changes in OTG(int, String) constructor such that on execution, output
is 128:TYPE-C.
super(capacity); will only assign value to capacity property, to assign value to type
another statement is needed.
super(capacity);
this.type = type;
Soru 43: Atlandı
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.time.LocalDateTime;
5.
6. public class Test {
7. public static void main(String [] args) {
8. LocalDateTime obj = LocalDateTime.now();
9. System.out.println(obj.getSecond());
10. }
11. }
It will print any int value between 1 and 60
Code compiles successfully but throws Runtime exception
Code fails to compile
Açıklama
LocalDateTime stores both date and time parts. LocalDateTime.now(); retrieves the
current date and time from the system clock. obj.getSecond() can return any value
between 0 and 59.
Soru 44: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. int x = 1;
6. while(checkAndIncrement(x)) {
7. System.out.println(x);
8. }
9. }
10.
11. private static boolean checkAndIncrement(int x) {
12. if(x < 5) {
13. x++;
14. return true;
15. } else {
16. return false;
17. }
18. }
19. }
Infinite loop
(Doğru)
2
3
4
5
1
2
3
4
5
1
2
3
4
Açıklama
x of checkAndIncrement method contains the copy of variable x defined in main
method. So, changes done to x in checkAndIncrement method are not reflected in the
variable x of main. x of main remains 1 as code inside main is not changing its value.
Soru 45: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. short [] args = new short[]{50, 50};
6. args[0] = 5;
7. args[1] = 10;
8. System.out.println("[" + args[0] + ", " + args[1] + "]");
9. }
10. }
[5, 10]
Compilation error
(Doğru)
An exception is thrown at runtime
[50, 50]
Açıklama
main method's parameter variable name is "args" and it is a local to main method.
So, same name "args" can't be used directly within the curly brackets of main method.
short [] args = new short[]{50, 50}; gives compilation error for using same name for local
variable.
Soru 46: Doğru
Given the code of Test.java file:
1. package com.udayan.oca;
2.
3. class Point {
4. int x;
5. int y;
6. void assign(int x, int y) {
7. x = this.x;
8. this.y = y;
9. }
10.
11. public String toString() {
12. return "Point(" + x + ", " + y + ")";
13. }
14. }
15.
16. public class Test {
17. public static void main(String[] args) {
18. Point p1 = new Point();
19. p1.x = 10;
20. p1.y = 20;
21. Point p2 = new Point();
22. p2.assign(p1.x, p1.y);
23. System.out.println(p1.toString() + ";" + p2.toString());
24. }
25. }
Point(0, 20);Point(0, 20)
Point(10, 20);Point(10, 20)
Point(10, 20);Point(0, 20)
(Doğru)
None of the other options
Açıklama
HINT: First check if members are accessible or not. All the codes are in same file
Test.java, and Point class & variable x, y are declared with default modifier hence these
can be accessed within the same package. Class Test belongs to same package so no
issues in accessing Point class and instance variables of Point class. Make use of pen and
paper to draw the memory diagrams (heap and stack). It will be pretty quick to reach
the result.
Point p1 = new Point(); means p1.x = 0 and p1.y = 0 as instance variable are initialized
to respective zeros.
Point p2 = new Point(); means p2.x = 0 and p2.y = 0 as instance variable are initialized
to respective zeros.
p2.assign(p1.x, p1.y); invokes the assign method, parameter variable x = 10 and y = 20.
As assign is invoked on p2 reference variable hence this and p2 refers to same Point
object.
So after assign method is invoked and control goes back to main method: p1.x = 10,
p1.y = 20, p2.x = 0 and p2.y = 20.
Soru 47: Yanlış
Consider codes below:
1. //A.java
2. package com.udayan.oca;
3.
4. public class A {
5. public void print() {
6. System.out.println("A");
7. }
8. }
1. //B.java
2. package com.udayan.oca;
3.
4. public class B extends A {
5. public void print() {
6. System.out.println("B");
7. }
8. }
1. //Test.java
2. package com.udayan.oca.test;
3.
4. import com.udayan.oca.*;
5.
6. public class Test {
7. public static void main(String[] args) {
8. A obj1 = new A();
9. B obj2 = (B)obj1;
10. obj2.print();
11. }
12. }
Compilation error
(Yanlış)
B
ClassCastException is thrown at runtime
(Doğru)
Açıklama
Class A and B are declared public and inside same package com.udayan.oca. Method
print() of class A has correctly been overridden by B.
B obj2 = (B)obj1; => obj1 is of type A and it is assigned to obj2 (B type), hence explicit
casting is necessary. obj1 refers to an instance of class A, so at runtime obj2 will also
refer to an instance of class A. sub type can't refer to an object of super type so at
runtime B obj2 = (B)obj1; will throw ClassCastException.
Soru 48: Yanlış
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.util.ArrayList;
5.
6. class Counter {
7. int count;
8. Counter(int count) {
9. this.count = count;
10. }
11.
12. public String toString() {
13. return "Counter-" + count;
14. }
15. }
16.
17. public class Test {
18. public static void main(String[] args) {
19. ArrayList<Counter> original = new ArrayList<>();
20. original.add(new Counter(10));
21.
22. ArrayList<Counter> cloned = (ArrayList<Counter>) original.clone();
23. cloned.get(0).count = 5;
24.
25. System.out.println(original);
26. }
27. }
An exception is thrown at runtime
[Counter-5]
(Doğru)
Compilation error
Açıklama
Let's see what is happening during execution:
In this case, original != cloned, but original.get(0) == cloned.get(0). This means both the
array lists are created at different memory location but refer to same Counter object.
Soru 49: Doğru
Which of the following correctly defines class Printer?
1. import java.util.*;
2. package com.udayan.oca;
3. public class Printer {
4.
5. }
1. public class Printer {
2. package com.udayan.oca;
3. }
1. /* Java Developer Comments. */
2. package com.udayan.oca;
3. public class Printer {
4.
5. }
(Doğru)
1. public class Printer {
2.
3. }
4. package com.udayan.oca;
Açıklama
If package is used then it should be the first statement, but javadoc and developer
comments are not considered as java statements so a class can have developer and
javadoc comments before the package statement.
If import and package both are available, then correct order is package, import, class
declaration.
Soru 50: Doğru
Consider below code:
1. public class Test {
2. static {
3. System.out.println(1/0);
4. }
5.
6. public static void main(String[] args) {
7. System.out.println("HELLO");
8. }
9. }
Yes, HELLO is printed on to the console
Açıklama
To invoke the special main method, JVM loads the class in the memory. At that time,
static initializer block is invoked. 1/0 throws a RuntimeException and as a result static
initializer block throws an instance of java.lang.ExceptionInInitializerError.
Soru 51: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. String str1 = new String("Core");
6. String str2 = new String("CoRe");
7. System.out.println(str1 = str2);
8. }
9. }
Core
true
false
CoRe
(Doğru)
Açıklama
System.out.println(str1 = str2) has assignment(=) operator and not equality(==)
operator.
After the assignment, str1 refers to "CoRe" and System.out.println prints "CoRe" to the
console.
Soru 52: Doğru
Consider 3 files:
1. //Order.java
2. package orders;
3.
4. public class Order {
5.
6. }
1. //Item.java
2. package orders.items;
3.
4. public class Item {
5.
6. }
1. //Shop.java
2. package shopping;
3.
4. /*INSERT*/
5.
6. public class Shop {
7. Order order = null;
8. Item item = null;
9. }
For the class Shop, which options, if used to replace /*INSERT*/, will resolve all the
compilation errors?
Select 2 options.
1. import orders.Order;
2. import orders.items.Item;
(Doğru)
import orders.items.*;
1. import orders.*;
2. import items.*;
1. import orders.*;
2. import orders.items.*;
(Doğru)
import orders.*;
Açıklama
If you check the directory structure, you will find that directory "orders" contains "items",
but orders and orders.items are different packages.import orders.*; will only import all
the classes in orders package but not in orders.items package.
You need to import Order and Item classes. To import Order class, use either import
orders.Order; OR import orders.*; and to import Item class, use either import
orders.items.Item; OR import orders.items.*;
Soru 53: Atlandı
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. import java.time.LocalDate;
4. import java.time.Month;
5. import java.util.ArrayList;
6. import java.util.List;
7.
8. public class Test {
9. public static void main(String[] args) {
10. List<LocalDate> dates = new ArrayList<>();
11. dates.add(LocalDate.parse("2018-07-11"));
12. dates.add(LocalDate.parse("1919-02-25"));
13. dates.add(LocalDate.of(2020, 4, 8));
14. dates.add(LocalDate.of(1980, Month.DECEMBER, 31));
15.
16. dates.removeIf(x -> x.getYear() < 2000);
17.
18. System.out.println(dates);
19. }
20. }
[2018-07-11, 1919-02-25, 2020-04-08, 1980-12-31]
[1919-02-25, 1980-12-31]
[2018-07-11, 2020-04-08]
(Doğru)
Runtime exception
Açıklama
LocalDate objects can be created by using static method parse and of.
Soru 54: Yanlış
For the class Test, which options, if used to replace /*INSERT*/, will print "Hurrah! I
passed..." on to the console? Select 2 options.
1. public class Test {
2. /*INSERT*/ {
3. System.out.println("Hurrah! I passed...");
4. }
5. }
public void main(String [] args)
static public void Main(String [] args)
public static void main(String [] a)
(Doğru)
static public void main(String [] args)
(Doğru)
public void static main(String [] args)
protected static void main(String [] args)
(Yanlış)
Açıklama
As System.out.println needs to be executed on executing the Test class, this means
special main method should replace /*INSERT*/.
Special main method's name should be "main" (all characters in lower case), should be
static, should have public access specifier and it accepts argument of String [] type.
String [] argument can use any identifier name, even though in most of the cases you
will see "args" is used.
Position of static and public can be changed but return type must come just before the
method name.
Soru 55: Yanlış
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. private static void m(int x) {
5. System.out.println("int version");
6. }
7.
8. private static void m(char x) {
9. System.out.println("char version");
10. }
11.
12. public static void main(String [] args) {
13. int i = '5';
14. m(i);
15. m('5');
16. }
17. }
char version
int version
char version
char version
int version
char version
(Doğru)
int version
int version
Compilation error
(Yanlış)
Açıklama
Method m is overloaded. Which overloaded method to invoke is decided at compile
time. m(i) is tagged to m(int) as i is of int type and m('5') is tagged to m(char) as '5' is
char literal.
Soru 56: Atlandı
Which of the following is a checked Exception?
RuntimeException
FileNotFoundException
(Doğru)
ExceptionInInitializerError
ClassCastException
Açıklama
ClassCastException extends RuntimeException (unchecked exception),
Soru 57: Yanlış
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. byte var = 100;
6. switch(var) {
7. case 100:
8. System.out.println("var is 100");
9. break;
10. case 200:
11. System.out.println("var is 200");
12. break;
13. default:
14. System.out.println("In default");
15. }
16. }
17. }
In default
Compilation error
(Doğru)
var is 200
var is 100
(Yanlış)
Açıklama
case values must evaluate to the same type / compatible type as the switch expression
can use.
char or Character
byte or Byte
short or Short
int or Integer
byte range is from -128 to 127. But in case expression [case 200], 200 is outside byte
range and hence compilation error.
Soru 58: Yanlış
Given code:
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. String [] arr = {"I", "N", "S", "E", "R", "T"};
6. for(/*INSERT*/) {
7. if (n % 2 == 0) {
8. continue;
9. }
10. System.out.print(arr[n]); //Line n1
11. }
12. }
13. }
All four options
(Doğru)
Only three options
Only one option
None of the other options
Only two options
(Yanlış)
Açıklama
From the given array, if you print the elements at 1st, 3rd and 5th indexes, then you will
get expected output.
Also note that, for values of n = 0, 2, 4, 6; Line n1 would not be executed, which means
even if the value of n is 6, above code will not throw ArrayIndexOutOfBoundsException.
For 1st option [int n = 0; n < arr.length; n += 1], values of n used: 0, 1, 2, 3, 4, 5 and
because of continue; statement, Line n1 will not execute for 0, 2 & 4 and it will execute
only for 1, 3 & 5 and therefore NET will be printed.
For 2nd option [int n = 0; n <= arr.length; n += 1], values of n used: 0, 1, 2, 3, 4, 5, 6 and
because of continue; statement, Line n1 will not execute for 0, 2, 4 & 6 and it will
execute only for 1, 3 & 5 and therefore NET will be printed.
For 3rd option [int n = 1; n < arr.length; n += 2], values of n used: 1, 3, 5 and therefore
NET will be printed.
For 4th option [int n = 1; n <= arr.length; n += 2], values of n used: 1, 3, 5 and therefore
NET will be printed.
Soru 59: Doğru
Which of these access modifiers can be used for a top level interface?
private
protected
All of the other options
public
(Doğru)
Açıklama
A top level interface can be declared with either public or default modifiers.
public interface is accessible across all packages but interface declared with default
modifier and be accessed in the defining package only.
Soru 60: Atlandı
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.time.LocalDate;
5.
6. class MyLocalDate extends LocalDate {
7. @Override
8. public String toString() {
9. return super.getDayOfMonth() + "-" + super.getMonthValue() +
10. "-" + super.getYear();
11. }
12. }
13.
14. public class Test {
15. public static void main(String [] args) {
16. MyLocalDate date = LocalDate.parse("1980-03-16");
17. System.out.println(date);
18. }
19. }
Compilation error
(Doğru)
1980-03-16
16-03-1980
An exception is thrown at runtime
Açıklama
LocalDate is a final class so cannot be extended.
Soru 61: Atlandı
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.time.Period;
5.
6. public class Test {
7. public static void main(String [] args) {
8. Period period = Period.of(0, 0, 0);
9. System.out.println(period);
10. }
11. }
p0d
P0D
(Doğru)
P0Y0M0D
Açıklama
Period.of(0, 0, 0); is equivalent to Period.ZERO. ZERO period is displayed as P0D, other
than that, Period components (year, month, day) with 0 values are ignored.
toString()'s result starts with P, and for non-zero year, Y is appended; for non-zero
month, M is appended; and for non-zero day, D is appended. P,Y,M and D are in upper
case.
1. //B.java
2. package com.udayan.oca.test;
3.
4. import com.udayan.oca.A;
5.
6. public class B extends A {
7. public void print() {
8. A obj = new A();
9. System.out.println(obj.i1); //Line 8
10. System.out.println(obj.i2); //Line 9
11. System.out.println(this.i2); //Line 10
12. System.out.println(super.i2); //Line 11
13. }
14.
15. public static void main(String [] args) {
16. new B().print();
17. }
18. }
One of the statements inside print() method is causing compilation failure. Which of the
below solutions will help to resolve compilation error?
Comment the statement at Line 9
(Doğru)
Comment the statement at Line 10
Comment the statement at Line 8
Comment the statement at Line 11
Açıklama
class A is declared public and defined in com.udayan.oca package, there is no problem
in accessing class A outside com.udayan.oca package.
class B is defined in com.udayan.oca.test package, to extend from class A either use
import statement "import com.udayan.oca.A;" or fully qualified name of the class
com.udayan.oca.A. No issues with this class definition as well.
Variable i1 is declared public in class A, so Line 8 doesn't cause any compilation error.
Variable i2 is declared protected so it can only be accessed in subclass using inheritance
but not using object reference variable. obj.i2 causes compilation failure.
class B inherits variable i2 from class A, so inside class B it can be accessed by using
either this or super. Line 10 and Line 11 don't cause any compilation error.
Soru 63: Doğru
Below is the code of Test.java file:
1. package com.udayan.oca;
2.
3. import java.util.ArrayList;
4. import java.util.List;
5.
6. public class Test {
7. public static void main(String [] args) {
8. List<Integer> list = new ArrayList<Integer>();
9. list.add(new Integer(2));
10. list.add(new Integer(1));
11. list.add(new Integer(0));
12.
13. list.remove(list.indexOf(0));
14.
15. System.out.println(list);
16. }
17. }
[2, 1]
(Doğru)
[1, 0]
An exception is thrown at runtime
Açıklama
remove method of List interface is overloaded: remove(int) and remove(Object).
indexOf method accepts argument of Object type, in this case list.indexOf(0) => 0 is
auto-boxed to Integer object so no issues with indexOf code. list.indexOf(0) returns 2
(index at which 0 is stored in the list). So list.remove(list.indexOf(0)); is converted to
list.remove(2);
Soru 64: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. StringBuilder sb = new StringBuilder();
6. System.out.println(sb.append(null).length());
7. }
8. }
Compilation error
(Doğru)
4
NullPointerException is thrown at runtime
1
Açıklama
'append' method is overloaded in StringBuilder class: append(String),
append(StringBuffer) and append(char[]) etc.
In this case compiler gets confused as to which method `append(null)` can be tagged
because String, StringBuffer and char[] are not related to each other in multilevel
inheritance. Hence `sb.append(null)` causes compilation error.
Soru 65: Atlandı
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.time.LocalDate;
5. import java.time.Period;
6. import java.time.format.DateTimeFormatter;
7.
8. public class Test {
9. public static void main(String [] args) {
10. LocalDate date = LocalDate.of(2012, 1, 11);
11. Period period = Period.ofMonths(2);
12. DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yy");
13. System.out.print(formatter.format(date.minus(period)));
14. }
15. }
01-11-12
Runtime exception
11-11-12
01-11-11
Açıklama
date --> {2012-01-11}, period --> {P2M}, date.minus(period) --> {2011-11-11} [subtract
2 months period from {2012-01-11}, month is changed to 11 and year is changed to
2011].
formatter -> {MM-dd-yy}, when date {2011-11-11} is formatter in this format 11-11-11
is printed on to the console.
Soru 66: Yanlış
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. public class Test {
4. public static void main(String[] args) {
5. String fruit = "mango";
6. switch (fruit) {
7. default:
8. System.out.println("ANY FRUIT WILL DO");
9. case "Apple":
10. System.out.println("APPLE");
11. case "Mango":
12. System.out.println("MANGO");
13. case "Banana":
14. System.out.println("BANANA");
15. break;
16. }
17. }
18. }
MANGO
BANANA
(Yanlış)
ANY FRUIT WILL DO
APPLE
MANGO
BANANA
(Doğru)
MANGO
ANY FRUIT WILL DO
Açıklama
"mango" is different from "Mango", so there is no matching case available. default block
is executed, "ANY FRUIT WILL DO" is printed on to the screen.
No break statement inside default, hence control enters in fall-through and executes
remaining blocks until the break; is found or switch block ends.
So in this case, it prints APPLE, MANGO, BANANA one after another and break;
statement takes control out of switch block. main method ends and program terminates
successfully.
Soru 67: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. import java.io.FileNotFoundException;
4. import java.io.IOException;
5.
6. abstract class Super {
7. public abstract void m1() throws IOException;
8. }
9.
10. class Sub extends Super {
11. @Override
12. public void m1() throws IOException {
13. throw new FileNotFoundException();
14. }
15. }
16.
17. public class Test {
18. public static void main(String[] args) {
19. Super s = new Sub();
20. try {
21. s.m1();
22. } catch (FileNotFoundException e) {
23. System.out.print("M");
24. } finally {
25. System.out.print("N");
26. }
27. }
28. }
MN
Program ends abruptly
N
Compilation error
(Doğru)
Açıklama
Even though an instance of FileNotFoundException is thrown by method m1() at
runtime, but method m1() declares to throw IOException.
Reference variable s is of Super type and hence for compiler, call to s.m1(); is to method
m1() of Super, which throws IOException.
And as IOException is checked exception hence calling code should handle it.
As calling code doesn't handle IOException or its super type, so s.m1(); gives
compilation error.
Soru 68: Yanlış
Consider below code:
1. //Test.java
2. package com.udayan.oca;
3.
4. import java.time.LocalDate;
5.
6. public class Test {
7. public static void main(String [] args) {
8. LocalDate date = LocalDate.of(2020, 9, 31);
9. System.out.println(date);
10. }
11. }
An exception is thrown at runtime
(Doğru)
Compilation error
(Yanlış)
Açıklama
LocalDate.of(...) method first validates year, then month and finally day of the month.
Soru 69: Doğru
What will be the result of compiling and executing Test class?
1. package com.udayan.oca;
2.
3. import java.time.LocalTime;
4.
5. public class Test {
6. public static void main(String[] args) {
7. LocalTime time = LocalTime.of(16, 40);
8. String amPm = time.getHour() >= 12 ? (time.getHour() == 12) ? "PM" : "AM";
9. System.out.println(amPm);
10. }
11. }
AM
An exception is thrown at runtime
PM
Compilation error
(Doğru)
Açıklama
This question is on ternary operator (?:). If an expression has multiple ternary operators
then number of ? and : should match.
Compilation error for Animal(String) constructor
Compilation error for Dog(String, String) constructor
:Beagle:Bubbly:Poodle
null:Beagle:Bubbly:Poodle
Compilation error for Dog(String) constructor
(Doğru)
Compilation error for Animal Class
Açıklama
abstract class can have constructors and it also possible to have abstract class without
any abstract method. So, there is no issue with Animal class.
Java compiler adds super(); as the first statement inside constructor, if call to another
constructor using this(...) or super(...) is not available.
Inside Animal class Constructor, compiler adds super(); => Animal(String name)
{ super(); this.name = name; }, super() in this case invokes the no-arg constructor of
Object class and hence no compilation error here.