OCAJP8 Flashcards

1
Q

If you invoke

System.out.println(exception);

will you see the stack trace on ths console?

A

No. Using System.out.println(exception) will NOT include the stack trace. It conly includes the name of the exception and the message.

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

True or False:

Static initializers can call static methods in their body.

A

True.

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

Is this a valid variable assignment?

int x, y, z, a; x = y = z = a = 15;

A

Yes. Variable assignments can be chained.

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

What will be the output of the following?

String s = null; s += “Hello”;

System.out.println(s);

A

The output will be “nullHello”. a String that is initialized as NULL is different from “”.

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

Given the following:

Integer x = new Integer(5);

x++;

Does the variable “x” still point to the same reference created in the the first line?

A

No. All the wrapper objects are immutable. So when you do x++, what actually happens is something like

x = new Integer( x.intValue() + 1);

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

Is Java using pass-by-value or pass-by-reference?

A

Java uses pass by value semantics in method calls. In case of primitive variables, their values are passed, while in case of Objects, their reference values are passed. Thus, when you assign a different object to reference variable in a method, the original reference variable that was passed from the calling method still points to the same object that it pointed to before the call.

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

Can the overriding method change the return type to a subclass of the original method?

A

Yes. Covariant returns are allowed since Java 1.5, which means that an overriding method can change the return type to a subclass of the return type declared in the overriden method.

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

When accessing static and instance variables, which class is being considered? Is it the reference or the actual instance?

A

Access to static and instance fields and static methods depends on the class of reference variable and not the actual object to which the variable points to.

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

When calling instance methods, which class is being considered? Is it the reference or the actual instance?

A

When calling instance methods, the method of the actual class of the the object is called.

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

Given the following call:

int x = 5; doOperation(x++);

What value of x will be passed to “doOperation”?

A

The value 6 will be passed. When there are operands in method parameters, they are first evaluated before calling the method.

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

What will the following code print?

void crazyLoop(){ int c = 0; JACK: while (c 3) break JILL; else c++; } }

A

It will not compile. Because break JILL; would be valid only when it is within the block of code under the scope of the label JILL. In this case, the scope of JILL extends only up till System.out.println(c); and break JILL; is out of the scope of the label.

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

Consider the following code:

class A{ A() { print(); } void print() { System.out.println(“A”); } }

class B extends A{ int i = 4;

public static void main(String[] args){ A a = new B(); a.print(); }

void print() { System.out.println(i); } }

What will be the output when class B is run ?

A

It will print 0, 4 Note that method print() is overridden in class B. Due to polymorphism, the method to be executed is selected depending on the class of the actual object. Here, when an object of class B is created, first A’s constructor is called, which in turn calls print(). Now, since the class of actual object is B, B’s print() is selected. At this point of time, variable i has not been initialized (because we are still initializing A at this point), so its default value i.e. 0 is printed. This happens because the method print() is non-private, hence polymorphic.

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

If an Exception is handled in a catch block and is not thrown, the execution continues.

A

If an Exception is handled in a catch block and is not thrown, the execution continues.

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

If the array reference expression produces null instead of a reference to an array, then a NullPointerException is thrown at runtime, but only after all parts of the array reference expression have been evaluated and only if these evaluations completed normally.

A

If the array reference expression produces null instead of a reference to an array, then a NullPointerException is thrown at runtime, but only after all parts of the array reference expression have been evaluated and only if these evaluations completed normally.

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

In Lambda Expressions, when is it required to put the method body inside curly braces.

A

In Lambda Expressions, you need to put the body within curly braces if you want to use the return keyword.

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

What does the add method of ArrayList return?

A

The add method of ArrayList returns a boolean. Further, it returns true if the list is altered because of the call to add.

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

Will an occurence of java.io.IOException be handled by a catch block that catches RuntimeException?

A

java.io.IOException extends Exception. It cannot be caught by a catch block that catches RuntimeException.

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

If there is an un-reachable code in a method, will it compile?

A

Un-reachable codes will cause compilation error except if it is inside an IF block.

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

Do ambiguous fields or methods cause compile time error?

A

Having ambiguous fields or methods does not cause any problem by itself but referring to such fields or methods in an ambiguous way will cause a compile time error.

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

Does a lambda expression create new scope for variables?

A

A lambda expression does not create a new scope for variables. Therefore, you cannot reuse the variable names that have already been used to define new variables in your argument list.

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

If an interface extends another interface with a default method, can it redeclare the default method?

A

An interface can redeclare a default method and also make it abstract.

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

If an interface extends another interface with a default method, can it redeclare the same default method and provide a different implementation?

A

An interface can redeclare a default method and provide a different implementation.

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

Can static methods be abstract?

