Java oca Flashcards

1
Q

What will this print?
class Test{
static boolean a;
static boolean b;
static boolean c;
public static void main (String[] args){
boolean bool = (a = true) || (b = true) && (c = true);
System.out.print(a + “, “ + b + “, “ + c);
}
}

A

true, false, false

Java parses expression from left to right, mind the short circuit operators. The && operator is not performed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When overriden method is called from variable with super class reference (but actual class is subclass), will it fetch method from super class/own or the subclass.

A

It will fetch the overriding method from subclass, fields are from superclass, static methods are also fetched from declared class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

C b1 = (B) b1; Why will this not compile

A

Because b1 is cast to a reference type other than reference type needed. There is no guarantee that a B can be assigned to C, this could be possible (based on casting rules) with double cast (C)(B)b1.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Can LocalDate(Time) be constructor like, new LocalDAte()?

A

No, because LocalDate(Time) as only private constructors. You need to use one of its static methods instead.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which of these two is correct

System.out.println(LocalDate.now()
.with(TemporalAdjusters.next(DayOfWeek.TUESDAY)));

vs

System.out.println(new LocalDate()
.adjust(TemporalAdjusters.next(DayOfWeek.TUESDAY)));

A

The first one, LocalDAte has a .with operator, but not .adjust.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

For instanting of object, which constructors run, from reference type or actual object. Which constructor(s) run first, super or child class.

A

Actual object and superclass (always, if not excplicit implicit, super() call).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Why won’t this run:

Class A{
A(int i){some code};
}
Class B extends Class a{}

A

Because Class B’s (implicit) constructor will make implicit super() call.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

public void ifTest(boolean flag){
if (flag) //1
if (flag) //2
System.out.println(“True False”);
else // 3
System.out.println(“True True”);
else // 4
System.out.println(“False False”);
}

What will be the outcome if rune with argument false? True? Under what condtion will it run True True?

A

False false, True false, none, because if false the second if, and thus not the first else, will not be entered.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What will be the content of newargs?

FunWithArgs fwa = new FunWithArgs();
String[][] newargs = {args};

A

{{“a”, “b” , “c”}}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

If overridden method has throws class, does overriding method need it?
Whether method call needs throws clause or try/catc blocks depends on either referency type or actual object, which one?

A

No.

Whether a call needs a throws clause/try catch block to handle an exception s based on reference type, not actual object, as actual object is only known at runtime (important in overrding situation)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

class XXX{
public void m() throws Exception{
throw new Exception();
}
}
class YYY extends XXX{
public void m(){ }

public static void main(String[] args) {
    \_\_\_\_\_\_\_\_  obj = new \_\_\_\_\_\_();
    obj.m();
} }

Fill the blanks with XXX YYY or YYY YYY, which one is correct.

A

YYY YYY, because reference type decides whether there is an exception thrown/handled that needs to be taken care of be calling method.

If it would be XXX YYY, main method should throw/handle exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Can an overiding method throw any exception?

A

No it can only, but does not have to, throw exception from throws clause overridden method, or any of subexception from the one thrown in overridden method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is correct order of initialization:

A
  1. Static constants, variables, blocks in order they appear. This is class initializaton, only happens when class is used first time (either object created or static method/field used).
    if class has superclass this step is processed first for super class.
  2. non static constants, variables, and blocks.
  3. constructor.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

int i = 5;
float f = 5.5f;
float f2 = 5.0f;

What is the outcome of:
i == f;
i == f2;

A

I will be promoted to float, so 5.0. So false and true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

if main method contians .
X x = new X();
x.apply(LOGICID); // LOGICID is a static method.

Which of these two imports is needed, assume paths are correct:
import static com.foo.X.;
import com.foo.
;

A

Both, because LOGICID is directly accessed without classname (X.LOGICID) static import is needed, but regular import is also needed because an object of x is created.

Import static com.foo.X.LOGICID would also suffice for the static import.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

int i =5;
float f =5.5f;
double d = 3.8;

outcome of:

(int) (f + d) == (int) f + (int) d;

A

becomes 9 ==8, so false.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the outcome?

