Java oca Flashcards
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);
}
}
true, false, false
Java parses expression from left to right, mind the short circuit operators. The && operator is not performed.
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.
It will fetch the overriding method from subclass, fields are from superclass, static methods are also fetched from declared class.
C b1 = (B) b1; Why will this not compile
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.
Can LocalDate(Time) be constructor like, new LocalDAte()?
No, because LocalDate(Time) as only private constructors. You need to use one of its static methods instead.
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)));
The first one, LocalDAte has a .with operator, but not .adjust.
For instanting of object, which constructors run, from reference type or actual object. Which constructor(s) run first, super or child class.
Actual object and superclass (always, if not excplicit implicit, super() call).
Why won’t this run:
Class A{
A(int i){some code};
}
Class B extends Class a{}
Because Class B’s (implicit) constructor will make implicit super() call.
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?
False false, True false, none, because if false the second if, and thus not the first else, will not be entered.
What will be the content of newargs?
FunWithArgs fwa = new FunWithArgs();
String[][] newargs = {args};
{{“a”, “b” , “c”}}
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?
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)
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.
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.
Can an overiding method throw any exception?
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.
What is correct order of initialization:
- 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. - non static constants, variables, and blocks.
- constructor.
int i = 5;
float f = 5.5f;
float f2 = 5.0f;
What is the outcome of:
i == f;
i == f2;
I will be promoted to float, so 5.0. So false and true.
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.;
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.
int i =5;
float f =5.5f;
double d = 3.8;
outcome of:
(int) (f + d) == (int) f + (int) d;
becomes 9 ==8, so false.
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);
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.
In switch block, does default to be at the end of all case options?
no
Can main method refer to this.x?
No, main method is static, so it cannot reference instance fields directly, it can only do so by creating an object.
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
}
}
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).
Which of these are not part of StringBuilder Class:
trim();
ensureCapacity(int);
append(boolean);
reverse();
setlength(int);
Trim(), it is only part of String.
byte b = 2;
short s= 2;
? x = s * b;
What would be the outcome, which data type
int 4, because anything lower than int will be converted to int in arithmetic operator.
int i = 1;
short s = 2;
s += i; //what would be the outcome?
3, compound assignment operators have implicit cast, and 3 fits in short.
Does “String”.replace(‘g’, ‘G’) create a new object.
and “String”.replace(‘g’, ‘g’)?
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
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();
}
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.
Whether casting works, determined at compile time or runtime
runtime, but assingment without casting at compile time. THis means, for the latter, that reference type matters, not actual object.
What should be the return type of the following method?
public RETURNTYPE methodX( byte by){
double d = 10.0;
return (long) by/d*3;
}
double, note cast only applies to by
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?
QBANK,
No static method or field of Sub itself is invoked, to its static initializer block does not run.
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
Because of line to, you cannot put something on third position when ArratyList has only one value yet, it needs at least two
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; } );
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.
Can break apply to if/else
No, if it has break statement is should be applied to outer constructor (switch or for loop)
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 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.
why doesn’t this work:
Short k = new Short(9); System.out.println(k instanceof Short);
9 is an int, and Short contains no constructor taking int.
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();
}
}
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.
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.
Yes
String f = “12.3”;
int i = Integer.parseInt(f);
Does this run without exception
No, numberformatexception because 12.3 is not an integer.
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() );
}
}
43
Which three modifiers cannob be applied to a constructor.
final, static, abstract
Test(Test b){}
Is this a valid constructor
Yes, constructor can take it’s own type as parameter
why doesn’t this work?:
new Object[1]{ new Object() };
You cannot specify array length if you initialize at the same place
Does String class have append and insert method?
No, because of being immutable
Which datatypes can be used in switch variable
byte, char, short in String, enums, Byte, Character, Short, and Integer.
Long, float, double and boolean are not allowed.
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;
}
}
7, it will always return 7
Can a catch block come after finally block
no
if (true) { break ; } (When not inside a switch block or a loop)
Will this compile?
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.
Will this work?
label: if(true){
System.out.println(“break label”);
break label;
}
Yes, break cannot be in if else, unless it is nested in loop construct or when if statement has label.
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”);
}
}
}
Double cannot be used in switch statement
Has overrding method to have to same acces level as overridden method?
No, it can be less restrictive. I.e. protected instead of default
Covariant return type for overriding means
Overriding method can also return subclass of return type overridden class
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()
- true, object –> abstractCollection –> AbstractList –> ArrayList
- true, not like linkedList where you have to go through every element before the element you want to get.
- false
- False
- true
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] ] );
}
}
1
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”);
}
}
}
For is a keyword so cannot be used for label.
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]); } }
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
Can final variable be hidden?
Yes
int a = b = c = 100;
Is this valid
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.
Are primitives and objects being passed by value?
Yes, both are
Will this one not compile or throw exception
public class TestClass{
public static void main(String args[]){
Exception e = null;
throw e;
}
}
not compile, because it is throwing an exception without the method not having a throws clause or handling it.
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));
}
}
5, because it uses a local variable that has not been initialized at compile time (it is not a constant).
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
}
}
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.
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”); }
}
Only line 1, but not 2 or both. A static method cannot be hidden/overidden by a non static method.
can charAt() take a char as argument?
What will charAT() return
Yes, because it is implicitly promoted to int.
char (primitive).
System.out.println(‘b’+new Integer(63));
prints 98, char is a numerical value
Does polymorphism make the code more efficient? And more dynamic?
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.
why not compile?
abstract class A{
protected int m1(){ return 0; }
}
class B extends A{
int m1(){ return 1; }
}
B does not override correct, it reduces accesibility.
At which places can a final variable be intialized.
right, away, instance initializer, any constructor.
Static variable cannot be initialized in constructor.
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?
true
ArrayList<Double> al = new ArrayList<>();
al.add(111);</Double>
Does this work?
No, na widening plus autoboxing.
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?
-10
Note that int x3 = ++x2; affects x2 as wel
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 ;
}
return after finally block not reachable.
class B { B(){ } }
Is this a default constrcutor?
No
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+” “); }
}
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.
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 …
weak encapsulation
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;
}
}
Does not compile, second break is not in loop where label is declared.
Precedence, dot operator or cast operator
dot operator.
public class TestClass{
int a;
int b = 0;
static int c;
public void m(){
int d;
int e = 0;
d++ }
}
outcome
outcome, d is not yet initialized, does not have default value.
Outcome?
public class TestClass {
public static void main(String[] args){ int k = 2; while(--k){ System.out.println(k); } } }
While condition does not evaluate to boolean, so does not compile
Which of these classes is not final
System, Number, Boolean, String, StringBuilder
Number