A

Static methods can never be abstract (neither in an interface not in a class).

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

Is an interface allowed to have a static method?

A

An interface can have a static method but the method must have a body.

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

What are the default characteristis of every field in an interface?

A

Any field in an interface is implicitly public, static, and final, whether these keywords are specified or not.

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

Can a final variable be hidden in a subclass.

A

A final variable can be hidden in a subclass.

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

Will this compile?

String s = “hello”;

StringBuilder sb = new StringBuilder(“hello”);

booean areTheyTheSame = (s == sb);

A

No. Java does not allow you to compare String and StringBuilder using ==

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

In multi-dimensional arrays, which is required to have the size initialized?

A

In multi-dimensional arrays, only the first array is required to have the size initialized.

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

Are two ArrayList with the same content equal?

A

Two ArrayList with the same content are equal.

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

How many times and where is it allowed to set values for static final variables?

A

static final variables must be set exactly once, and it must be in the declaration line or in a static initialization block.

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

What is the result of the following expression?

new Boolean(“true”) == Boolean.TRUE

A

The expression will result to false because they point to two different Boolean wrapper objects.

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

Are two Array with the same content equal?

A

Two Array with the same content is not equal.

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

Does Java allow constructors with empty bodies?

A

Constructors cannot have empty bodies.

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

If a concrete class implements an interface and extends a class that implements another interface, is it required to implement all methods defined in an inherited interface?

A

A concrete class is NOT necessarily required to implement all methods defined in an inherited interface because some methods may have been already implemented by a superclass.

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

Which method implementaion will be called if you cast an instance to the interface with a default method?

A

Even if you cast an instance to the interface with a default method, the instance method will be run if it overrides the default.

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

When does an object become eligible for garbage collection?

A

An object can be made eligible for garbage collection by making sure there are no references pointing to that object.

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

When will the implementation of a hidden method be called in a subclass?

A

With hidden methods, the specific method used depends on where it is referenced.

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

Is it possible to hide protected and public methods?

A

Protected and public methods may be overridden, not hidden.

39
Q

Are private methods overriden or hidden in a subclass?

A

Private methods are always hidden in a subclass.

40
Q

Can static methods be overriden?

A

Static methods cannot be overriden, only hidden.

41
Q

Is it possible to override a variable in a subclass?

A

Variables may only be hidden, regardless of the access modifier.

42
Q

How can you invoke the garbage collector?

A

You cannot directly invoke the garbage collector. You can suggest the JVM to perform garbage collection by calling System.gc();

43
Q

Does an extra semi-colon at the end of a line cause compilation error?

A

Java compiler ignores an extra semi-colon because it is equivalent to an empty statement.

44
Q

Where can you put labels in Java code?

A

You can apply a label to any code block or a block level statement (such as a for statement) but not to declarations. For example: loopX : int i = 10;

45
Q

Can you call break and continue with label in a regular line inside a method?

A

Break and continue with labels are only valid if called from within the block of code.

46
Q

Which of the following are valid formatters?

  • LOCAL_DATE_TIME
  • ISO_LOCAL_DATE_TIME
  • ISO_DATE_TIME
A

LOCAL_DATE_TIME is not a valid formatter.

ISO_LOCAL_DATE_TIME is valid though, which is same as ISO_DATE_TIME except that it does not use the Zone or Offset.

47
Q

How can you enfore immutability in a Java Bean?

A

Immutability uses private instance variables.

48
Q

If the index part in an array operation contains an expression, what the the order or execution?

A

When working with arrays, the expression for the index is always evaluated first including checkign whether the array is NULL or not.

49
Q

What is the result of the following?

Integer myInt = new Integer(1);

Long mylong = new Long(1);

System.out.printlin(myInt == myLong);

A

The code will not compile. Using the operator == with two drifferent wrapper class types will cause compilation error.

50
Q

What is the result of the following?

Integer myInt = new Integer(1);

Long mylong = new Long(1);

System.out.printlin(myInt.equals(myLong));

A

The equals() operator will give FALSE if you compare two different wrapper class types even with the same values.

51
Q

Which is faster when accessing an element? Array or ArrayList?

A

Accessing an element in an Array is faster than in ArrayList.

52
Q

Which takes precedence? Importing by classname or using wildcards?

A

Importing by classname takes precedence over wildcards.

53
Q

Is this a valid code?

class Hello {

public void Hello(){};

}

A

Yes. Methods (with return type) having the same name as the class is allowed.

54
Q

Are static variables accessible in instance initializers?

A

Both instance and static initializers are able to access static variables

55
Q

Will this compile?

double amount = 0xE;

A

Yes. Hex values can be assigned to double.

56
Q