public class Noobs {
public void m(int a){
System.out.println(“In int “);
}
public void m(char c){
System.out.println(“In char “);
}
public static void main(String[] args) {
Noobs n = new Noobs();
int a = ‘a’;
char c = 6;
n.m(a);
n.m(c);

A

In int
in char

type of primitive is leading, note that ‘a’ to int has numerical value, and 6 for char will be converted to some char.

An int cannot be passed into char.
A char can be passed to both int and char, but char is more specific.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

In switch block, does default to be at the end of all case options?

A

no

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Can main method refer to this.x?

A

No, main method is static, so it cannot reference instance fields directly, it can only do so by creating an object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Why won’t this work?:

public void generateReport( int n ){
String local; // 1
if( n > 0 ) local = “good”; //2
System.out.println( s1+” = “ + local ); //3
}
}

A

Local variable does not get default value, if only intialized in if compiler cannot be sure it will be intitialized. Make it an instance variable so it gets a default value, or at an else part where it will be initialized as well (if initialization in both if and else compiler can be sure it will be initialized).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Which of these are not part of StringBuilder Class:
trim();
ensureCapacity(int);
append(boolean);
reverse();
setlength(int);

A

Trim(), it is only part of String.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

byte b = 2;
short s= 2;

? x = s * b;

What would be the outcome, which data type

A

int 4, because anything lower than int will be converted to int in arithmetic operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

int i = 1;
short s = 2;

s += i; //what would be the outcome?

A

3, compound assignment operators have implicit cast, and 3 fits in short.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Does “String”.replace(‘g’, ‘G’) create a new object.
and “String”.replace(‘g’, ‘g’)?

A

Yes and no, if there is no change (case sensitive) some object is returned. This implies that:
“String”.replace(‘g’,’G’)==”StrinG”; // is false
“String”.replace(‘g’, ‘g’)==”String”; // is true
“String”.replace(‘g’,’G’) == “String”.replace(‘g’,’G’); // is false

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Does this work?:
class TestClass implements T1, T2{
public void m1(){}
}
interface T1{
int VALUE = 1;
void m1();
}
interface T2{
int VALUE = 2;
void m1();
}

A

Yes, ambiguous fields itself do not cause any error, but ambiguous references will. In this case value has to be print like this:

System.out.println((TI)VALUE);

For the method no casting is required, both methods are abstract, the implementation in the implementing class counts for both.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Whether casting works, determined at compile time or runtime

A

runtime, but assingment without casting at compile time. THis means, for the latter, that reference type matters, not actual object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What should be the return type of the following method?
public RETURNTYPE methodX( byte by){
double d = 10.0;
return (long) by/d*3;
}

A

double, note cast only applies to by

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

class Super { static String ID = “QBANK”; }

class Sub extends Super{
static { System.out.print(“In Sub”); }
}
public class Test{
public static void main(String[] args){
System.out.println(Sub.ID);
}
}
What will be the output when class Test is run?

A

QBANK,

No static method or field of Sub itself is invoked, to its static initializer block does not run.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

import java.util.*;
public class TestClass {
public static void main(String[] args) throws Exception {
List list = new ArrayList();
list.add(“val1”); //1
list.add(2, “val2”); //2
list.add(1, “val3”); //3
System.out.println(list);
}
}

Why does this fail

A

Because of line to, you cannot put something on third position when ArratyList has only one value yet, it needs at least two

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

Which one will correctly return the largest value

int max(int x, int y){
if (x > y) return x;
return y;
}

int max(int x, int y){
return( if(x > y){ x; } else{ y; } );

int max(int x, int y){
return( if(x > y){ return x; } else{ return y; } );

A

The first one.

The second one has an if statement that does not retun anything so does not work).

The third one would work if the first return and corresponding brakcets are removes.

conclusion, return is insied if/else, not outside.

Note in first example, ones first return (in if) performed second one will not be reached.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

Can break apply to if/else

A

No, if it has break statement is should be applied to outer constructor (switch or for loop)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What will be the result of attempting to compile and run the following program?
public class TestClass{
public static void main(String args[ ] ){
Object a, b, c ;
a = new String(“A”);
b = new String(“B”);
c = a;
a = b;
System.out.println(““+c);
}
}

A

A will be printed, actual object matters and String class overrides toString. If actual object is of Object it would return something with the hascode of object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

why doesn’t this work:

Short k = new Short(9); System.out.println(k instanceof Short);

A

9 is an int, and Short contains no constructor taking int.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

why doesn’t this work?;

class MyException extends Exception {}
public class TestClass{
public static void main(String[] args){
TestClass tc = new TestClass();
try{
tc.m1();
}
catch (MyException e){
tc.m1();
}
finally{
tc.m2();
}
}
public void m1() throws MyException{
throw new MyException();
}
public void m2() throws RuntimeException{
throw new NullPointerException();
}
}

A

The catch blocks, again, throws exception, which is not handled or thrown. Either at a nested try catch block or add to method signature.

Note that the method thrown in finally clause is fine because it throws a runtime exception.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

Are these two correct?

Multiple inheritance of state includes ability to inherit instance fields from multiple classes.

Multiple inheritance of type includes ability to implement multiple interfaces and/or ability to extend from multiple classes.

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

String f = “12.3”;
int i = Integer.parseInt(f);

Does this run without exception

A

No, numberformatexception because 12.3 is not an integer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

What will the following program print when run?

class Super{
public String toString(){
return “4”;
}
}
public class SubClass extends Super{
public String toString(){
return super.toString()+”3”;
}
public static void main(String[] args){
System.out.println( new SubClass() );
}
}

A

43

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Which three modifiers cannob be applied to a constructor.

A

final, static, abstract

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

Test(Test b){}

Is this a valid constructor

A

Yes, constructor can take it’s own type as parameter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

why doesn’t this work?:
new Object[1]{ new Object() };

A

You cannot specify array length if you initialize at the same place

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

Does String class have append and insert method?

A

No, because of being immutable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

Which datatypes can be used in switch variable

A

byte, char, short in String, enums, Byte, Character, Short, and Integer.

Long, float, double and boolean are not allowed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What will the following method return when you give 8 as argument:

public int luckyNumber(int seed){
if(seed > 10) return seed%10;
int x = 0;
try{
if(seed%2 == 0) throw new Exception(“No Even no.”);
else return x;
}
catch(Exception e){
return 3;
}
finally{
return 7;
}
}

A

7, it will always return 7

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

Can a catch block come after finally block

A

no

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
42
Q

if (true) { break ; } (When not inside a switch block or a loop)

Will this compile?

A

No, break cannot be in if statement, unless the if(else) is part of loop. You can also use it without loop if it has a label.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
43
Q

Will this work?

label: if(true){
System.out.println(“break label”);
break label;
}

A

Yes, break cannot be in if else, unless it is nested in loop construct or when if statement has label.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
44
Q

What is the problem?
public class TestClass{
public static double getSwitch(String str){
return Double.parseDouble(str.substring(1, str.length()-1) );
}
public static void main(String args []){
switch(getSwitch(args[0])){
case 0.0 : System.out.println(“Hello”);
case 1.0 : System.out.println(“World”); break;
default : System.out.println(“Good Bye”);
}
}
}

A

Double cannot be used in switch statement

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
45
Q

Has overrding method to have to same acces level as overridden method?

A

No, it can be less restrictive. I.e. protected instead of default

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
46
Q

Covariant return type for overriding means

A

Overriding method can also return subclass of return type overridden class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
47
Q

Are the following true/false?
1. ArrayList extends java.util.AbstractList
2. it allows you to access its elements in random order
3. You must specify the class of objects you want to store in ArrayList when ou declare a variable of type ArrayList.
4. ArrayList does not implement RandomAccess
5. You can sort is elements using Collections.sort()

A
  1. true, object –> abstractCollection –> AbstractList –> ArrayList
  2. true, not like linkedList where you have to go through every element before the element you want to get.
  3. false
  4. False
  5. true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
48
Q

What will this print?:

class Test{
public static void main(String[ ] args){
int[] a = { 1, 2, 3, 4 };
int[] b = { 2, 3, 1, 0 };
System.out.println( a [ (a = b)[3] ] );
}
}

A

1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
49
Q

issue?
public class TestClass{
public static void main(String[] args){
for : for(int i = 0; i< 10; i++){
for (int j = 0; j< 10; j++){
if ( i+ j > 10 ) break for;
}
System.out.println( “hello”);
}
}
}

A

For is a keyword so cannot be used for label.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
50
Q

problem?
static String[] days = {“monday”, “tuesday”, “wednesday”, “thursday”,
“friday”, “saturday”, “sunday” };

public static void main(String[] args) {
    
    int index = 0;
    for(String day : days){
        
        if(index == 3){
            break;
        }else {
             continue;
        }
        index++;
        if(days[index].length()>3){
            days[index] = day.substring(0,3);
        }
    }
    System.out.println(days[index]);
} }
A

Cannot get past if else because of break and continue. If there is code that, determied at compile time, is unreachable it will not compile

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
51
Q

Can final variable be hidden?

A

Yes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
52
Q

int a = b = c = 100;

Is this valid

A

No, chaining is not allowed if you do declaring and initialization at the same time. If b and c were already declared it would work.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
53
Q

Are primitives and objects being passed by value?

A

Yes, both are

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
54
Q

Will this one not compile or throw exception

public class TestClass{
public static void main(String args[]){
Exception e = null;
throw e;
}
}

A

not compile, because it is throwing an exception without the method not having a throws clause or handling it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
55
Q

Which line does not compile?

public class Discounter {
static double percent; //1
int offset = 10, base= 50; //2
public static double calc(double value) {
int coupon, offset, base; //3
if(percent <10){ //4
coupon = 15;
offset = 20;
base = 10;
}
return couponoffsetbase*value/100; //5
}
public static void main(String[] args) {
System.out.println(calc(100));
}
}

A

5, because it uses a local variable that has not been initialized at compile time (it is not a constant).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
56
Q

outcome?

class Base{
void methodA(){
System.out.println(“base - MethodA”);
}
}

class Sub extends Base{
public void methodA(){
System.out.println(“sub - MethodA”);
}
public void methodB(){
System.out.println(“sub - MethodB”);
}
public static void main(String args[]){
Base b=new Sub(); //1
b.methodA(); //2
b.methodB(); //3
}
}

A

Not compile because of line 3, method called is not included in reference type, so at compile time compiler cannot be sure that it is present. The actual object is only considered at runtime.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
57
Q

Can line 1 and two 2 be uncommented?

class A{
public static void sM1() { System.out.println(“In base static”); }
}

class B extends A{

Line 1 –> // public static void sM1() { System.out.println(“In sub static”); }

Line 2 –> // public void sM1() { System.out.println(“In sub non-static”); }

}

A

Only line 1, but not 2 or both. A static method cannot be hidden/overidden by a non static method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
58
Q

can charAt() take a char as argument?
What will charAT() return

A

Yes, because it is implicitly promoted to int.
char (primitive).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
59
Q

System.out.println(‘b’+new Integer(63));

A

prints 98, char is a numerical value

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
60
Q

Does polymorphism make the code more efficient? And more dynamic?

A

ambiguous, efficient can mean efficient in different ways. For execution efficiency it is not true, because of dynimic binding at runtime it is slightly less efficient.

Yes, there is dynamic binding at runtime, i.e. method invoked can be decided at runtime based on actual class of object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
61
Q

why not compile?

abstract class A{
protected int m1(){ return 0; }
}
class B extends A{
int m1(){ return 1; }
}

A

B does not override correct, it reduces accesibility.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
62
Q

At which places can a final variable be intialized.

A

right, away, instance initializer, any constructor.

Static variable cannot be initialized in constructor.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
63
Q

public class TestClass{
public static void main(String[] args){
Object obj1 = new Object();
Object obj2 = obj1;
if( obj1.equals(obj2) ) System.out.println(“true”);
else System.out.println(“false”);
}
}// what will it print?

A

true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
64
Q

ArrayList<Double> al = new ArrayList<>();
al.add(111);</Double>

Does this work?

A

No, na widening plus autoboxing.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
65
Q

public class Operators{

public static int operators(){
    int x1 = -4;
    int x2 = x1--;
    int x3 = ++x2;
    if(x2 > x3){
        --x3;
    }else{
        x1++;
    }
    return x1 + x2 + x3;
}
public static void main(String[] args) {
    System.out.println(operators());
} }

outcome?

A

-10

Note that int x3 = ++x2; affects x2 as wel

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
66
Q

problem
public float parseFloat(String s){
float f = 0.0f;
try{
f = Float.valueOf(s).floatValue();
return f ;
}
catch(NumberFormatException nfe){
System.out.println(“Invalid input “ + s);
f = Float.NaN ;
return f;
}
finally { System.out.println(“finally”); }
return f ;
}

A

return after finally block not reachable.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
67
Q

class B { B(){ } }

Is this a default constrcutor?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
68
Q

outcome?

class A{
A() { print(); }
void print() { System.out.print(“A “); }
}
class B extends A{
int i = 4;
public static void main(String[] args){
A a = new B();
a.print();
}
void print() { System.out.print(i+” “); }
}

A

0 4

implicit super() call means A is constructed first. The print call is non private, which implies it is polymorphic, meaning that it is overridden by b’s print() method. So b’s print method is called, note that b’s i has not yet been initialized (because A is first initialized). This means i still has its default value, 0.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
69
Q

When a class, whose members should be accessible only to members of that class, is coded such a way that its members are accessible to other classes as well, this is called …

A

weak encapsulation

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
70
Q

Outcome?

public void method1(int i){
int j = (i*30 - 2)/100;

POINT1 : for(;j<10; j++){
boolean flag = false;
while(!flag){
if(Math.random()>0.5) break POINT1;
}
}
while(j>0){
System.out.println(j–);
if(j == 4) break POINT1;
}
}

A

Does not compile, second break is not in loop where label is declared.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
71
Q

Precedence, dot operator or cast operator

A

dot operator.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
72
Q

public class TestClass{
int a;
int b = 0;
static int c;
public void m(){
int d;
int e = 0;
d++ }
}

outcome

A

outcome, d is not yet initialized, does not have default value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
73
Q

Outcome?

public class TestClass {

public static void main(String[] args){
    int k = 2;
    while(--k){
        System.out.println(k);
    }
} }
A

While condition does not evaluate to boolean, so does not compile

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
74
Q

Which of these classes is not final
System, Number, Boolean, String, StringBuilder

A

Number

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
75
Q

Which number is a valid method

public class TestClass{
public TestClass(int a, int b) { } // 1
public void TestClass(int a) { } // 2
public TestClass(String s); // 3
private TestClass(String s, int a) { } //4
public TestClass(String s1, String s2) { }; //5
}

A

2, the others constructors.

76
Q

Which assignments are valid?

1 short s =12;
2 long g =012;
3 int i = (int)false;
4 float f = -123;
5 float d = 0 *15;

A
  1. valid, implicit narrowing (can happen until int if size allows)
  2. valid octal number
  3. boolean cannot be converted to other type.
  4. Impliclit widening.
  5. Double cannot be implicitly narrowed to a float, even if value is representable by float.
77
Q

If the following method is declared in an interface, would it be valid?

static void compute();

A

No static method should have a body, static method cannot be (impliclitly) abstract.

78
Q

is this allowed:

for(final Object o2 :c){ }

A

Yes, final is the only modifier allowed here.

79
Q

which methods are passed an implicit this parameter when called?

A

all instance (or non static) methods

80
Q

When can you directly use something from another class without importing

A

When in same package, and if access modifier allows

81
Q

package uitl.log4j;
public class Logger{some codce}

How to create object of this class in another package without import

A

new util.log4j.Logger();
i.e. use fully qualified name.

82
Q

Does Array or ArrayList implement collection interface?

A

ArrayList

83
Q

Name two benefits of Array over ArrayList

A

It consumes less memory
Accessing an element in an array is faster than in ArrayList

84
Q

Is empty String same as null?

A

no

85
Q

void crazyLoop(){
int c = 0;
JACK: while (c < 8){
JILL: System.out.println(c);
if (c > 3) break JILL; else c++;
}
}

Outcome?

A

Does not compile, JILL can only be breaked in own scope. Its scope ends after System.out.println(c); You would have to use brackets to make it work.

86
Q

Can overriding method have more or less visibility?

A

more, so protected instead of default, but not private instead of default.

87
Q

while (false) { x=3; }
if (false) { x=3; }

Which one will compile?

A

Second one, normally it is a problem if certain code is unreachable, but if is defined as an exception.

88
Q

Outcome?
public int transformNumber(int n){
int radix = 2;
int output = 0;
output += radixn;
radix = output/radix;
if(output<14){
return output;
}
else{
output = output
radix/2;
return output;
}
else {
return output/2;
}
}

A

Does not compile because there is one else without if.

89
Q

public class Test{
public static void main(String[] args){
if (args[0].equals(“open”))
if (args[1].equals(“someone”))
System.out.println(“Hello!”);
else System.out.println(“Go away “+ args[1]);
}
}

What if run with java Test closed

A

Printes nothing, the else is associated with inner if, which is never reached.

Note that if you would run with open arrayIndexOutOfBounds would be thrown.

90
Q

private ArrayList<Integer> scores;</Integer>

How can encapsulation of this field be improved?

A

Return a copy, because arrayList is mutable;

Like public Arraylist<Integer> getScores(){
return new ArrayList(scores);
}</Integer>

91
Q

//in file Movable.java
package p1;
public interface Movable {
int location = 0;
void move(int by);
public void moveBack(int by);
}

//in file Donkey.java
package p2;
import p1.Movable;
public class Donkey implements Movable{
int location = 200;
public void move(int by) {
location = location+by;
}
public void moveBack(int by) {
location = location-by;
}
}

//in file TestClass.java
package px;
import p1.Movable;
import p2.Donkey;
public class TestClass {
public static void main(String[] args) {
Movable m = new Donkey();
m.move(10);
m.moveBack(20);
System.out.println(m.location);
}
}

A

There is no problem with the code. All variables in an interface are implicitly public, static, and final. All methods in an interface are public. There is no need to define them so explicitly. Therefore, the location variable in Movable is public and static and the move() method is public.

Now, when you call m.move(10) and m.moveBack(20), the instance member location of Donkey is updated to 190 because the reference m refers to a Donkey at run time and so move and moveBack methods of Donkey are invoked at runtime. However, when you print m.location, it is the Movable’s location (which is never updated) that is printed.

92
Q

class MyException extends Throwable{}
class MyException1 extends MyException{}
class MyException2 extends MyException{}
class MyException3 extends MyException2{}
public class ExceptionTest{
void myMethod() throws MyException{
throw new MyException3();
}
public static void main(String[] args){
ExceptionTest et = new ExceptionTest();
try{
et.myMethod();
}
catch(MyException me){
System.out.println(“MyException thrown”);
}
catch(MyException3 me3){
System.out.println(“MyException3 thrown”);
}
finally{
System.out.println(“ Done”);
}
}
}

A

fails because most specific exception should come first.

93
Q

how can you make the following work without adding System in the code?

out.println(MAX_VALUE);

A

import static java.lang.System.*

out is a static field.

94
Q

final class TestClass { }

private class TestClass { }

Which one cannot be subclassed?

A

The final one

95
Q

Can a class be static?

A

Yes, but only inner classes

96
Q

What can the native keyword be used upon?

A

Methods, not on classes or fields

97
Q

Can an enhanced for loop iterature over a map

A

no, only over array or objects that implements iterable.

98
Q

Thread t = new Runnable();

Can you do this

A

No, Runnable is an interface, it cannot be instantiated like this.

99
Q

Why doesn’t this work?

Data d = new Data(1); al.add(d);
d = new Data(2); al.add(d);
d = new Data(3); al.add(d);

filterData(al, d -> d.value%2 == 0 );

A

lambda does not create new scope for variable, and d is already in use

100
Q

Which method in String class is not final?

A

None, String class itself is final and so all of its methods are impliclity final.

101
Q

Does StringBuilder extend String?

A

no, it extends objects

102
Q

name all packages that are automatically imported

A

java.lang

103
Q

Does this work?:

package com.enthu.rad.*;

A

No, no * can be used in package statement

104
Q

Why doesn’t the following work?

public static boolean checkList(List list, Predicate<List> p){
return p.test(list);
}</List>

checkList(new ArrayList(), (ArrayList al) -> al.isEmpty());

A

Predicate with type List is used, so list, and not ArrayList, should be used in Lambda.

105
Q

Outcome?

Object t = new Integer(107);
int k = (Integer) t.intValue()/9;
System.out.println(k);
A

Does not compile, because Object has no intValue() method. This is due to dot operator having precedence over cast operator. ((Integer)t).intValue()/9 would work

106
Q

getClass()l

prints classname reference type or actual object?

A

actual object

107
Q

If no proper main method, compile error or exception or Error?

A

Error

108
Q

Fields in interface are implicitly?

A

public static final

109
Q

What is the following evaluated to? (b1 and b2 are false)
b2 != b1 = !b2

A

false = !b2, which does not compile because false is not a variable.

This is due to = having least precedence (of all operators)

b2 = b1 != b2) would work

