Core Java Questions
Interview Questions
1. Can a class be declared as final??
Yes, a class can be declared final; that is, the class cannot be sub-classed. This is done for security and design.
2. Are instance variables assigned a default value?
Yes, member or instance variables are always given a default value.
3. Can you compare a boolean to an int?
No, booleans are true and false keywords and nothing else.
4. Can the access specifier for an overriding method allow more or less access than the overridden method?
More. The access specifier for an overriding method can allow more, but not less, access than the overridden method.
5. What is the difference between the default and protected access specifier?
Default does not allow sub class access. Both allow package access.
6. What are the access levels in order of most restrictive to least?
Class, Package, Sub class, and World.
7. What are the access specifiers in order of most restrictive to least?
Private, Default, Protected, and Public.
8. When you pass a variable as an argument to a method call, what are you passing?
A copy of the value. You always get a copy of whatever is in the variable - either a primitive or a reference. So for objects, you get a copy of the reference.
9. What does break do?
The break statement has two forms: labeled and unlabeled. An unlabeled break statement terminates the innermost switch, for, while, or do-while statement, but a labeled break terminates an outer statement.
10. What does continue do?
The continue statement skips the current iteration of a for, while, or do-while loop. The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. A labeled continue statement skips the current iteration of an outer loop marked with the given label.
11. Where can an anonymous inner class be defined?
An anonymous class is an expression. So anywhere an expression is used.
12. Can overriding methods throw different exceptions than that of the super?
Overriding methods cannot throw any new or broader exception that is checked. Unchecked does not apply.
13. Can a private method be overridden?
No, but the can be re-declared in the subclass. This is not polymorphism.
14. Can a private method be overridden?
No, but the can be re-declared in the subclass. This is not polymorphism.
15. Does each source file need a public class in it?
No.
16. What access is the generated constructor given when one is not supplied?
If the class is public, than it is public. Otherwise the default constructor is default.
17. What is the keyword transient?
It marks a member variable not to be serialized when it is persisted to streams of bytes.
18. What is the keyword native?
The native keyword is applied to a method to indicate that the method is implemented in native code using JNI.
19. Will this line compile without errors?
Object obj = new Object ();
Yes.
20. Will this line compile without errors?
Object [ ] obj = new Object [7];
Yes.
21. Will this line compile without errors?
Object obj [ ] = new Object [7];
Yes.
22. Will this line compile without errors?
Object obj [ ] = {new Object(), new Object()};
Yes.
23. Will this line compile without errors?
Object obj [ ] = {new Object [1], new Object [2]};
Yes.
24. Will this line compile without errors?
Object [ ] obj = new Object ();
Incorrect because they have () instead of [] after the type.
25. Will this line compile without errors?
Object obj [ ] = new Object() ;
Incorrect because they have () instead of [] after the type.
26. Will this line compile without errors?
Object [ ] obj = new Object [ ];
Incorrect because they do not assign a size to the array.
27. Will this line compile without errors?
Object obj [ ] = new Object[ ] ;
Incorrect because they do not assign a size to the array.
28. Will this line compile without errors?
Object [ ] obj = new Object [3]();
Incorrect because the () after the [] is not the correct syntax.
29. Will this line compile without errors?
Object obj [ ] = new Object [3]();
Incorrect because the () after the [] is not the correct syntax.
30. Will this line compile without errors?
Object [8] obj = new Object [ ];
Incorrect because the size is not assigned when it is declared.
31. Will this line compile without errors?
Object [7] obj = new Object [7];
Incorrect because the size is not assigned when it is declared.
32. Will this line compile without errors?
Object [3] obj = new Object [3]() ;
Incorrect because the size is in the declaration and the extra () after the [] is not the correct syntax.
33. Will this line compile without errors?
Object obj [] = new {new Object(), new Object()};
Incorrect because the first new operator is being used with the {} initialization method.
34. What best describes the result of the following code segment? The ArrayList sampleArrayList has already been declared and initialized.
int i = 63;
sampleArrayList.add(i);
The int is converted to an Integer via auto boxing and then placed into the ArrayList. Primitives cannot be stored in an ArrayList. However, if they are placed into their primitive wrapper class they can be stored. Java will automatically make that conversion via its autoboxing feature if a primitive is placed into an ArrayList.
35. Will this line compile without errors?
double[ ][ ][ ] numbers = new double[ ][ ][ ];
No. When the new operator is used, at least one array dimension in a multi-dimensional array must be given a size.
36. Will this line compile without errors?
double[ ][ ] numbers = {{1,2,3},{7,8},{4,5,6,9}};
Yes.
37.Will this line compile without errors?
double[ ][ ][ ] numbers = new double[7][ ][ ];
Yes.
38. Can a constructor have a synchronized modifier?
No; they can never be synchronized.
39. What is the output of the following code segment?
int value = 1;
switch (value) {
case 0:
System.out.println("Dog");
case 1:
System.out.println("Cat");
case 1:
System.out.println("Fish");
default:
System.out.println("Cow");
}
This will not compile because it includes a case statement with the same value twice.
40. Can a constructor be declared static?
No, constructors are for creating new instance objects. Static methods are for non-instance code, so it makes no sense to have a static constructor.
41. Can a top-level class be marked as protected?
No, a top-level class can only be marked public or default. The protected access is just for member variables and methods, and allows subclasses outside the superclass package to inherit the protected members.
42. Can a constructor be declared private?
Yes. This can be used to control the creation of the object by other less restrictive methods.
43. True or False - during arithmetic, when the operands or different types, the resulting type is always the widest of the two type.
False, the result of an arithmetic operation on any two primitive operands will be at least an int -- even if the operands are byte and short.
44. If break statements are not used in a switch, what will happen?
Once a case statement is entered, the code will continue to execute in each case below it, until it hits a break statement.
45. Given:
public void simpleTest () {
int i;
System.out.println(i);
}
What will occur?
A compiler error will occur since the value has not been initialized.
46. Which of the following are interfaces to ArrayList? List, Map, Queue, RandomAccess, and Set.
List and RandomAccess are interfaces to ArrayList.
47. Fill in the blank. Import statements are ______.
Required in all versions of Java.
48. What will be printed?
System.out.println("roberto".replaceAll("o", "!").substring(1, 7));
!bert!
49. What will be printed? System.out.println("roberto".substring(3, 7));
erto
50. What will be printed? System.out.println("roberto".replaceAll("o","!").substring(1, 6));
!bert
51. What will be printed? System.out.println("roberto".replaceAll("o", "!").substring(2, 7));
bert!
52. What version of Unicode is supported by Java SE 7?
Unicode standard, version 6.0.0
53. True or False, octal literals must start with a 0.
True
54. True or False, octal literals can start with \u.
False
55. True or False, octal literals can start with \x.
False
56. In the following code segment, how many times will an even number be sent to standard out?
for (int x = 0; x < 10; x++){
if (x % 2 == 0) {
System.out.println("x: " + x + " - Even");
continue;
}
else {
System.out.println("x: " + x + " - Odd");
}
x++;
}
1 time
57. What is the new method of the Locale class to Java SE 7?
The getUnicodeLocaleAttributes method was introduced to the Locale class in JDK 1.7 along with the getDefault, setDefault, getScript, getExtension, getExtensionKeys, getUnicodeLocalType, getUnicodeLocaleKeys, toLanguageTag, forLanguageTag, and getDisplay script. It's presented here to stress your need to be familiar with the Javadoc documentation of the Java API specification.
58. What is missing from the following multi-dimensional array declaration:
int[][] array = int[10][10];
The new keyword is needed to establish memory allocation.
59. What is the last value that is sent to standard out for x in the given code segment?
int x = 0;
do {
x = x+2;
System.out.println("x: " + x);
}
while (--x < 5);
x: 6 The do while statement will increment x by 2 each time through the loop, and then, before it checks the while condition, it will first decrement it by 1.
60. How can this interface be correctly implemented?
public interface TestInterface {
public boolean errorState();
}
public class ClassX implements TestInterface {
public boolean errorState() {
return false;
}
}
// An object can act as any interface it implements.
// and
public class ClassX implements TestInterface {
private boolean errorState() {
return false;
}
}
An object can also act as any of its superclasses.
61. What is the primitive storage range of a byte?
-128 to 127
62. java.io.Serializable is a marker interface, also known as a tag interface. What is the unique attribute of marker interfaces?
A marker interface includes no methods or fields.
63. Which literal data types must be cast in order to work with an int data type?
Literals of type long, float, and double must be explicitly cast to an int to be used with a variable of the type int.
64. InterruptedIOException is a subclass of?
IOException
65. ClassNotFoundException is a subclass of?
ReflectiveOperationException
66. IllegalAccessException is a subclass of?
ReflectiveOperationException
67. NoSuchMethodException is a subclass of?
ReflectiveOperationException
68. Which access modifiers can be applied to constructors?
Constructors can have package-private, private, protected, and public access modifiers applied to them.
69. If you want to define an unchecked exception, your exception must extend (directly or indirectly) which class?
If you want to define an unchecked exception, your exception must extend the RuntimeException class.
70. Which lines will not compile?
Integer luckyNumber = 66;
System.out.println(luckyNumber.booleanValue());
System.out.println(luckyNumber.charValue());
System.out.println(luckyNumber.byteValue());
System.out.println(luckyNumber.shortValue());
System.out.println(luckyNumber.longValue());
System.out.println(luckyNumber.floatValue());
System.out.println(luckyNumber.doubleValue());
Lines two and three will not compile, because you cannot convert the Integer wrapper class to a boolean or char primitive. For the Integer class, the methods booleanValue and charValue do not exist.
71. Will this compile?
int ivar = 77;
Integer integer = ivar;
Primitives and their wrapper classes are automatically converted back and forth with autoboxing and auto-unboxing.
72. Which method of the Stringbuilder class attempts to reduce storage used for the character sequence?
The trimToSize method attempts to reduce storage used for the character sequence.
73. Which statement is correct?
ArrayList d1 = new ArrayList();
ArrayList d2 = new ArrayList<>();
ArrayList<> d3 = new ArrayList<>();
ArrayList<Double> d4 = new ArrayList<>();
ArrayList<Double> d5 = new ArrayList<Float>();
The declarations for d1, d2, and d4 are valid as they will compile.
74. Running out of Java heap memory is an example of what?
Running out of heap memory results in a java.lang.OutOfMemoryError unchecked error.
75. What is the value for the variable sum?
int[][] sampleArray = new int[3][4];
for (int i = 0; i < 3; i++) {
sampleArray[i][i+1] = 2;
}
int sum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
sum += sampleArray[i][j];
}
}
4
76. Is this valid?
Object [] o = {"Song Book", 35.95, new Guitar(), 6};
Yes, it is fine to have subtypes as elements in an array of a supertype.
77. Is this valid?
short s = 1000s;
There is no s postfix.
78. Java 7's Garbage-First (G1) garbage collector is planned as the long-term replacement of which collector?
Java 7's Garbage-First (G1) garbage collector is planned as the long-term replacement of the Concurrent Mark-Sweep (CMS) collector.
79. If a variable is cast to an invalid object, what is the effect?
This will cause a runtime exception to be thrown.
80.
int b1 = 0b_0101_0101_0101_0101;
int b2 = 0b_1010_1010_1010_1010;
int b3 = b1 & b2;
System.out.println("Value:" + b3);
What will be the result?
A compilation error will occur because an underscore cannot be used after the b in the literal. The other underscores are allowed.
81. Is this valid?
static final long APHELION = 152,097,701;
Commas are not allowed in numeric literals, so a compiler error will occur.
82. Can a member variable be declared synchronized?
No, the keyword synchronized marks method code so that it cant be run by more than one thread at a time.