Where are underscores allowed in numeric literals?

A

Underscores are allowed in numbers as long as they are directly between two other digits.

57
Q

What is the assumption on interface methods without any access modifier?

A

Interface methods without any access modifier is always assumed to be public.

58
Q

Can a class inherit two interfaces that both define default methods with the same signature without overriding the method?

A

A class cannot inherit two interfaces that both define default methods with the same signature, unless the class implementing the interfaces overrides it iwth an abstract or concrete method.

59
Q

In a subclass constructor, if there is no explicit call to the parent constructor, what will be inserted as the first line?

A

In a subclass constructor, if there is no explicit call to the parent constructor, the default no-argument super() will be inserted as the first line.

60
Q

Does autoboxing apply in Predicates?

A

Autoboxing does not work with Predicates

61
Q

Where is synchronized keyword used?

A

Synchronized keyword is only for metods and blocks

62
Q

What will the following code produce?

LocalDate myDate = LocalDate.of(2015, Calendar.January, 1);

A

The code will throw an exception. In the new Date API, months are indexed staring 1 so using the static fields from Calendar will cause trouble.

63
Q

Can you shadow instance variables in loops and methods?

A

Instance variables can be shadowed in loops and methods.

64
Q

In Encapsulation, what can be done to lists/collections in getter methods if you need to protect the contents?

A

In Encapsulation, it is good to return copies of lists/collections in getter methods if you need to protect the contents.

65
Q

Does Java allow arrays of length zero to be created?

A

Java allows arrays of length zero to be created

66
Q

Can bitwise operators (&, |, ^) have integral operands?

A

Bitwise operators (&, |, ^) can have integral as well as boolean operands

67
Q

Can an overriding method declare that it can throw a superclass of the exceptions the overridden method can throw?

A

An overriding method only needs to declare that it can throw a subset of the exceptions the overridden method can throw. Having no throws clause in the overriding method is OK.

68
Q

Describe a Functional Interface.

A

A Functional Interface must have exactly one abstract method and may have other default or static methods.

69
Q

What does the operation -1 do?

A

The operation -1 in binary would be: complement the bits for 1 and add 1

70
Q

What does the leftmost bit in a binary integer represent?

A

The leftmost bit in a binary integer is the sign bit which is 1 for negative and 0 for positive

71
Q

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

A

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T is a class and an instance of T is created.
  • T is a class and a static method declared by T is invoked.
  • A static field declared by T is assigned.
  • A static field declared by T is used and the field is not a constant variable.
  • T is a top-level class, and an assert statement lexically nested within T is executed.
72
Q

According to the Java Language Specification, what is the rule when acessing protected members in a subclass on a different package?

A

A protected member is inherited by a subclass and it is therefore accessible in the subclass. However, In the words of Java Language Specification, protected members of a class are accessible outside the package only in subclasses of that class, and only when they are fields of objects that are being implemented by the code that is accessing them. Basically, it implies that a protected member is accessible in the subclass only using a reference whose declared type is of the same subclass (or its subclass).

73
Q

Is an empty switch block is a valid construct?

A

An empty switch block is a valid construct.

74
Q

When valueOf is called in wrapper classes, does auto-boxing apply?

A

When valueOf is called in wrapper classes, auto-boxing does not apply

75
Q

What happens when you pass a primitive type to a method?

A

When you pass a primitive type to a method, it is passed by value. Thus, a copy of the argument is made, and what occurs to the parameter that receives the argument has no effect outside the method.

76
Q

What is the effect of calling the method intern() in concatenated strings?

A

Concatenating strings results in a new String object. Calling the intern() method removes duplicates in string pool:

77
Q

If a catch block throws an exception and the finally block throws a dirrent exception, which one will be thrown?

A

If a finally block throws an exception, that is the one printed regardless of the one thrown in a catch block.

78
Q

When are you required to use a finally block in a regular try statement?

A

When there are no catch blocks in a try statement.

79
Q

Which of the following exceptions are thrown by the JVM?

  • ArrayIndexOutOfBoundException
  • ExceptionInInitializerError
  • java.io.IOException
  • NullPointerException
  • NumberFormatException
A

The following exceptions are thrown by the JVM:

  • ArrayIndexOutOfBoundException
  • ExceptionInInitializerError
  • NullPointerException
80
Q

Can a method throw Runtime exceptions without declaring it in the throws section?

A

Runtime exceptions can be thrown in any method even without the thows declaration.

81
Q

What will the following class print ?

class Test {

public static void main(String[] args){

int[][] a = { { 00, 01 }, { 10, 11 } };

int i = 99;

try { a[val()][i = 1]++; } catch (Exception e) { System.out.println( i+”, “+a[1][1]); } }

static int val() throws Exception { throw new Exception(“unimplemented”); } }