110
Q

What matters for casting, reference or actual object?

A

actual object

111
Q

Does casting change reference type, or actual object?

A

actual object

112
Q

output?

abstract class Calculator{
abstract void calculate();
public static void main(String[] args){
System.out.println(“calculating”);
Calculator x = null;
x.calculate();
}
}

A

print calculating and then throw nullpointerException

113
Q

problem?

interface Bozo{
int type = 0;
public void jump();
}

Now consider the following class:

public class Type1Bozo implements Bozo{
public Type1Bozo(){
type = 1;
}

     public void jump(){
        System.out.println("jumping..."+type);
     }

     public static void main(String[] args){
        Bozo b = new Type1Bozo();
        b.jump();
     } }
A

fields in interfaces are public static final, so type cannot be reassigned a value. Will not compile.

114
Q

Can this(…) be called in a method?

A

No, only in Constructor

115
Q

//In File Other.java
package other;
public class Other { public static String hello = “Hello”; }

//In File Test.java
package testPackage;
import other.*;
class Test{
public static void main(String[] args){
String hello = “Hello”, lo = “lo”;
System.out.print((testPackage.Other.hello == hello) + “ “); //line 1
System.out.print((other.Other.hello == hello) + “ “); //line 2
System.out.print((hello == (“Hel”+”lo”)) + “ “); //line 3
System.out.print((hello == (“Hel”+lo)) + “ “); //line 4
System.out.println(hello == (“Hel”+lo).intern()); //line 5
}
}
class Other { static String hello = “Hello”; }
What will be the output of running class Test?

