Sie sind auf Seite 1von 12

POINTS TO BE TAKEN CARE IN SCJP :

1. Sleep, join and wait method in thread throws InterruptedException, so


any call to these methods must be surrounded by try/catch block.

2. If null is passed in a call to method, where there are two overloaded


methods having argument of types String and Object, method with String
pay per click advertising
arg will get preference over the method with Object arg. If method with
String arg is not present, method with Object arg will be called.

3. Float.NaN == Float.NaN is false

4. Put(key,value) method in HashMap returns previous value assigned to


that key. (null if there was no key)

5. When a class is loaded always static variables are initialized before non
static variables.

6. If one thread is executing a method synchronized on one object lockA,


other threads cannot execute the methods/block that are also synchronized
on the same object - lockA. Because if method foo is synced on object
lockA and is getting executed by one thread, lock to object lockA would not
be available to any other thread untill execution of method foo gets
completed. (An object has only one lock - if it is used by some thread any
other thread have to wait untill its get released by previous thread using the
same lock)

7. A char can be assigned an integer. ie. char a = 5; is true.

8. Command line arguments starts after class name. ie. if test is class name,
java test 2 will have args.length = 1 and args[0] = 2.

9. Math class cant be instantiated, constuctor of Math class is private.

10. If a class has to behave properly with all java collection and interfaces,
it must have implemented following methods correctly. The collection
classes internally use these two methods of objects for performing various
collection operations.

public int hashCode()


public boolean equals(Object obj)

