Professional Documents
Culture Documents
1. The static import construct allows unqualified access to static members without inheriting
from the type that contains those static members. Static imports can be performed for
individual members or for a group of members.
For example:
import static java.lang.Math.PI;
// Here we import the constant PI individually from the Math class.
2. There are three top-level elements that may appear in a compilation unit. None of these
elements is mandatory. If they are present, then they must appear in the following order:
• package declaration
• import statements
• class definitions
3. The filed members in an interface are implicitly public, final, and static. Interface methods
cannot be native, static, synchronized, final, private, and protected. They are implicitly
public, abstract, and non-static.
4. A constructor
5. Abstract classes
a. cannot be instantiated.
b. have one or more constructors.
c. may or may not have abstract methods.
d. may or may not have non-abstract methods.
6. A default constructor is created by the compiler only if you have not provided any other constructor in the class. The
default constructor has no arguments and has the same access modifier as the class.
7. A class can implement any number of interfaces, but it can extend only one class. An
interface can extend any number of interfaces, but it cannot implement another interface.
8. A concrete (non-abstract) class implementing an interface has to implement all the methods
declared in the interface. A concrete class extending an abstract class must define all the
abstract methods defined in the latter.
Variable of the defined enum type can then be created like this.
Fruit f;
12. Invoking the values() method on an enum returns an array of all the values in that type.
13. When an array is created, all its elements are initialized to their default values, even if the
array is declared locally. Static and instance variables of a class are also initialized with a
default value. Local variables are never given a default value; they have to be explicitly
initialized before use.
14. A final class cannot be extended, so it is forbidden to declare a class to be both final and
abstract.
15. According to the JavaBean naming standards, if the property name is 'x' and the type is
‘Type’, the accessor method is of the form
Type getX()
boolean isX()
void setX(boolean newValue)
16. Variable arguments (varargs) allow you to specify a method that can take multiple
arguments of the same type and does not require that the number of arguments be
predetermined.
The three periods(ellipsis) after the final parameter's type indicate that the final argument
may be passed as an array or as a sequence of arguments.
17. You can only use one ellipsis per method. For example, the following is not allowed:
public Computer(String companyName, String model, String... components, double... componentPrices)
18. It is legal to call the method without passing in the varargs parameter.
For example, we can invoke
20. Static methods and static variables of a class can be used without having any instances of
that class at all. A static method cannot access non-static variables of the class. Static
methods cannot be redefined as non-static in subclasses, and vice versa.
21. An identifier is composed of a sequence of characters where each character can be a letter,
a digit, an underscore, or a dollar sign. An identifier cannot be a Java keyword and it cannot start with a
digit. It is possible to use class names as identifiers even though it is not a smart choice.
For Example:
number, $$abc, _x, String // Legal
new, 15bb, he-he // Illegal
22. To get the array size, use the array instance variable called length. Arrays are indexed
beginning with zero and end with length-1. Whenever you attempt to access an index value
outside the range 0 to n-1, an ArrayIndexOutOfBoundsException is thrown.
23. The return type of an overriding method should match that of the overridden method except
in the case of covariant returns, as discussed in the next point. Return types of overloaded
methods can be different, but changing only the return type is not legal. The arguments
should also be different.
24. Covariant return types allow a method in a subclass to return an object whose type is a
subclass of the type returned by the method with the same signature in the superclass.
25. A method that declares a class as a return type can return any object which is of the
subclass type. A method that declares an interface as a return type can return any object
whose class implements that interface.
26. A static nested class is a static member of the enclosing class. It does not have access to
the instance variables and methods of the class.
27. As the above example shows, a static nested class does not need an instance of the outer
class for instantiation.
28. To instantiate a non-static inner class, you need an instance of the outer class.
A non-static inner class has access to all the members of the outer class. From inside the outer instance code, use the
inner class name alone to instantiate it:
From outside the outer instance code, the inner class name must be included in the outer instance:
30. The switch statement now supports the use of enum values. You must not preface each enumerated type with the
enum class name, in the case statement. So it is ‘case A’ and not ‘case Grade.A’.
30. When a break statement is encountered, the control moves out of the switch statement. If no break statement is
encountered, all the case statements are executed till a break is encountered or the switch statement ends.
31. The body of the ‘while’ loop may not be executed even once.
For example: while(false){}
where expr1 is the initialization expression, expr2 is the conditional test, and expr3 is the
iteration expression.
Any or all of these three sections could be omitted and the code would still be legal.
33. The enhanced ‘for’ loop (also known as the ‘for-each’ loop) provides a simpler way to iterate over collections, arrays
or other Iterable objects. It has the following syntax
34. The break statement is used to exit from a loop or a switch statement. The continue
statement is used to stop just the current iteration of a loop and to proceed to the next one.
35. Breaking to a label (using break <labelname>;) means that the loop at the
label will be terminated and any outer loop will keep iterating. While a
continue to a label (using continue <labelname>;) proceeds with the execution of the next
iteration of the labeled loop.
assert Expression1 ;
assert Expression1 : Expression2 ;
42. A java.lang.RuntimeException and its subclasses are unchecked exceptions. All remaining
exceptions are checked exceptions. Checked exceptions should either be handled by
declaring the exception using the throws keyword in the method declarator, or by using
try/catch blocks. Unchecked exceptions are not required to be handled.
43. The try block contains the code which might throw an exception. One or more catch clauses can be provided to
handle the different exception types that might be thrown from the code in the try block. All the catch blocks must be
ordered from the most specific exception to the most general one.
44. A try block should have either a catch block or a finally block, but it’s not compulsory to have both.
45. The finally block is always executed after the try block and all catch blocks have been executed, whether an exception
is thrown or not. The only exception is when the System.exit() is invoked before it.
46. The checked exceptions that a method can throw must be declared using the ‘throws’
keyword.
To throw an exception explicitly from the code, use the ‘throw’ keyword.
For example:
void f() throws Exception
{
if(x > y) throw new Exception();
}
47. More than one exception can be listed in the throws clause of a method using
commas.
For example:
public void myMethod() throws IOException, ArithmeticException
48. You can also rethrow the same exception which you caught.
For example: catch(IOException e) { throw e; }
49. NumberFormatException is thrown to indicate that the application has attempted to convert a string to one of the
numeric types, but that the string does not have the appropriate format. It is a subclass of IllegalArgumentException.
50. AssertionError is thrown to indicate that an assertion has failed. StackOverflowError is thrown when a stack overflow
occurs because an application recurses too deeply and exhausts all the available stack space.
51. An ExceptionInInitializerError is thrown to indicate that an exception occurred during evaluation of a static initializer
or the initializer for a static variable.
52. All the wrapper classes except the Character class have two constructors; one that takes a primitive value and one that
takes a String representation of the value as argument.
53. Instances of the String class in Java are immutable. Once an instance is created, the wrapped string value cannot be
changed. But the StringBuffer class provides support for mutable string instances.
54. StringBuilder is almost identical to the StringBuffer class, however it isn't thread-safe, while StringBuffer is. If you
know you are going to create a string within a single thread, it is better to use StringBuilder. However, if it involves
multiple threads, using StringBuffer is recommended.
55. Autoboxing is the automatic conversion process between primitive types and primitive wrapper types. A boxing
conversion converts a value of a primitive type to the corresponding value of the wrapper type.An unboxing
conversion converts a value of a wrapper type to the corresponding value of the primitive type.
56. A File object represents a file's name and path, not the physical file on disk. Thus, you can create a File object to
represent a name and a path, even if a file of that name at the given path doesn't exist. This also means that creating a
new File object does not result in the creation of a new physical file on the disk.
59. The BufferedReader class reads text from a character-input stream, buffering characters so
as to provide for the efficient reading of characters, arrays, and lines. It is advisable to wrap
a BufferedReader around any Reader whose read() operations may be costly, such as
FileReaders andInputStreamReaders.
For example,
60. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer
whose write() operations may be costly, such as FileWriters and OutputStreamWriters.
For example:
61. The following method allows to create a FileWriter object, given a File object.
public FileWriter(File file, boolean append) throws IOException
If the second argument is true, then bytes will be appended at the end of the file. Otherwise, the contents of the file
are overwritten.
62. A class is serializable if it implements the java.io.Serializable interface. All subtypes of a serializable class are
themselves serializable.
63. For complete and explicit control of the serialization process, a class must implement the Externalizable interface. For
Externalizable objects, only the identity of the object's class is automatically saved by the stream. The class is
responsible for writing and reading its contents, and it must coordinate with its superclasses to do so. The
Externalizable interface extends the Serializable interface.
64. The Serializable interface has neither fields nor methods. The Externalizable interface defines the following methods.
void readExternal(ObjectInput in)
The object implements the readExternal() method to restore its contents by calling the
methods of DataInput for primitive types and readObject() method of ObjectInput for
objects, strings, and arrays.
The object implements the writeExternal() method to save its contents by calling the
methods of DataOutput for its primitive values or calling the writeObject() method of
ObjectOutput for objects, strings, and arrays.
65. The java.util.Scanner class represents a simple text scanner for parsing primitive types and strings using regular
expressions.
A scanner splits its input into tokens using a delimiter pattern.
The methods used to change the delimiter for tokenizing the input are
Scanner useDelimiter(String)
Scanner useDelimiter(Pattern)
66. The Formatter class provides a constructor which creates a new Formatter instance with the specified destination and
locale.
Formatter(Appendable a, Locale l)
The Appendable interface must be implemented by any class whose instances are intended to receive formatted
output from a Formatter. This interface is implemented by StringBuilder but not by the String class.
67. The format() method of the Formatter class writes a formatted string to this object's
destination using the specified format string and arguments.
The format() method of the String class returns a formatted string using the specified
format string and arguments.
68. A Locale object represents a specific geographical, political, or cultural region. The available constructors are
• Locale(String language)
• Locale(String language, String country)
• Locale(String language, String country, String variant)
69. The Locale class provides a number of convenient constants to create Locale objects for commonly used locales.
For example, the following creates a Locale object for the United States:
Locale locale = Locale.US;
70. DateFormat class has methods to format and parse dates for any locale.
DateFormat d = DateFormat.getDateInstance();
String str = d.format(date);
71. The NumberFormat class helps you to format and parse numbers for any locale.
Use getInstance() or getNumberInstance() to get the normal number format. Use
getIntegerInstance() to get an integer number format.
Use getCurrencyInstance() to get the currency number format.
Use getPercentInstance() to get a format for displaying percentages.
72. To format a number for the current Locale, use one of the factory class methods:
myString = NumberFormat.getInstance().format(myNumber);
To format a number for a different Locale, specify it in the call to getInstance():
NumberFormat nf = NumberFormat.getInstance(Locale.US);
73. The Pattern class is a compiled representation of a regular expression. The compile()
method of the Pattern class compiles the given regular expression into a pattern and then the
matcher method creates a matcher that will match the given input against this pattern.
74. The split() method of the String class returns an array containing the tokens into which the
invoking string has been split. It takes the regular expression, which is to be used as the
delimiter, as the argument.
75. The System.out.printf() method sends formatted numerical output to the console. It uses
a java.util.Formatter object internally.
Objective: Concurrency
This method will be executed by the new thread after it has been started by the thread scheduler.
79. When the start() method is called on a Thread object, the thread moves from the NEW
state to the RUNNABLE state. When the Thread scheduler gives the thread a chance to
execute, the run() method is invoked.
80. Many threads can be in the RUNNABLE state, but only one thread can be actually running at a given time on a
mono-processor machine. The order in which threads were started might be different from the order in which they
actually run.
81. It is legal to invoke the run() method directly, but it does not start a new thread of
execution. Instead, the current thread executes it like a normal method.
82. The start() method should be invoked only once on a Thread object, otherwise it will throw
an IllegalStateException.
83. A thread is considered dead, when its run method returns. A dead thread cannot be started again.
84. The sleep() method puts the currently executing thread to sleep for a given time in
milliseconds.
85. The yield() method causes the current thread to move from the RUNNING state to the
RUNNABLE state, so that another thread can have a chance to run. There is no guarantee
that the next chosen thread chosen will be a different thread.
86. The isAlive() method returns true if the thread upon which it is called has been started,
but is not yet dead.
85. By default, every thread gets the priority of the thread of execution that creates it. The
setPriority() method is used to set the priority of a Thread, which varies from 1 to 10.
86. When a thread calls join() on another thread, the currently running thread will wait until the
thread it joins with has finished executing.
87. Every object in Java has one and only one lock which ensures synchronized access to the resource.
88. If a thread has obtained the lock, no other thread can enter the synchronized code till the lock is released. When the
thread holding the lock exits the synchronized code, the lock is released.
89. If a thread tries to get the lock of an object and finds that the lock is already taken, the thread goes into a blocked state
till the lock is released.
a.) Synchronize an entire method by using the synchronized modifier in the method declaration.
b.) Synchronize a block, using the synchronized keyword with an expression that evaluates to an object reference.
The block must be enclosed in curly braces.
For example,
void funct(){
synchronized(obj)
{
// code to be thread protected
}
}
85. Static methods can be synchronized, using the lock from the java.lang.Class object representing that class.
86. If a thread sleeps while executing synchronized code, the lock is not released.
89. Only one thread can access the synchronized code of an object at a time, but any number of threads can access the
same object’s non-synchronized code.
90. The wait(), notify(), and notifyAll() methods are defined in the java.lang.Object class.
91. A thread gives up the lock on a synchronized object and moves from the RUNNING state to
the WAITING state when the wait() method is invoked.
92. The notify() method is used to signal one of the threads waiting on the object to return to
the RUNNABLE state. The notifyAll() method sends the signal to all the threads waiting on
the object to return to the RUNNABLE state.
93. A thread can invoke wait() or notify() on a particular object, only if it currently holds the
lock on that object. So these methods can only be invoked from synchronized code
Objective: OO Concepts
90. Cohesion is the degree to which all the elements of a component are directed towards and essential for performing the
same task. A well-designed class must have high cohesion.
92. Coupling indicates the degree of dependence among components. Tight coupling tends to
indicate poor design of classes, since it makes modifying parts of the system difficult, for
example, modifying a component affects all the components to which the component is
connected.
94. The relationship of a subclass with its superclass is termed "IS-A". It is implemented using the ‘extends’ keyword.
The relationship of a subinterface with its superinterface is termed "IS-A". It is also implemented using the ‘extends’
keyword.
95. Two objects, X and Y are in a HAS-A relationship if Y is a property or a component of X. If X HAS-A Y, than Y will
be an member variable in class X.
96. Hiding the implementation details of a class behind a public programming interface is called encapsulation. A class is
considered to be well encapsulated if the instance variables are private (or protected if need be) and access is allowed
only through public methods.
97. All constructors implicitly call the no argument constructor of the immediate superclass using
super(); if no explicit call is made to the superclass constructor.
98. A superclass / interface type reference variable can refer to an object of the subclass, but the opposite is not true.
100. A class can overload both the methods declared in it as well as the methods of its superclass.
101. Constructors can be overloaded, but not overridden, since they are not inherited by subclasses.
103. Polymorphism comes into action during overriding, the method invoked depends on the actual object type at runtime.
104. To invoke the superclass version of an overridden method from the subclass, use
super.method().
106. Final methods cannot be overridden. Private methods cannot be overridden since they are not inherited.
107. A collection is a data structure in which objects are stored. They can grow and shrink dynamically.
108. Collection is an interface whereas Collections is a helper class which has utility methods for sorting, collections
searching, etc.
109. Set and List extend the java.util.Collection interface, but Map does not implement the Collection interface, though it
is a part of Java's collection framework.
110. A List is a collection, which can contain duplicate elements and the elements are ordered.
112. A Set is a collection, which cannot contain any duplicate elements and has no explicit order to its elements.
114. A Map is an object that maps keys to values. It cannot contain duplicate keys; each key can map to at most one value.
116. The hashcode value of an object gives a number which can be used to effectively index objects in a collection.
117. If two objects are equal as determined by the equals() method, their hashcodes should be
the same. So whenever equals() is overridden, hashCode()should also be implemented. The
reverse is not required, i.e., two objects that are not equal can have the same hashcode.
For Example:
public int hashCode() { return (int)(value^5); }
118. It is incorrect to involve a random number or transient variable directly when computing the hashcode because it
would not return the same hashcode for multiple invocations of the method.
119. When comparing reference variables using the “==” operator, it returns true if the reference variables are referring to
the same object.
120. The Object class provides the equals(Object obj) method, which can be overridden to
return “true” if two objects are considered meaningfully equal.
121. The default implementation of the equals() method in Object class returns true only if an
object is compared to itself i.e., it behaves like “==”
122. The equals() method is overridden by the String and wrapper classes. However, the
StringBuffer class does not override this method.
123. In the Arrays class, there are sort methods for all primitive type and object arrays, of the form
• Arrays.sort(primitivetype[])
• Arrays.sort(Object[])
You can perform binary search on sorted arrays of primitive type or Object type using the binarySearch() method.
Arrays.binarySearch(type[],type key)
124. It is possible to restrict a collection type to contain objects of a particular data type only. Such types are called generic
types.
For example, the declaration below indicates that List is a generic interface that takes a type parameter, which is a
Double. The compiler guarantees that only Double objects are added to this List.
125. The TreeSet class guarantees that the set will be sorted according to the natural order of the elements (if the elements
implement the Comparable interface), or by the comparator provided at the set creation time.
126. The Comparable interface defines the int compareTo(Object o) method which compares
this object with the specified object for order. It returns a negative integer, zero, or a
positive integer depending on whether this object is less than, equal to, or greater than the
specified object.
127. The Comparator interface defines the int compare(Object o1, Object o2) method which
compares two objects. They can be passed to a sort method (such as Collections.sort) to
allow precise control over the sort order. Comparators can also be used to control the order
of certain data structures (such as TreeSet or TreeMap).
128. The Queue interface extends the Collection interface and adds the following methods:
• E element()
• boolean offer(E o)
• E peek()
• E poll()
• E remove()
The offer method is used to add elements to the Queue. It returns false if the element
cannot be added.
The remove() and poll() methods are for removing the first element of the Queue. The
remove method throws NoSuchElementException when it is called on an empty collection,
the poll method just returns null.
The peek() and element() methods can return the element at the head of the queue,
without removing it. The peek() method returns null if the queue is empty, while the
element() method throws NoSuchElementException in that case.
129. All instances of a generic class have the same runtime class, regardless of their actual type parameters. So it is not
meaningful to use the instanceof operator to check if an object is the instance of a particular invocation of a generic
type.
130. When a generic type is used without a type parameter, it is called a raw type. Since you can insert all type of objects
into these raw types, it is not possible to check their correctness. So assigning generic types to raw types generates an
unchecked warning.
131. In general, if Foo is a subtype (subclass or subinterface) of Bar, and G is some generic type declaration, it is not the
case that G<Foo> is a subtype of G<Bar>.
For example, the second line of code here will not compile.
For example,
void printCollection(Collection<?> c) {
for (Object e : c) {
System.out.println(e);
}
}
And now, we can call it with any type of collection.
Note that the following code can take only Collection <Object>
void printCollection(Collection<Object> c) {
for (Object e : c) {
System.out.println(e);
}
}
Since we don’t know what type that is, we cannot pass in anything. The sole exception is null, which is a member of
every type.
134. We can declare variables which can accept collections of any subclass of a particular class, say X, by using the
bounded wild card type <? extends X>.
Objective: Fundamentals
135. You can request for the garbage collector to run by invoking the System.gc() method, but
you cannot force it to happen.
136. The garbage collector runs in a low priority thread and its implementation is specific to the JVM.
137. There is no guarantee of the order in which the objects will be garbage collected.
138. An object is considered eligible for garbage collection when no live thread can reach it. However, there is no
guarantee that it will be garbage collected.
139. If available memory is too low, the garbage collector will surely run before it throws OutOfMemoryError.
140. Objects which are created locally in a method are eligible for garbage collection when the method returns, unless they
are assigned to some reference variable outside of the method.
141. The finalize() method defined in the Object class is inherited by all classes and may be
overridden if necessary.
142. To include a JAR file in the class path, the path must reference the JAR itself, not merely the directory that contains
the JAR.
For example, the following command sets the classpath to contain the jar file myjar.jar in the /jars folder.
143. When you pass an object reference into a method, only a copy of the reference variable is actually passed. The copies
of the variable with the caller and called methods are identical, so both refer to the same object. If the object is
modified inside the method, the change is visible outside also.
144. The instanceof operator is used for object reference variables only, it is used to check if an object is of a particular
type.
145. The & operator sets a bit to 1 if both operands’ bits are 1.
148. If both operands are true, & and && operators return true.
149. If at least one operand is true, the | and || operators return true.
150. || and && are called short-circuit operators because the right operand is not evaluated if the result of the operation can
be determined after evaluating only the left operand. In case of & and |, both operands are always evaluated.
151. The conditional operator has three operands; it decides which of the two values should be assigned to a variable. Note
that the two values must be of the same type. It is not possible to return a double if the expression is true and a String
is the expression is false.
someVariable = (boolean expr) ? Value if true : Value if false
In the first case, y will be incremented first and then assigned to x. In the second case, first y will be
assigned to x and then it will be incremented.