A

[99, 11]

If evaluation of a dimension expression completes abruptly, no part of any dimension expression to its right will appear to have been evaluated.
Thus, while evaluating a[val()][i=1]++, val() throws an exception and i=1 will not be executed. Therefore, i remains 99 and a[1][1] will print 11.

82
Q

Is this valid?

int[10] iA;

A

No. Size of the array is NEVER specified on the Left Hand Side

83
Q

What is the default length of the args parameter in the public static void main method if the code is run without any arguments?

A

Remember that the args array is never null. If the program is run without any arguments, args points to a String array of length 0.

84
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

It will print “QBANK”

A reference to a static field causes initialization of only the class or interface that actually declares it, even though it might be referred to through the name of a subclass, a subinterface, or a class that implements an interface.

85
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 that the cast (long) applies to ‘by’ not to the whole expression.

86
Q

Which of the following statements will evalutae to true?

  • “String”.replace(‘g’,’G’) == “String”.replace(‘g’,’G’)
  • “String”.replace(‘g’,’g’) == new String(“String”).replace(‘g’,’g’)
  • “String”.replace(‘g’,’G’)==”StrinG”
  • “String”.replace(‘g’,’g’)==”String”
A

“String”.replace(‘g’,’g’)==”String”

There are 2 points to remember:

  1. replace() method creates a new String object.
  2. replace() method returns the same String object if both the parameters are same, i.e. if there is no change.
87
Q

Given:

byte b = 1; char c = 1; short s = 1; int i = 1;

Which of the following expressions are valid?

  • s = b * b;
  • i = b + b;
  • s *= b;
  • c = c + b;
  • s += i;
A

The following are valid:

  • i = b + b;
  • s *= b;
  • s += i;

All compound assignment operators internally do an explicit cast.

88
Q

What are the casting rules for primitives?

A

Remember these rules for primitive types:

  1. Anything bigger than an int can NEVER be assigned to an int or anything smaller than int ( byte, char, or short) without explicit cast.
  2. CONSTANT values up to int can be assigned (without cast) to variables of lesser size ( for example, short to byte) if the value is representable by the variable.( that is, if it fits into the size of the variable).
  3. operands of mathematical operators are ALWAYS promoted to AT LEAST int. (i.e. for byte * byte both bytes will be first promoted to int.) and the return value will be AT LEAST int.
  4. Compound assignment operators ( +=, *= etc) have strange ways so read this carefully.
89
Q

Will the following code compile?

public class FunWithArgs {
 public static void main(String[][] args) {
 System.out.println(args[0][1]);
 }
 public static void main(String[] args) {
 FunWithArgs fwa = new FunWithArgs();
 String[][] newargs = {args};
 fwa.main(newargs);
 }
}
A

There is no problem with the code. The main method is just overloaded.
When it is run, the main method with String[] will be called. This method then calls the main with String[][] with an argument { {“a”, “b”, “c”} }
Thus, args[0][1] refers to “b”, which is what is printed.

90
Q

You want to print the date that represents upcoming tuesday from now even if the current day is a tuesday. What are the 2 ways to accomplishthis?

A

You can accomplish it by:

  • System.out.println(LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.TUESDAY)));
  • System.out.println(TemporalAdjusters.next(DayOfWeek.TUESDAY).adjustInto(LocalDate.now()));
91
Q

What will be the values of a ,b, and c after the following statement?

boolean bool = (a = true) || (b = true) && (c = true);

A

a = true

b = false

c = false

Java parses the expression from left to right. Once it realizes that the left operand of a conditional “or” operator has evaluated to true, it does not even try to evaluate the right side expression.

92
Q
A
93
Q

What is the output of the following?

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
It will not compile. Observe that play() in Game declares Exception in its throws clause. Further, class Soccer overrides the play() method without any throws clause. This is valid because a list of no exception is a valid subset of a list of exceptions thrown by the superclass method. 
Now, even though the actual object referred to by 'g' is of class Soccer, the class of the variable g is of class Game. Therefore, at compile time, compiler assumes that g.play() might throw an exception, because Game's play method declares it, and thus expects this call to be either wrapped in a try-catch or the main method to have a throws clause for the main() method.
94
Q

What is wrong with the following code?

public String getDateString(LocalDateTime ldt){
return DateTimeFormatter.ISO_ZONED_DATE_TIME.format(ldt);
}

A

Note that LocalDateTime class does not contain Zone information but ISO_ZONED_DATE_TIME requires it. Thus, it will throw the following exception:

Exception in thread “main” java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: OffsetSeconds

UnsupportedTemporalTypeException extends DateTimeException.