Reflexivity rule: An object must be equal to itself. (In case of composite


21. Divide by zero will cause an exeption ONLY with integer arithmetic. Floating point
arithmetic will simply assign the result to be infinity and no exeption will be thrown.
(System.out.println(3.0/0); will print 'Infinity')

22. System.exit(n) and finally cannot be used together. The System.exit() method calls the
Runtime.exit() method, which calls shutdown hooks and then terminates all running
threads, without executing evn finally method.

If you have something important that you need to do upon exit, you would be better off
putting it into a finalizer or into a shutdown hook. You can create a shutdown hook as
Thread, and register it with runtime.getRuntime().addShutdownHook().

23. Intantiating a thread doesn't start the execution. A call to start() method is required to
start a thread. Even after call to start() thread might not start executing. call to start() only
makes a Thread ready to be called.

24. && and || are short-circuit operators. It will evaluate both the operands only if
necessary.

25. & and | always evaluate both the operands regardless of anything.

26. The yield() method of Thread is called by currently running thread to allow another
thread of the same or higher priority to run. The selection of the thread will depend on the
underlying operating system and the threading algorithm of the JVM.

27. A final member method can not be overridden but it can be accessed from the subclass
- it is still inherited

28. Defining a method in a subclass with the same signature of a method in the superclass
is allowed, but if a method in super class is declared final then it will cause a compiler
error.

29. Defining a method in the subclass with the same signature as the parent's private
method is allowed. The subclass doesn't know about not only private method but any
private member of parent - it's private to the parent class.

30. Private constructors are legal and often quite useful. Final constructors are illegal. A
constructor is never inherited so marking it as final is just plain silly. Instances could still
be created from within the class, but not from outside of the class.

31. Private constructors are used in Singleton pattern. The Singleton pattern allows you to
control the instantiation of an object. In general, it is used when you want to ensure that
there is only one instance of an object and everyone uses that same instance. (You can
have some method like getInstance() which returns the already created instance of the
class, which would be static)

32. Casting to an Interface is ALWAYS OK at compile time, but not casting to a class.

"If S is a class type: ... If T is an interface type: ... If S is not a final class (§8.1.1), then the
cast is always correct at compile time (because even if S does not implement T, a subclass
of S might).

"If S is a class type: ... If T is a class type, then S and T must be related classes-that is, S
and T must be the same class, or S a subclass of T, or T a subclass of S; otherwise a
compile-time error occurs."

33. Everyone knows that an int is 32 bits in Java. However, it's important to realize that
only 31 of those bits actually contain the number. For example, Integer.MAX_VALUE
returns 2^31 - 1, not 2^32 - 1. The most significant bit (the one furthest to the left) is a
"sign" bit. It tells you if the number is positive or negative: a 0 means this is a positive
number, a 1 means this is a negative number.

11111111 11111111 11111111 11110110

In Java, negative numbers are stored in two's complement. In order to determine what this
value really is, we have to flip all of the bits and then add 1.

11111111 11111111 11111111 11110110 // Original Value


00000000 00000000 00000000 00001001 // Flip the Bits
00000000 00000000 00000000 00001010 // Add 1
Here 1010 is 10 in decimal so our original value represents -10 in binary.

34. The rules that hashCode values must abide by. You can find these in the Java API Spec
for Object.

- Whenever it is invoked on the same object more than once during an execution of a Java
application, the hashCode method must consistently return the same integer, provided no
information used in equals comparisons on the object is modified. This integer need not
remain consistent from one execution of an application to another execution of the same
application.

- If two objects are equal according to the equals(Object) method, then calling the
hashCode method on each of the two objects must produce the same integer result.

- It is not required that if two objects are unequal according to the


equals(java.lang.Object) method, then calling the hashCode method on each of the two
objects must produce distinct integer results. However, the programmer should be aware
that producing distinct integer results for unequal objects may improve the performance of
hashtables.

35. An inner class just can't exist without an instance of its enclosing class. You can never
create an instance of InnerClass without first creating an instance of EnclosingClass.
InnerClass is forever bound to EnclosingClass.

------------- Declaration and access control --------------

36. [] ; or []; both are valid array declarations. is just a reference variable that can denote
array of type .

37. default initialization value for array is null. default element value is as per default
value of the element type.

38. Each array object has a final field called length (thats why its not expandable), which
specifies the array size, that is, the number of elements the array can accommodate.

Prev- Next
39. Example of valid declaration & initialization of multi dimentional array...

Pizza[] pizzaGalore[] = {
{ new Pizza(), null, new Pizza() }, // 1. row is an array of 3 elements.
{ null, new Pizza()}, // 2. row is an array of 2 elements.
new Pizza[1], // 3. row is an array of 1 element.
{}, // 4. row is an array of 0 elements. null // 5. row is not constructed. };

40. When JVM invoke a static method on an instance, it don't take into account what that
instance is. Rather, it only consider the type of the variable used.

Example: Assume class ContainsStaticMethods has one static method called doIt.
ContainsStaticMethods c = new ContainsStaticMethods();
ContainsStaticMethods.doIt();
c.doIt();
c = null;
c.doIt(); // this statement will not throw
NullPointerException, but succesfully execute the method doIt().

Here the compile-time type of the variable c is going to be used to invoke the method
doIt(). It doesn't matter that c references null in the last case - all it cares about is the type
of c which is ContainsStaticMethods.

41. Inner Class (non-static member class) and Nested Class (static member class)

- There is no such thing as a Static Inner Class. If a class is defined within another class
and it is marked with the static modifier, it is not an inner class. Rather, it is called a
nested class.

- You don't need to create an instance of the enclosing class first because a nested class is
associated only with it's enclosing class, not with an instance of that class. Because of this,
you also can not access instance members of that enclosing class like InnerClass could
previously. It is quite possible to create an instance of NestedClass without an instance of
EnclosingClass so it just wouldn't make any sense to access instance variables of
EnclosingClass from such a context. A nested class can, however, access static members
(even private ones) of its enclosing class.

In addition to the lack of a bond between this instance and an instance of its enclosing
class, a nested class can declare static members (unlike inner classes, which can not).

- Access to local variables is allowed as long as the variable is declared final. If the
variable is not final, it can not be accessed from within the anonymous class.

- With an anonymous class, we can't have a constructor. We can, however, make use of the
instance initializer block.

- In Java, every class has a name, including anonymous classes. With anonymous classes,
however, that name is automatically generated. By using the line
"this.getClass().getName()".

42. Forward reference to variable on RHS of assignment is only allowed THROUGH


methods. But in that case as the referenced variable is not initialized, default value of the
variable will be taken.

int i = peek(); // ALLOWED. But default value of j (0) would be taken.c int peek()
{ return j; }
int j = 1;

43. Unicode escapes are interpreted very early by javac. As a result, using the escape
Unicode literals to express a line termination character such as carriage return or line feed
results in an end-of-line appearing before the terminal single quote mark.

(So, '\u000a' converts into '[LF]'resulting into compilation error. Simillarly '\u000d' would
be converted to '[CR]'

So use of Unicode escapes for Carriage Return (CR) and Line Feed (LF) will cause
compilation error. Use '\n' and '\r' instead.

44. All 'int' literals are assignable to lesser range primitive types char/short/byte provided
the value of the 'int' literal is within the range of the left hand side var type.

byte b = 100; // valid


byte b = 1000; // invalid
char c = 1000; // valid
char c = 66000; // invalid (Max limit of char is 65535)
45. '+' operator in java is overloaded for String objects for concatanation. i.e. String t =
"xyz"; then t = t+t; is valid (concatanation)

46. sleep() is a static method of the Thread class. sleep has two overloaded methods.
sleep(long miliseconds);
sleep(long miliseconds, long nanoseconds);

47. Method intValue() is only implemented in those Wrapper Classes which extend
java.lang.Number (Byte, Integer, Float and Double)

48. Abstract methods and native methods can't have a body.

49. If a class has a constructor defined other than default one, compiler would not insert
the default zero argument constructor. Compiler will insert the default constructor only if
class doesn't have any constructor defined. 50. If b is a boolean, b = false/true, returns
boolean. so if(b=true){...} is a valid if statement. (here, if b is of any type other than
boolean, it would cause compilation error)

51. Math.random() method returns a double number between 0 and 1.

52. In a class, you cant have any statment other than declaration outside of any
block/method.

53. Emply try/catch block will compile without any error.

54. Garbage Collection can never be forced. You can only request JVM to do so by calling
methods System.gc or Runtime.gc(), but it doesn't guarantee that the garbage collection
will occur because some other thread with higher priority may stop this thread for a while.

55. Argument of switch statment can be any expression which evaluates to an int.

56. Argument of case statement can be any constant expression which evaluates to an int.
2+1 is a constat expression, but i+1 is not.

57. Any class derived from an abstract class must either define all of the abstract methods
or be declared abstract itself.

58. All the Wrapper classes are final and implements Serializable interface either directly
or by extending Number Class which implements Serializable.

59. While initializing a multidimensional array it is necessary and sufficient to initialize


the leftmost dimension for the code to compile.

60. Core Object instances compares for identity. i.e. (Object1.equals(Object2)) is only true
if Object1 == Object2. (Unlike Strings)

61. Class StringBuffer doesn't override the equals() methods inherited from the Object
class. As Object.equals() compares for identity, calling equals() will only check if they
reference the same object or not. (See point 60)

62. Even if out of scope, local variable still has a reference. (Can not be garbage collected)

Prev- Next
63. Concrete classes and interfaces: These are some of the most useful data structure
classes, listing the primary data-structure relevant interface, and omitting utility interfaces
such as Cloneable and Serializable.

1. Most commonly used classes


-------------------------------------------------------------------------------------
Class Implementation
-------------------------------------------------------------------------------------
ArrayList - Sequence of values stored in resizable array, unorderd. Duplicate values are
allowed.
LinkedList - Sequence of values stored in linked list, in insertion order. Duplicate values
are allowed.
HashMap - Key/value pairs in hash table. unorderd. Only unique keys.
TreeMap - Key/value pairs in balanced binary tree, sorted, unique keys.
HashSet - Single copy of value stored in hash table. Implements Set, unorderd. unique
values.
TreeSet - Single copy of value stored in balanced binary. Implements
Set, sorted. unique values.

-------------------------------------------------------------------------------------
2. Interfaces
-------------------------------------------------------------------------------------
Class Implementation
-------------------------------------------------------------------------------------
Collection - Methods common to all data structures.
List - Basic List methods. Implemented by ArrayList and LinkedList.
Map - Basic Map methods. Implemented by HashMap and TreeMap.
Map.Entry - Key/value pairs in Set returned by Map.entrySet().
Set - Basic Set methods. Implemented by HashSet and TreeSet.
Iterator - Methods for forward iteration.
ListIterator - Additional methods for going backward.
-------------------------------------------------------------------------------------
3. Older classes which have a newer replacement
-------------------------------------------------------------------------------------
Class Implementation
-------------------------------------------------------------------------------------
HashTable Older, synchronized version of HashMap.
Vector Older, synchronized version of ArrayList, still used.
64. static variable can also be inherited like instance variables, there is nothing
problematic in that.
65. A thread is started and scheduled for running just after call to start() and before
executing run().
66. run() method of a class implementing Thread, can be synchronized. Below is a valid
example of thread...
public class TestThread extends Thread{
private int data = 7;
public static void main(String[] args){
TestThread t = new TestThread();
t.foo();
}
public synchronized void foo(){
start();
// below statements will executed, because run is synchronized method,
so it will only start after completion of method foo..
data = 100; data += 20; data+= 3;
}
public synchronized void run(){
System.out.println("data");
}

67. All the methods which are optional in Collection Class throws an
UnsupportedOperationException if implementation of the method is not provided.
java.util package provides implementation for all the optional methods.

68. A collection (or a map) only stores references to objects, and not the actual objects.

69. Collection method : Object[] toArray(Object a[]) Stores the elements of a collection
into an array of a specified type.

If the given array is big enough, the elements are stored in this array. If there is room to
spare in the array, that is, the length of the array is greater than the number of elements in
the collection, the spare room is filled with null values before the array is returned. If the
array is too small, a new array of the same runtime type and appropriate size is created. If
the runtime type of the specified array is not a supertype of the runtime type of every
element in the collection, an ArrayStoreException is thrown.

70. When inserting an element into Collection, its reference is automatically upcasted to
the type Object. On retrieval, it might be necessary to downcast the reference value of the
object to invoke subtype-specific behavior.

71. The majority of the iterators provided in the java.util package are said to be fail-fast.
When an iterator has already been obtained, structurally modifying the underlying
collection by other means will invalidate the iterator. Subsequent use of this iterator will
throw a ConcurrentModificationException. The remove() method of an iterator is the only
recommended way to delete elements from the underlying collection during traversal with
an iterator.

72. The Set interface does not define any new methods. All the methods it has are
inherited from Collection interface.

73. List subList(int fromIndex, int toIndex)

This method returns a view of the list, which consists of the sublist of the elements from
the index fromIndex to the index toIndex-1. A view allows the range it represents in the
underlying list to be manipulated. Any changes in the view are reflected in the underlying
list, and vice versa.

74. Vector class is a legacy class that has been retrofitted to implement the List interface.

75. The Vector and ArrayList classes are implemented using dynamically resizable arrays,
providing fast random access and fast list traversal very much like using an ordinary array.

76. Unlike the ArrayList class, the Vector class is thread-safe, meaning that concurrent
calls to the vector will not compromise its integrity.

77. A List can have duplicate elements.

78. The clear() method in Collection interface does not have a return value.

79. Constructors can not be abstract, final, static, synchronized and native. However,
block synchronization can be used within constructors.

80. Main Thread is the thread from which other "child" threads will be spawned. It must
be the last thread to finish execution. When main thread stops, the program terminates.

Prev- Next
81. wait method must be used in synchronized code and there must be provision for notify
the waiting thread, otherwise the thread would wait forever.

82. valueOf() method of wrapper classes takes a String parameter representing a


respective wrapper type value.

83. X.equals(Y) always returns false if X and Y are classes of different types. It will not
throw any errors.

84. Overloaded methods must have different signature. (Signature doesn't include return
type, so two same methods having just different return types will cause compile time
error)

85. An abstract class can contain final methods but a final class cannot contain abstract
metods.

86. The default (no-argument) constructor provided by the compiler when no constructor
is explicitly provided is not always public. it will have the access modifier same as access
modifier of the class to which the constructor belongs.

87. A method with the same name as constructor can be present in a class. (it can have
return value, so it is not just another constructor but a method with simillar name as
class/constructor)

88. Run() is the only method which Interface Runnable has.

89. A class within a method can only access the final variables of that method.

90. A statement re-assigning value to final variable will compile OK, althoght it would not
change the value of a final variable, which is once initialized.

91. A join() method waits for the thread on which it is called to die.

92. An inner class can extend another class and it can be static (nested class - it is a type of
inner class)

93. NullPointerException is not a subclass of ArithmaticException.

94. It is not necessary to override the run() method when you extend Thread class.

95. ~j = (-j)-1 is the expression to calculate the value of a valid expression ~j.

96. It is not required that if two objects are unequal according to the equals(Object anObj)
method, then calling the hashCode method on each of the two objects must produce
distinct integer results. They can produce equal integer values.

97. a.equals(null) will always return false for any non-null reference value a, there isnt
any problem in that. Problem can occur if a would be null.
98. output of a%b can be negtive as % operator is not actually a true modulus opertor, but
it computes the reminder which can be negative.

99. java.lang.Character has only one constructor that takes a char value.

100. The class java.lang.Void is an unintantiable placeholder class to hold a reference to


the Class object representing the java keyword void. This class is final and has a private
constructor (All wrapper classes are final but other classes can be instantiated unlike
Void). Hence it can neither be extended nor can it be instantiated.

101. A native method can be static.

102. You can invoke the start method only once for each thread, invoking it again on a
running thread will throw illigalThreadStateExeption at runtime.

103. Class has no public constructor. Class objects are constructed automatically by JVM
as classes are loaded and by calls to the defineClass method in the class loader.

104. The Class of the object passed as the argument in Thread t = new Thread(Object obj)
must be implementing interface Runnable and must be implementing the method "public
void run()" ovrridden from Runnable.

Prev

Das könnte Ihnen auch gefallen