A

true, true, true, false, true

These are the six facts on Strings:
1. Literal strings within the same class in the same package represent references to the same String object.
2. Literal strings within different classes in the same package represent references to the same String object.
3. Literal strings within different classes in different packages likewise represent references to the same String object.
4. Strings computed by constant expressions are computed at compile time and then treated as if they were literals.
5. Strings computed at run time are newly created and therefore are distinct. (So line 4 prints false.)
6. The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents. (So line 5 prints true.)

We advise you to read section 3.10.5 String Literals in Java Language Specification.

116
Q

package strings;
public class StringFromChar {

public static void main(String[] args) {
    String myStr = "good";
    char[] myCharArr = {'g', 'o', 'o', 'd' };
    
    String newStr = null;
    for(char ch : myCharArr){
        newStr = newStr + ch;
    }

    System.out.println((newStr == myStr)+ " " + (newStr.equals(myStr)));
A

false false

newStr is changed to nullgood…

117
Q

Do you need to type decimal values for double or float?

A

No, but .00 will implicitly be added

118
Q

Can an int be assigned to a char variable

A

Only with casting

119
Q

What is the problem
public void filterData(ArrayList<Data> dataList, Predicate<Data> p){</Data></Data>

and

filterData(al, (Data y) -> y.value%2 );

A

Predicate is a functional interface with a method called test that returns a boolean, so the body of the lambda must return a boolean

120
Q

int num[] = {2,3,4,5} ;
List list = new ArrayList();
int length = …… + …….;

How can you get the total length by filling the blanks?

A

for num[] num.length // array has field length
list.size()//araylist has method size

121
Q

String [][] strings = // a properly defined two dimensional Array
Arrys.sort(strings);

How will a twodiminsonial array be sorted?

A

Not, there is no overloaded version that takes a two dimensional array, this will lead to a classCastException

122
Q

If there is an unhandled/not catched runtime exception, will the finally block run?

A

Yes

123
Q

What is the correct command to compile a java source file with the name Whizlabs?

A

javac Whizlabs.java

124
Q

Public class someClass{

public static void main(String args[]){
System.out.println(“Main”);
}

{System.out.println(“something”); };

static{System.out.print(“Static”);};

}

What will be printed when above is run?

A

Static Main,

the static block will run once the class loads, which will happen if you call the main method in it.

The non-static initializer block will not run because no instance of the class is created.

125
Q

What will be the outcome?

public class someThing{

public static void main(String args[]){

int x = 2;
for(int x = 0; x < 3; x++){
System.out.print(x);
}
}
}

A

Compilation fails, variable x is defined in the same scope twice. It would work if the first x would be defined above the main method, than it would be an instance variable that would be hidden by the local variable x.

126
Q

What will be the outcome of the following?

public class Whiz {

static int x =10;

public static void main(String args[]){
for(x=1; x < 3; x++){
System.out.print(x);
}
System.out.println(x);
}
}

A

123

No new variable x has been declared in method, so it refers to the static variable x. So that variable will be set to 1 first and than gradually be changed to three, which the last print outisde of loop will print.

127
Q

do{
int i = 1;
System.out.print(i++);
} while(i <= 5);

outcome?

A

Compilation fails, i in do part is unreachable for while statement.

128
Q

outcome?

public static void main(String args[]){
int x =10;

if(x>10);
System.out.println(“>”);
else if(x<10)
System.out.println(“<”);
}
}

A

Does not compile, there is a semi colon directly after the if statement, so there is no code the if block could perform, this leads to a compile error.

128
Q

final int x;
x = 0;

switch(x){
case x:
…. more code

Does this work

A

No, x is not compile time constant, even though it is final its value is assigned later.

129
Q

int _6 = 6;
if(_6 > 6)
System.out.print(“>6”);
System.out.print(“or”);

else{
System.out.print(“<6”);
}
}
}

outcome?

A

Does not compile, as else is ‘unhinged’ from if

130
Q

int count = 0;
int x = 3;
while(count++ ˂ 3) {
int y = (1 + 2 * count) % 3;

What will be the value of y?

A

0, because 1+2*count % 3 == 0.

131
Q

public interface Animal { public default String getName() { return null; } }
interface Mammal { public default String getName() { return null; } }
abstract class Otter implements Mammal, Animal {}

What three things can you do to make this compile

A

Have the Otter class override getname with EITHER a concrete or an abstract class

Remove default modifier for hte methods in both interfaces, i.e. make them abstract. Note, you should do this with both, if one is abstract and one not there is a problem.

132
Q

public class Deer {
2: public Deer() { System.out.print(“Deer”); }
3: public Deer(int age) { System.out.print(“DeerAge”); }
4: private boolean hasHorns() { return false; }
5: public static void main(String[] args) {
6: Deer deer = new Reindeer(5);
7: System.out.println(“,”+deer.hasHorns());
8: }
9: }
10: class Reindeer extends Deer {
11: public Reindeer(int age) { System.out.print(“Reindeer”); }
12: public boolean hasHorns() { return true; }
13: }

What will be the outcome

A

DeerReindeer, false,

because Deer’s hasHorns() is private it is not overridden, because reference type is Deer deer’s method will be picked.

133
Q

Which of the following lines can be inserted at line 11 to print true? (Choose all that apply)

10: public static void main(String[] args) {
11: // INSERT CODE HERE
12: }
13: private static boolean test(Predicate˂Integer˃ p) {
14: return p.test(5);
15: }

D. System.out.println(test((int i) -˃ i == 5);
E. System.out.println(test((int i) -˃ {return i == 5;}));

A

None of mentioned options, collections inferring predicates DO NOT have the ability of autoboxing. As the predicate in the example is of type Integer this implies that the parameter cannot be of type int in parameter.

134
Q

Bytecode is in a file with which extension?

A

.class

135
Q

outcomme of

4: String numbers = “2468”;
5: int total = 0;
6: total += numbers.indexOf(“6”);
7: total += numbers.indexOf(“9”);
8: char ch = numbers.charAt(3);
9: System.out.println(total + “ “ + ch);

A

1 8

note that if indexOf does not find element it returns -1

136
Q

outcome fo Count?

public class Deer {
static int count;
static { count = 0; }

Deer() {
count++;
}

public static void main(String[] args) {
count++;
Deer mother = new Deer();
Deer father = new Deer();
Deer fawn = new Deer();
System.out.println(father.count);
}
}

A

4

137
Q

Is the following a referency variable?

int[] ints;

A

Yes, all arrays are reference variables, even if of a primitive type

138
Q

1: import java.util.function.*;
2:
3: public class Panda {
4: int age;
5: public static void main(String[] args) {
6: Panda p1 = new Panda();
7: p1.age = 1;
8: check(p1, Panda p -˃ p.age ˂ 5);
9: }
10: private static void check(Panda panda, Predicate˂Panda˃ pred) {
11: String result = pred.test(panda) ? “match” : “not match”;
12: System.out.print(result);
13: } }

outcome?

A

Does not compile on line 8 because parentheses are lacking around parameter (as parameter type is included)

139
Q

public class HowMany {
public static int count(int a) {
if (a != 3) { int b = 1;
} else {
int b = 2;
}
return a++ + b;
}
public static void main(String[] args) {
System.out.print(count(3));
System.out.print(count(9));
}}

outcome

A

b is local to if, or else, so it is not reachable ones to code hits return

140
Q

find two problems

1: package aquarium;
2: public class Water {
3: public String toString() { return “”; } }

1: package aquarium;
2: public class Shark {
3: static int numFins;
4: static Water water;
5: public static void Main(String[] args) {
6: String s1 = water.toString();
7: String s2 = numFins.toString(); } }

A

numFins is a primitive, so cannot de method chaining. Shark class does not have a proper main method, so will produce an error

141
Q

1: interface Climb {
2: boolean isTooHigh(int height, int limit);
3: }
4:
5: public class Climber {
6: public static void main(String[] args) {
7: check((h, l) -˃ h ˃ l, 5);
8: }
9: private static void check(Climb climb, int height) {
10: if (climb.isTooHigh(height, 10))
11: System.out.println(“too high”);
12: else
13: System.out.println(“ok”);
14: }
15: }

A

prints ok, because method in interface takes to parameters lambda should define two parameters.

142
Q

String letters = “abcde”;String answer = ____________________System.out.println(answer);

can blank be filled with letters.charAt(2);

A

No, because charAt returns char and not String.

143
Q

LocalDate date = LocalDate.of(2018, Month.APRIL, 30).plusMonths(-1)
.plusYears(20);
System.out.println(date.getYear() + “ “ + date.getMonth() + “ “
+ date.getDayOfMonth());

Outcome

A

2038 MARCH 30

144
Q

problem

3: int x = 10 % 2;
4: int y = 3 / 5 + ++x;
5: int z += 4 * x;
6: System.out.print(x+”,”+y+”,”+z);

A

compound operator is used on variable that is not declared beforehand, it is not allowed to use compound operator and declare variable at same time.

145
Q

What files are generated when the following is compiled?

1: public class Plant {
2: public boolean flowering;
3: public Leaf [] leaves;
4: }
5: class Leaf {
6: public String color;
7: public int length; }

A

Plant.class and Leaf.class bytecode files are created

146
Q

A. String[] grades; grades = {“B”, “C”, “F”, “A”, “D”};
B. String[] grades; grades = new String[] {“B”, “C”, “F”, “A”, “D”};
C. String[] grades = {“B”, “C”, “F”, “A”, “D”};
D. String grades [] = {“B”, “C”, “F”, “A”, “D”};
E. String grades[]; grades = new []String {“B”, “C”, “F”, “A”, “D”};
F. String []grades[] = {“B”, “C”, “F”, “A”, “D”};

Which ones are correct

A

B, C, D

Option A attempts to use an anonymous initializer, which is only allowed in the declaration. Option B correctly separates the declaration and
initialization. Option C correctly uses an anonymous initializer. Option D shows the brackets can be either before or after the variable name. Option
E is incorrect because the brackets are not allowed to be before the type. Option F is incorrect because the initializer is a one-dimensional array
whereas the declaration is a two-dimensional array.

147
Q

outcome?

14: List˂String˃ numbers = new ArrayList˂˃();
15: numbers.add(“4”); numbers.add(“7”);
16: numbers.set(1, “5”);
17: numbers.add(“8”);
18: numbers.remove(0);
19: for (String number : numbers) System.out.print(number);

A

58

148
Q

which line will not compile?

1: interface HasHindLegs {
2: int getLegLength();
3: }
4: interface CanHop extends HasHindLegs {
5: public void hop();
6: }
7: public class Rabbit implements CanHop {
8: int getLegLength() { return 5; }
9: public void hop() { System.out.println(“Hop”); }
10: public static void main(String[] args) {
11: new Rabbit().hop();
12: }
13: }

A

8, because access is more restrictive (remember, interface methods are assumed public).

149
Q

In which package is the LocalDate class

A

java.time

150
Q

Which line is first to not compile

1: public class Frog {
2: public int Frog() { return 0; }
3: private List˂Integer˃ legs;
4: public Frog() {
5: legs = new ArrayList˂Integer˃();
6: for (int i = 0; i ˂ 4; i++) {
7: legs.add(i);
8: } } }

A

3, no ArrayList import.

Note, because it starts at 1 the whole thing is displayed, so as no imports are presents they cannot be assumed.

151
Q

is the following correct?

E. check((s1) -˃ s.isEmpty());

A

no, parameter list should match the name used in body

152
Q

outcome?

public class TestClass{
public static void main(String args[ ] ){
StringBuilder sb = new StringBuilder(“12345678”);
sb.setLength(5);
sb.setLength(10);
System.out.println(sb.length());
}
}

A

will print 10.

If full sub printed it would be “12345 “ (5 null characters, ‘\u0000’).

153
Q

Can main method be final?

A

Yes, final method cannot be overidden or hidden by subclass

154
Q

Is object passed by value or reference

A

Value, so not the object but value of object is used as argument

155
Q

Must switch and case staemetn have the same data type

A

yes

156
Q

What will happen when the following code is compiled and run?

class AX{
static int[] x = new int[0];
static{
x[0] = 10;
}
public static void main(String[] args){
AX ax = new AX();
}
}

A

ExceptionInInitializerError

157
Q

What will the following program print when compiled and run?

class Game{
public void play() throws Exception{
System.out.println(“Playing…”);
}
}

public class Soccer extends Game{
public void play(){
System.out.println(“Playing Soccer…”);
}
public static void main(String[] args){
Game g = new Soccer();
g.play();
}
}

A

Not compile, game’s play() throws exception, because Game is used as reference type calling method must throw exception as well (it will only discover the overriding method without exception at runtime).

158
Q

Is chaining of methods allowed in Period and LocalDAte

A

Not in Period, or at least only last one willw ork, but fine for LocalDateTime

159
Q

What will the following line of code print?
System.out.println(LocalDate.of(2015, Month.JANUARY, 01)
.format(DateTimeFormatter.ISO_DATE_TIME));

A

Exception, DateTime formate is used on date only

160
Q

valid?
double x=10, double y;
double x= 10, y;

A

Only the second one

161
Q

a.equals(b) throws an exception if they refer to instances of different classes.

true or false

A

false, as it will return false in such case

162
Q

ArrayList s1……..

s1.remove(“a”)

If multiple a elements , will al be removed?

A

No, only the first occurence

163
Q

Is runtime exception child of exception

A

yes

164
Q

valid?

int j=5;
for(int i=0, j+=5; i<j ; i++) { j–; }

A

No, int j already declared, so cannot be declared again in for loop. int i declaration should be moved outside of for loop

165
Q

Which of the following lambda expressions can be used to invoke a method that accepts a java.util.function.Predicate as an argument?

x -> System.out.println(x)

x -> System.out.println(x);

x -> x == null

() -> true

x->true

A

First one Incorrect, to capture Predicate Interface boolean must be returned.

Second one incoorrect, semi colon is invalid as no braces, does not return boolean.

Thrid one correct, returns boolean.

fourth one incorrect, Predicate expects exactly one parameter, this one is empty.

fifth one correct

166
Q

Consider the following class :

public class Parser{
public static void main( String[] args){
try{
int i = 0;
i = Integer.parseInt( args[0] );
}
catch(NumberFormatException e){
System.out.println(“Problem in “ + i );
}
}
}
What will happen if it is run with the following command line:
java Parser one

A

int i is declared in try block, so not visible in catch block

167
Q

What will the following code print when run?

import java.util.function.Predicate;
class Employee{
int age; //1
}

public class TestClass{

public static boolean validateEmployee(Employee e, Predicate<Employee> p){
return p.test(e);
}</Employee>

public static void main(String[] args) {
Employee e = new Employee(); //2
System.out.println(validateEmployee(e, e->e.age<10000)); //3
}
}

A

e is already declared, as a Lambda does not provide a new scope for a variable you cannot pick a name for parameter that is already in use

168
Q

Can Arraylist store primitive?

A

No, but it can handle primitives with autoboxing

169
Q

Does ArrayList allow constant itme access to all its elements

A

Yes, due to java.util.RandomAcces interface

170
Q

Is an ArrayList backed by an Array

A

Yes, an array is used to store values.

171
Q

Standard JDK provides no subclasses of ArrayList

A

False, it provides ATtributeList, RoleList, RoleUnresolvedList

172
Q

Do you need anything to be able to run java code on a specific OS

A

Yes, a JRE for that OS

173
Q

Valid?

java.time.LocalDateTime.parse(“2015-01-02”);

java.time.LocalDateTime.of(2015, 10, 1, 10, 10);

A

No, as no time provided, if you do java.time.LocalDateTime.parse(“2015-01-02T17:13:50”) it would work

Yes, second one is valid, hours and minutes are provided

174
Q

Can a switch block contain code without a label

A

No, all code should have a case label

175
Q

void test(byte x){
switch(x){
case ‘a’: // 1
case 256: // 2
case 0: // 3
default : // 4
case 80: // 5
}
}

outcme?

A

Compile error because of line 2, 256 does not fit byte. -128 to 127

176
Q

public void stringProcessor(String… strs){
}
public void stringProcessor(String[] strs){
}

Which one is correct if you want the method to be able to take a flexible amount of String arguments

A

first one

177
Q

class A { public void perform_work(){} int a = 0 }
class B extends A { public void perform_work(){ inta = 1} }
class C extends B { public void perform_work(){ int a = 2} }
How can you let perform_work() method of A to be called from an instance method in C? And how variable a from A?

A

Not possible for methods you can go only one up.

Variables are not overridden but hidden. This means you can unhide it with a cast. from c it would be ((A)c).a.

178
Q

Consider the following class:

public class PortConnector{
public PortConnector(int port) throws IOException{
…lot of valid code.
}
…other valid code.
}

You want to write another class CleanConnector that extends from PortConnector. Which exception should the constructor of CleanConnector throw?

A

IOEception or its parent, Exception.

It can throw any exception it would, but is should at least throw IOException or its parent

Observe that the rule for overriding a method is opposite to the rule for constructors. An overriding method cannot throw a superclass exception, while a constructor of a subclass cannot throw subclass exception (Assuming that the same exception or its super class is not present in the subclass constructor’s throws clause). For example:

179
Q

What is a virtual call

A

Call is bound to method at run time not compile time, this is true for all non-private and non-final instance method calls.

180
Q

comment on:

class A{
public void mA(){ };
}

class B extends A {
public void mA(){ }
public void mB() { }
}

A x = new B();
x.mB();

A

Will not compile because mB() is not defined in A

181
Q

What will the following code print?
int x = 1;
int y = 2;
int z = x++;
int a = –y;
int b = z–;
b += ++z;

    int answ = x>a?y>b?y:b:x>z?x:z;
    System.out.println(answ);
A

2

This is a simple but frustratingly time consuming question. Expect such questions in the exam.
For such questions, it is best to keep track of each variable on the notepad after executing each line of code.

The final values of the variables are as follows -
x=2 y=1 z=1 a=1 b=2

The expression x>a?y>b?y:b:x>z?x:z; should be grouped as -
x > a ? (y>b ? y : b) : (x>z ? x : z);

It will, therefore, assign 2 to answ.

182
Q

Given:

package strings;
public class StringFromChar {

public static void main(String[] args) {
    String myStr = "good";
    char[] myCharArr = {'g', 'o', 'o', 'd' };
    
    String newStr = "";
    for(char ch : myCharArr){
        newStr = newStr + ch;
    }
    boolean b1 = newStr == myStr;
    boolean b2 = newStr.equals(myStr);
    
    System.out.println(b1+ " " + b2);
    
} }

What will it print when compiled and run?

A

false true,

newString’s value is not determined at compile time, so at runtime new object will be created. It points to a different object than MyStr, even if it has the same value, so the == yields false.

183
Q

When question about making more encapsulated watch out for variable’s that are not needed because value already calculated by method (e.g. area variable can be ommited if there is a method that calculates it based on side variable). I.e. setters should be set in such a way that data members are consistent with each other.

A

….

184
Q

Valid?

try {
try {
Socket s = new ServerSocket(3030);
}catch(Exception e) {
s = new ServerSocket(4040);
}
}

A

No, first try does not have catch or finally block

185
Q

Valid?

try {
for( ;; );
}finally { }

A

Yes, try does need either a catch or finally block, but not necessarily both at the same time

186
Q

Valid?

int x = validMethod();
try {
if(x == 5) throw new IOException();
else if(x == 6) throw new Exception();
}finally {
x = 8;
}
catch(Exception e){ x = 9; }

A

NO, finally cannot appear before catch block

187
Q

Outcome?

What will the following program print?

class Test{
public static void main(String args[]){
int i=0, j=0;
X1: for(i = 0; i < 3; i++){
X2: for(j = 3; j > 0; j–){
if(i < j) continue X1;
else break X2;
}
}
System.out.println(i+” “+j);
}
}

3 0

or

33

A

33, because j is set to 3, because every first iteration of x2 is terminated it never decreases

188
Q

size array specified at left or right side?

A

right

189
Q

What will happen when the following program is compiled and run?

public class SM{
public String checkIt(String s){
if(s.length() == 0 || s == null){
return “EMPTY”;
}
else return “NOT EMPTY”;
}

public static void main(String[] args){
  SM a = new SM();
  System.out.println(a.checkIt(null));
} }
A

It will throw NullPointerException.
Because the first part of the expression (s.length() == 0) is trying to call a method on s, which is null. The check s == null should be done before calling a method on the reference.