Sie sind auf Seite 1von 54

Abstraction - Abstraction is way of converting real world objects in terms of class.

For
example creating a class Vehicle and injecting properties into it. E.g
public class Vehicle {
public String colour;
public String model;
}
Encapsulation - The encapsulation is achieved by combining the methods and attribute into
a class. The class acts like a container encapsulating the properties. The users are exposed
mainly public methods.The idea behind is to hide how thinigs work and just exposing the
requests a user can do.
Association - Association is a relationship between two classes. In this relationship the
object of one instance perform an action on behalf of the other class. The typical behaviour
can be invoking the method of other class and using the member of the other class.
public class MyMainClass{
public void init(){
new OtherClass.init();
}
}
Aggregation - Aggregation has a relationship between two classes. In this relationship the
object of one class is a member of the other class. Aggregation always insists for a direction.
public class MyMainClass{
OtherClass otherClassObj = new OtherClass();
}
Composition - Composition is a special type of aggregation relationship with a difference
that its the compulsion for the OtherClassobject (in previous example) to exist for the
existence of MyMainClass.
15) How to find the size of an object?
Ans)The heap size of an object can be found using Runtime.totalMemory()-Runtime.freeMemory() .
Q9) How to change the heap size of a JVM?
Ans) The old generation's default heap size can be overridden by using the -Xms and -Xmx
switches to specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program
Q10) What is difference between instanceof and isInstance(Object obj)?

Ans) Differences are as follows:


1) instanceof is a reserved word of Java, but isInstance(Object obj) is a method of
java.lang.Class.
if (obj instanceof MyType) {
...
}else if (MyType.class.isInstance(obj)) {
...
}
2) instanceof is used of identify whether the object is type of a particular class or its subclass
but isInstance(obj) is used to identify object of a particular class.
Q8) What are the different types of references in java?
Ans) Java has a more expressive system of reference than most other garbage-collected
programming languages, which allows for special behavior for garbage collection. A normal
reference in Java is known as a strong reference. The java.lang.ref package defines three
other types of referencessoft, weak, and phantom references. Each type of reference is
designed for a specific use.
A SoftReference can be used to implement a cache. An object that is not reachable by a
strong reference (that is, not strongly reachable), but is referenced by a soft reference is
called softly reachable. A softly reachable object may be garbage collected at the discretion
of the garbage collector. This generally means that softly reachable objects will only be
garbage collected when free memory is low, but again, it is at the discretion of the garbage
collector. Semantically, a soft reference means "keep this object unless the memory is
needed."
A WeakReference is used to implement weak maps. An object that is not strongly or softly
reachable, but is referenced by a weak reference is called weakly reachable. A weakly
reachable object will be garbage collected during the next collection cycle. This behavior is
used in the class java.util.WeakHashMap. A weak map allows the programmer to put
key/value pairs in the map and not worry about the objects taking up memory when the key
is no longer reachable anywhere else. Another possible application of weak references is the
string intern pool. Semantically, a weak reference means "get rid of this object when nothing
else references it."
A PhantomReference is used to reference objects that have been marked for garbage
collection and have been finalized, but have not yet been reclaimed. An object that is not
strongly, softly or weakly reachable, but is referenced by a phantom reference is
called phantom reachable. This allows for more flexible cleanup than is possible with the
finalization mechanism alone. Semantically, a phantom reference means "this object is no
longer needed and has been finalized in preparation for being collected."
Q6) What is a strictfp modifier?
Ans) Strictfp is used with variable only . It is used to restrict floating point calculations ( fp )
to ensure portability ( platform Independent ). When this modifier is specified, the JVM

adheres to the Java specifications ( IEEE-754 floating-point specification ) and returns the
consistent value independent of the platform. That is, if you want the answers from your
code (which uses floating point values) to be consistent in all platforms, then you need to
specify the strictfp modifier
Q4) What is volatile keyword?
Ans) In general each thread has its own copy of variable, such that one thread is not
concerned with the value of same variable in the other thread. But sometime this may not be
the case. Consider a scenario in which the count variable is holding the number of times a
method is called for a given class irrespective of any thread calling, in this case irrespective
of thread access the count has to be increased. In this case the count variable is declared as
volatile. The copy of volatile variable is stored in the main memory, so every time a thread
access the variable even for reading purpose the local copy is updated each time from the
main memory. The volatile variable also have performance issues.
* Cloning the Class objects :
The process of creating the exact copy of an existing object is called cloning. In
cloning, already an object should exist and when we clone the objects, a bit wise copy
of the object will result. The original object and the cloned object will be exactly the
same bit to bit. If the original object has some data in it, it also automatically comes
into cloned object.
There are two types of cloning :
1. Shallow Cloning
2. Deep Cloning
When the cloned object is modified, same modification will also affect the original
object. This is called shallow cloning In shallow copy the object is copied without its
contained objects. Shallow clone only copies the top level structure of the object not the
lower levels. It is an exact bit copy of all the attributes.
Object class has a method clone() which does shallow cloning.
When the cloned object is modified, if the original object is not modified, then it is
called deep cloning.
In deep copy the object is copied along with the objects it refers to. Deep clone copies all
the levels of the object from top to the bottom recursively.
Disadvantages of using Serialization to achieve deep cloning
Serialization is more expensive than using object.clone().
Not all objects are serializable.
Serialization is not simple to implement for deep cloned object..
* Static and Transient Variable can not be serialized. (transient only used with
variables)
* A native method is a method that is implemented in a language other than Java. (only
used with only methods)
* A native method and abstract method have no body.
are not a keyword.

* null, true, false

* Final Classes All Wrapper Classes, String, StringBuffer, StringBuilder, System,


Math, StrictMath, Formatter, Void,
* Marker Interface Serializable, Clonable, SingleThreadModel,Random Access,
Remote

* Immutable Class All wrapper classes, String, Class, BigInteger, BigDecimal.


* A Constructor is called concurrently when the object creation is going on. JVM first
allocates memory for the
object and then execute the constructor to initialize the instance variables. By the
time, object creation is
completed, the constructor execution is also completed.
* State of immutable objects can not be changed once they are created they are
automatically synchronized/thread-safe.
* The references to the immutable objects can be easily shared or cached without
having to copy or clone them as there
state can not be changed ever after construction.
* The best use of the immutable objects is as the keys of a map.
* Steps for Custom Immutable Classdefine class as final,
properites of class as private,
define only getter method,
if class contains any mutable reference then while initialising the reference assign new
value in the reference (dont assign the same reference that we have passed as
argument).
* Java uses primitive data types and hence is not a pure object oriented language. Also
not support multiple inheritance.
* Unicode system is an encoding standard that provides a unique number for every
character, no matter what the
platform, program, or language is. Unicode uses 2 Bytes to represent a single
character.
* Object based Programming languages follow all the features of OOPS, except
Inheritance. Ex. JavaScript, VBScript.
* Path and Classpath are operating system level environment variables.
> Path is used define where the system can find the executables(.exe) files
> classpath is used to specify the location .class files.
We can remove the Classpath as follows :
set classpath=
* main() method can be overloaded and main() method may be final (final main()
method will normaly executed).

* Sub Class object contains copy of super class object so members of super class
available in Sub Class.
* A top level class can not be declared as private, protected, static, native, synchronized,
volatile, transient.
* Externalizable is an Interface that extends Serializable Interface. And sends data into
Streams in
Compressed Format. It has two methods, writeExternal(ObjectOuput
out) and readExternal(ObjectInput in)
public interface Externalizable
extends Serializable
Only the identity of the class of an Externalizable instance is written in the serialization
stream and it is the responsibility of the class to save and restore the contents of its
instances. The writeExternal and readExternal methods of the Externalizable interface
are implemented by a class to give the class complete control over the format and
contents of the stream for an object and its supertypes. These methods must explicitly
coordinate with the supertype to save its state. These methods supercede customized
implementations of writeObject and readObject methods.
Object Serialization uses the Serializable and Externalizable interfaces. Object
persistence mechanisms can use them as well. Each object to be stored is tested for the
Externalizable interface. If the object supports Externalizable, the writeExternal
method is called. If the object does not support Externalizable and does implement
Serializable, the object is saved using ObjectOutputStream.
When an Externalizable object is reconstructed, an instance is created using the public
no-arg constructor, then the readExternal method called. Serializable objects are
restored by reading them from an ObjectInputStream.
An Externalizable instance can designate a substitution object via the writeReplace and
readResolve methods documented in the Serializable interface.
* In JDK 1.4
only added).

- 51 Keywords

* In JDK 1.5

52 Keywords (enum is

Class is a user defined data types. It is a group of Java methods and variables. It is the
place where the properties and functionality of the specific type of object will be
defined. We can say that class as the structure of an object. If we defining one class, we
can define any number of objects depends on our requirement.
A Class contains variables, methods, constructors, blocks, class, interface, enum.
Object is the instance of the class. It is a run time entity. It has the separate memory
location, where the data of the specific type (user defined type) will be stored. We can
create any number of objects of the specific type.
* Keyword super refer super class members from a sub class .
* super is used to access super class variables, methods, constructors.

* Use super() always refers to the superclass immediately above the calling class.
* super() will the first statement of any constructor.
* Keyword this refer the current class object.
* this(...) - Calls another constructor in same class.
JVM (Java Virtual Machine) :
# A Java virtual machine (JVM) is a virtual machine capable of executing Java
bytecode.
# JVM's are not platform independent. JVM's are platform specific run time
implementation provided by the vendor.
As we all aware when we compile a Java file, output is not an 'exe' but it's a '.class' file.
'.class' file consists of Java byte codes which are understandable by JVM. Java Virtual
Machine interprets the byte code into the machine code depending upon the underlying
operating system and hardware combination. It is responsible for all the things like
garbage collection, array bounds checking, etc.
The JVM is called "virtual" because it provides a machine interface that does not
depend on the underlying operating system and machine hardware architecture. This
independence from hardware and operating system is a cornerstone of the write-once
run-anywhere value of Java programs.
There are different JVM implementations are there. These may differ in things like
performance, reliability, speed, etc. These implementations will differ in those areas
where Java specification doesnt mention how to implement the features, like how the
garbage collection process works is JVM dependent, Java spec doesnt define any
specific way to do this
JDK (Java Development Kit)
# JDK is Java Development Kit which is for development purpose and it includes
execution environment also.
Java Developer Kit contains tools needed to develop the Java programs, and JRE to
run the programs. The tools include compiler (javac.exe), Java application launcher
(java.exe), Appletviewer, etc
Compiler converts java code into byte code. Java application launcher opens a JRE,
loads the class, and invokes its main method.
You need JDK, if at all you want to write your own programs, and to compile the m.
For running java programs, JRE is sufficient.
JRE is targeted for execution of Java files
i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime
libraries.
JDK is mainly targeted for java development. I.e. You can create a Java file (with the
help of Java packages), compile a Java file and run a java file

JRE (Java Runtime Environment)


# JRE contains JVM, class libraries, and other supporting files.
# JRE does not contain any development tools such as compiler, debugger, etc. Actually
JVM runs the program, and it
uses the class libraries, and other supporting files provided in JRE. If you want to
run any java program, you need to
have JRE installed in the system.
# The Java Virtual Machine provides a platform-independent way of executing code;
programmers can concentrate on
writing software, without having to be concerned with how or where it will run.
# If u just want to run applets (ex: Online Yahoo games or puzzles), JRE needs to be
installed on the machine.
* An anonymous class may implement an interface or extend a super class, but may not
be declared to do both.
* static modifier is removed from the signature of the main() method or do not
provide String array as
argument in main () method then Program compiles. But at runtime throws an error
"NoSuchMethodError".
* if the main() method is declared as private then program compiles properly but at
runtime it will give "main() method not public." message.
Primitive Data Type : Represent Single Value, methods are not available to handle
premitive data types.
Reference Data Type : Represent group of values, methods are available to perform
various operations.
* converting one data type into another data type is called type casting or simply
casting.
# Widening : Converting Lower to Higher
# Narrowing : Converting Highter to
Lower
* Implicit Casting : Automatic casting done by Java Compiler internally, convert a
Lower to Higher data type.
* Explicit Casting : done by Programmer, compulsory while converting from a Higher
to Lower data type.
* Generalization : Converting a sub class type into a super class type is called
Generalization, because we are
making the sub class to become more general and its scope is widening. This is also
called Widening or upcasting.
* Specialization : Converting a super class type into a sub class type is called
Specialization, Hence we are coming down from more general form to a specific form
and hence the scope is narrowed. Hence this is also called narrowing or down-casting.

* Literals : A literal represents a value that is stored into a variable directly. Ex : Char
c=A (A is literal)
Integer literals, Float literals, Character literals, String literals, Boolean literals. (total 5
literals)
------------------------------------------------- Inner Class
-----------------------------------------------------* Instance Inner class can not contain static property. Instance Inner class can access
Outer class any
type of property.
* All the Members of Instance Inner Class can not be access inside the outer class
directly but allowed
through the Inner class object.
* Static Inner class contains both static members and non-static members.
* Only static member of the Outer class can be accessed inside Static Inner Class.
* Method Local Inner Class can not have static declaration and can not contain static
property.
* A Method can contain more than one Class but can not contain any Interface.
* We can perform Inheritance Operation on Method Local Inner Class.
* Local Inner Class may be abstract and contains abstract methods.
* Anonymous Inner Class will be sub class to some other class or interface always.
* Anonymous Inner Class contains static declaration.
* If we want to access local variable in Anonymous Inner Class or Method Local Inner
Class then local
variable must be declared as final.
Q5) Does a static nested class have access to the enclosing class' non-static methods or
instance variables?
Ans) No .
Q6)What are the advantages of Inner classes?
Ans) The embedding of inner class into the outer class in the case when the inner class is to be
used only by one class i.e. the outer class makes the package more streamlined. Nesting the
inner class code where it is used (inside the outer class) makes the code more readable and
maintainable.
The inner class shares a special relationship with the outer class i.e. the inner class has access
to all members of the outer class and still have its own type is the main advantages of Inner
class. Advantage of inner class is that they can be hidden from the other classes in the same
package and still have the access to all the members (private also) of the enclosing class. So
the outer class members which are going to be used by the inner class can be made private and

the inner class members can be hidden from the classes in the same package. This increases
the level of encapsulation.
If a class A is written requires another class B for its own use, there are two ways to do this.
One way is to write a separate class B or to write an inner class B inside class A. Advantage of
writing the inner class B in the class A is you can avoid having a separate class. Inner classes
are best used in the event handling mechanism and to implement the helper classes. The
advantage of using inner class for event handling mechanism is that the use of if/else to select
the component to be handled can be avoided. If inner classes are used each component gets its
own event handler and each event handler implicitly knows the component it is working for.
e.g.
Button btn1 = new Button("Submit");
Btn.addActionListener(new ActionListener(){/br>
Public void actionPerformed(ActionEvent ae){ submitClicked(); }
} );
The advantage of using static nested class is that to instantiate a static nested class you need
not create an instance of the enclosing class which reduces the number of objects the
application creates at runtime.
Q7)What are disadvantages of using inner classes?
Ans) 1. Using inner class increases the total number of classes being used by the application.
For all the classes created by JVM and loaded in the memory, jvm has to perform some tasks
like creating the object of type class. Jvm may have to perform some routine tasks for these
extra classes created which may result slower performance if the application is using more
number of inner classes. 2. Inner classes get limited support of ide/tools as compared to the
top level classes, so working with the inner classes is sometimes annoying for the developer.
Q8) What are different types of anonymous classes?
Ans 1) Plain old anonymous class type one
e.g.
class superClass{
void doSomething() {
System.out.println(Doing something in the Super class);
}
}
class hasAnonymous{
superClass anon = new superClass(){
void doSomething() {
System.out.println(Doing something in the Anonymous class);
}
};
Here anon is the reference which is of type superClass which is the class extended by the

anonymous class i.e. superclass of the anonymous class. The method doSomething() is the
super class method overridden by the anonymous class.
2) Plain old anonymous class type two
interface Eatable{
public void prepareSweets();
}
class serveMeal{
Eatable food = new Eatable(){
public void prepareSweets(){ //come implementation code goes here }
};
}
food is reference variable of type Eatable interface which refers to the anonymous class
which is the implementer of the interface Eatable. The anonymous implementer class of the
interface Eatable implements its method prepareSweets() inside it.
3) Argument defined anonymous class e.g.
interface Vehicle {
void getNoOfWheels();
}
class Car {
void getType(Vehical v) { }
}
class BeautifulCars {
void getTheBeautifilCar() {
Car c = new Car ();
c.getType (new Vehicle () {
public void getNoOfWheels () {
System.out.println("It has four wheels");
}
});
}
}
Anonymous class is defined as the argument of the method getTheBeautifilCar(), this
anonymous class is the implementer of the interface Vehicle. The method of class Car
getTheBeautifilCar() expects the argument as an object of type Vehicle. So first we create an
object of Car referenced by the variable c. On this object of Car we call the method
getTheBeautifilCar() and in the argument we create an anonymous class in place which is the
implementer of interface Vehicle hence of type Vehicle.
Q9) If you compile a file containing inner class how many .class files are created and
what are all of them accessible in usual way?
Ans) If a inner class enclosed with an outer class is compiled then one .class file for each inner
class an a .class file for the outer class is created. e.g.
class EnclosingOuter {
class Inner{ }

}
If you compile the above code with command
% javac EnclosingOuter.java
Two files
EnclosingOuter.class
EnclosingOuter$Inner.class
will be created. Though a separate inner class file is generated, the inner class file is not
accessible in the usual way like,
% java EnclosingOuter$Inner
Q10) How to access the inner class from code within the outer class?
Ans) The inner class is instantiated only through the outer class instance.
class EnclosingOuter {
private int noInnerClass = 1;
public void getNoOfInnerClasses(){
Inner in = new Inner();
System.out.println(No Of Inner classes is : + in.getNoOfClassesFromOuter());
}
class Inner{
public int getNoOfClassesFromOuter(){ return noInnerClass; }
}
Here the method getNoOfInnerClasses() is called on the outer classs instance through this
outer class instance the inner class instance in is created.
Q11) How to create an inner class instance from outside the outer class instance code?
Ans) To create an instance of the inner class you must have the instance of its enclosing
class.
e.g. class EnclosingOuter {
class Inner{ }
}
To create the instance of inner class from class other than the enclosing class.
1) class OtherThanOuter{
EnclosingOuter out = new EnclosingOuter();
EnclosingOuter.Inner in = out.new Inner();
}
2) class OtherThanOuter{
EnclosingOuter.Inner out = new EnclosingOuter.Inner (); }
Q12) How to refer to the outer this i.e. outer classs current instance from inside the
inner class?
Ans) The outer this reference i.e. the outer class current instance reference can be refered
using OuterClassName.this. E.g

class EnclosingOuter {
class Inner{
System.out.println(Inner class reference is + this); // inner class instance
System.out.println(Outer class reference is + EnclosingOuter.this); //outer class instance
}
}
To refer the inner class reference from within the inner class use this.
Q13) Which modifiers can be applied to the inner class?
Ans) Following are modifiers that can be applied to the inner:
public
private
abstract
final
protected
strictfp
static turns the inner class into static nested class.
Q14) Can the method local inner class object access methods local variables?
Ans) No, a method local inner class object can not access the method local variable.
Reason: The local variables are not guaranteed to live as long as the local inner class object.
The method local variable live on stack and exist only till the method lives, their scope is
limited only code inside the method they are declared in. But the local inner class object
created within the method lives on heap and it may exist even after the method ends if in case
the reference of this local inner class is passed into some other code and is stored in an
instance variable. So we can not be sure that the local variables will live till the method local
inner class object lives, therefore the method local inner class object can not access the
method local variable. To access the method local variables, the variable has to be declared as
final.
Q15) Can a method local inner class access the local final variables?Why?
Ans) Yes. Because the final variables are stored on heap and they live as long as the method
local inner class object may live.
Q16) Which modifiers can be applied to the method local inner class?
Ans) Only abstract or final keyword isallowed.
Q17) Can a local class declared inside a static method have access to the instance
members of the outer class?

Ans) No. There is no this reference available in the static method .The static method class can
not have access to any members of the outer class other than static members.
Q18) Can a method which is not in the definition of the superclass of an anonymous class
be invoked on that anonymous class reference?
Ans) No. Compilation will fail.As the reference variable type of the anonymous class will be
of superclass which will not know of any method defined inside the anonymous class the
compilation will fail.
e.g. class SuperClass{
void doSomething() {
System.out.println("In the Super class");
}
}
class hasAnonymous{
SuperClass anon = new SuperClass(){
void doSomething() {
System.out.println("In the Anonymous class");
}
void doStuff() {
System.out.println("An Anonymous class method not present in superClass");
}
};
public void doIt(){
anon.doSomething(); // legal superClass has this method
anon.doStuff(); // Not legal }
}
The above code does not compile as the superClass does not know about the anonymous class
method doStuff().
Q19) Can an anonymous class define method of its own?
Ans) Yes. But there will be no way by which the methods defined in the anonymous class
which are not present in its superclass be invoked. As only those methods which are defined in
the suprclass which the anonymous class extends be invoked defining the methods in the
anonymous class will be of no use.
Q20) Can an anonymous class implement multiple interfaces directly?
Ans) No. An anonymous class can implement only one interface. If the anonymous class is
extending a class then it becomes the implementer of all the interfaces implemented by its
superclass automatically.
Q21) Can an anonymous class implement an interface and also extend a class at the same
time?

Ans) No. An anonymous class can either extend a class or implement a single interface. If the
anonymous class is extending a class then it becomes the implementer of all the interfaces
implemented by its superclass automatically.
Difference between Comparable and Comparator :
Both are used for the same purpose(to Sort) but in different contexts. Comparable
interface has to be implemented by a Class to make it comparable. SortedXXX kind of
collections need its objects to satisfy the Comparable type. Comparator could be used
to sort a collection by custom sorting. You have a set of objects where you want to sort
it in both ascending and decending order.
Comparable (Interface)
available in java.lang package.
Used for natural storing order.

Comparator (Interface)
available in java.util package.
Used for implementing customized sorting.
Constains only two method :
Constains only one method :
public int compare(Object obj1, Object
public int compareTo(Object obj);
obj2);
public boolean equals(Object);
Implementing Comparator means "I can
Implementing Comparable means "I can
compare two other objects." This is
compare myself with another object." This typically useful when there are multiple
is typically useful when there's a single
ways of comparing two instances of a type
natural default comparison.
- e.g. you could compare people by age,
name etc.

---------------------------------------------------------------------------------------------------------

Interface

@ The class which implements the interface needs to provide implementation of all methods
declared in the interface. But it is not necessary that call all the interface variables in the
class.
@ All methods by default public and abstract. And all variables by deafult public, static and
final.
@ We can not use private, protected, static, final access modifier with the interface name,
we can only use public and abstract access modifier. If not mention then it will be default.
@ We can not specify the Instance variable, Instance method, Static Method, Constructor,
Instance Block, Static Block, Concrete Method in Interface.
@ An interface reference can point to objects of its implementing classes.
@ An interface can extends from one or many interfaces. A class can extend only one class
but implements any number of interfaces. An Interface can not implements or extends any
Class.
@ When a class is implementing two or more interfaces which contain same variable then
matching variable should not reffer directly. Always matching variable must access with the
interface name using dot/period (.) operator.
@ When a class is implementing two or more interfaces which contain same method
signature, we must override the method only once in sub class.
@ An interface can be declared in side the another interface and a top-level class only.
@ An interface can not be declared in side the method and inner-class.
@ when interface declared inside a class or Interface only public, protected, private, static &
abstract are permitted. Final not allowed.
@ Nested Interface can be implemented by any class (package level, nested or inner) as
long as the access modifiers permit visibility.
@ as with regular package level interfaces variables defined inside are considered to be
constants (static, public) regardless of whether the modifiers are specified like the package
level interfaces they can declare nested classes and interfaces
------------------------------------------> Exception Handling
<---------------------------------------------

* Checked Exception / Compiletime Exception : The Exceptions that are checked at


Compilition Time by the Java
Compiler. Checked Exception force the programmer to catch them explicitly in trycatch block.
* Unchecked Exception / Runtime Exception : The Exceptions that are checked by
JVM at runtime.
* Difference between Error and Exception :
Exception is an error which can be handled at runtime but Error is an error
which can not handled.
Exception are related to the application and Error is related to the environment
in which the application is running.
Exception can be Built-in or User Defined but Error is always Built-in.
For Handling Exception we can use try, catch, throws keyword but not with
Error.
Exception can be checked or unchecked but Errors are always unchecked.

* Throws :
# A throws cause lists the types of exceptions that a method meight throw.
# This is necessary for all exceptions, except those of type ERROR or Runtime
Exception.
# All other Exceptions that a method can throw must be declared in the throws
clause. If they are not, a

compile-time error will result.

* Throw :
# We can throw an Exception explicitly, using throw statement.
* We can catch more than one Exception in a single catch block.
* It is not considered as a good practice to write a single catch to catch all the
exceptions because If we use the
Superclass Exception in the catch block then we will not get the valuable information
about each of the
exception thrown during the execution, though we can find out the class of the
exception occurred. Also it will
reduce the readability of the code as the programmer will not understand what is the
exact reason for putting
the try-catch block.
* The catch block throw the exception caught by itself This is called rethrowing of the
exception by catch block.
try{

}
Catch(Exception E){
throw FileNotFound(); // called rethrowing
}
* Once the control switches to the catch block does not it return back to the try block to
execute the balance code.
* There should not be any line of code present between the try and the catch/finally
block.
* All the exceptions inherit a method printStackTrace() from the Throwable class. This
method prints the stack trace from where the exception occurred. It prints the most
recently entered method first and continues down, printing the name of each method
as it works its way down the call stack from the top.
* Exception object will be garbage collected after Exception Handling.
* The subclass exception should precede the base class exception when used within the
catch clause.
*
*
*
Q8) What is difference between ClassNotFoundException and
NoClassDefFoundError?
Ans) A ClassNotFoundException is thrown when the reported class is not found by the
ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be
loaded from another class which was loaded in a parent classloader and hence the class from
the child classloader is not visible.
Consider if NoClassDefFoundError occurs which is something like
java.lang.NoClassDefFoundError
src/com/TestClass
does not mean that the TestClass class is not in the CLASSPATH. It means that the class
TestClass was found by the ClassLoader however when trying to load the class, it ran into an
error reading the class definition. This typically happens when the class in question has static
blocks or members which use a Class that's not found by the ClassLoader. So to find the
culprit, view the source of the class in question (TestClass in this case) and look for code
using static blocks or static members.
Q20) What happens if the exception is never caught and throws down the method stack?

Ans) If the exception is not caught by any of the method in the methods stack till you get to the
main() method, the main method throws that exception and the JVM halts its execution.
Q21) How do you get the descriptive information about the Exception occurred during the
program execution?
Ans) All the exceptions inherit a method printStackTrace() from the Throwable class. This
method prints the stack trace from where the exception occurred. It prints the most recently
entered method first and continues down, printing the name of each method as it works its way
down the call stack from the top.

Q3) Can static block throw exception?


Ans) Yes, static block can throw only Runtime exception or can use a try-catch block to
catch checked exception.
Typically scenario will be if JDBC connection is created in static block and it fails then
exception can be caught, logged and application can exit. If System.exit() is not done, then
application may continue and next time if the class is referred JVM will throw
NoClassDefFounderror since the class was not loaded by the Classloader.
Types of Built-in Exceptions :
RuntimeException - RuntimeException is the superclass of those exceptions that can be
thrown during the normal operation of the Java Virtual Machine.
A method is not required to declare in its throws clause any subclasses of RuntimeException
that might be thrown during the execution of the method but not caught.
-------------------------------------------------------------------------------------------------

Polymorphism

Polymorphism is a process of one form behaving differently in different class.


There are two types of Polymorphism :Compile-time/Static Polymorphism: We can achieve Compile-time Polymorphism using
Method Overloading because in the case of Method Overloading method invocation will be
decided based on parameters of the method. This check will be done by compiler at the
compile time only.
Run-time/Dynamic Polymorphism: We can achieve Run-time Polymorphism using
Method Overriding and Dynamic Dispatch.
Method Overloading: Writing multiple methods inside the class with same name is called
as Method Overloading. When we are overloading the methods we need to remember the
following rules :
1. Method name must be same.
2. Return type can be anything.

3. Parameter must be changed in any one of the following three ways:


Interms of types of Parameter.
Interms of nos. of Parameter.
Interms of order of Parameter.
Method Overriding: Implementing Super class method in the sub class with same method
signature is called as method overriding. When we are overriding Super class method in the
Sub class we have to check the following:
Sub class method name must be same as Super class method name.
Sub class method parameter must be same as Super class method parameters.
Sub class method return type must be same as Super class method return type.
Sub class method access modifier must be same or higher than Super class access
modifier.
Dynamic Dispatch : The process of assigning Sub class object to Super class reference
variable is called as Dynamic Dispatch.
class A{ }
class B extends A{}
A obj1=new A();
B obj2=new B();
A obj1=new B();
B obj1=new A();

- True
- True
- True (Dynamic Dispatch)
- False

Q. What is method signature ?


Ans : Method signature represents the method name along with method parameters.
Difference between Method Overloading and Method Overriding :
Method Overloading
Method Overriding
Writing two or more methods with the same Writing two or more methods with the same
name but with different signatures is called
name and same signature is called Method
Method Overloading.
Overriding.
Method Overloading a done in the same
Method Overriding is done in Super and Sub
class.
classes.
In method overloading, method return type
In method overriding, method return type
can be same or different.
should also be same.
JVM decides which method is called
JVM decides which method is called
depending on the different in the method
depending on the data type (class) of the
signature.
object used to call the method.
Method Overloading is done when the
Method Overriding is done when the
programmer wants to extend the already
Programmer wants to provide a different
available feature.
implementation (body) for the same feature.
Method Overloading is code refinement.
Method Overriding is code replacement. The
Same method is refined to perform a
sub class method overrides (replace) the
different task.
super class method.

Polymorphism with Static Methods:


A Static method is a method whose single copy in memory is shared by all the objects of the
class. Static method belongs to the class rather than to the objects. So they are also called
class methods. When static methods are overloaded or overridden, since they do not depend
on the objects, the Java compiler need not wait till the objects are created to understand
which method is called.
Example:
class A{
static void show(){
System.out.println("A- show() method");
}
}
class B extends A{
static void show(){
System.out.println("B- show() method");
}
}
public class StaticMethodPoly {
public static void main(String[] args) {
// Super class reference refers to sub class object
A a=new B();
// call show() method using super class reference
a.show();
}
}
Polymorphism with Private Methods. (Overriding No, Overloading Yes)
* Method overriding is not possible in case of Private Methods. (Private Methods are not
available in
the sub classes, this means, there is no possibility to override the private methods of the
super class
in its sub classes.)
* Method overloading is possible in case of private methods.
Q. What happens if a method is written in the sub class with the same name as that of
the private method of the super class ?
Ans. : It is possible to do so. But in this case, the method in the super class and the method
in the sub class act as different methods. The super class will get its own copy and the sub
class will have its own copy. It does not come under method overriding. The only way to call
the private method of a class is by calling them within the class. For this purpose, we should
create a public method and call the private method from within it. When this public method
is called, it calls the private method.
Polymorphism with Final Methods. (Overriding No, Overloading Yes)
Final Methods can not be overridden, because they are not available to the sub classes.
Therefore, only method overloading is possible with final methods.

Q. Can we take private methods and final methods as same?


Ans : Yes.
--------------------------------------------- Garbage Collection
--------------------------------------------In Java Language we can allocate memory using new operator but there is no facility
provided for deallocate memory or cleaning the Object available in heap memory.
The JVM's heap stores all objects created by an executing Java program. Objects are
created by Java's "new" operator, and memory for new objects is allocated on the heap at run
time. Garbage collection is the process of automatically freeing objects that are no longer
referenced by the program.
The name "garbage collection" implies that objects that are no longer needed by the program
are "garbage" and can be thrown away. The garbage collector must somehow determine
which objects are no longer referenced by the program and make available the heap space
occupied by such unreferenced objects. In the process of freeing unreferenced objects, the
garbage collector must run any finalizers of objects being freed.
Why garbage collection?
JVM is responsible to cleaning the Memory. Giving this job to the JVM has several
advantages :
First, it can make programmers more productive. When programming in non-garbagecollected languages the programmer can spend many late hours (or days or weeks) chasing
down an elusive memory problem. When programming in Java the programmer can use that
time more advantageously by getting ahead of schedule or simply going home to have a life.
A second advantage of garbage collection is that it helps ensure program integrity. Garbage
collection is an important part of Java's security strategy. Java programmers are unable to
accidentally (or purposely) crash the JVM by incorrectly freeing memory.
A potential disadvantage of a garbage-collected heap is that it adds an overhead that can
affect program performance. The JVM has to keep track of which objects are being
referenced by the executing program, and finalize and free unreferenced objects on the fly.
This activity will likely require more CPU time than would have been required if the
program explicitly freed unnecessary memory. In addition, programmers in a garbagecollected environment have less control over the scheduling of CPU time devoted to freeing
objects that are no longer needed.
Fortunately, very good garbage collection algorithms have been developed, and adequate
performance can be achieved for all but the most demanding of applications. Because Java's
garbage collector runs in its own thread, it will, in most cases, run transparently alongside
the execution of the program. Plus, if a programmer really wants to explicitly request a
garbage collection at some point, System.gc() or Runtime.gc() can be invoked, which will
fire off a garbage collection at that time.
The Java programmer must keep in mind that it is the garbage collector that runs finalizers
on objects. Because it is not generally possible to predict exactly when unreferenced objects

will be garbage collected, it is not possible to predict when object finalizers will be run. Java
programmers, therefore, should avoid writing code for which program correctness depends
upon the timely finalization of objects. For example, if a finalizer of an unreferenced object
releases a resource that is needed again later by the program, the resource will not be made
available until after the garbage collector has run the object finalizer. If the program needs
the resource before the garbage collector has gotten around to finalizing the unreferenced
object, the program is out of luck.
Take help from another copy something is not OK
Sometime some object may refused GC for cleaning the memory.
When object hold the reference to resource like Database Connection, Connection to
file, Connection to printer etc. than that object will not allow GC to recleaned the
memory and GC also cant force that object.
Before invoking GC someone has to close all the resources properly.
JVM is responsible to invoke runFinalization() to clean the resources before invoking
etc.
JVM Tasks :
[i]
JVM has to detect the unused objects time to time and has to prepare the unused object
list.
[ii] When memory shortage problem is detected then JVM has to do the following :
* System.runFinalization();
* System.gc();
runFinalization() : This method is responsible to invoking finalize() method on all unused
object.
finalize() : This method is responsible for releasing the resources.
gc() : This method is responsible for cleaning the memory of all unused objects.
Note : As a developer we can call runFinalization() method and gc() method but not
guarantee for cleanup i.e. we cant force garbage collector.
----------------------------------------------**
**----------------------------------------------

MultiThreading

* threads are light-weight because they utilize minimum resources of the system. This
means they take
less memory and less processor time.
* A thread represents a separate path of execution of a group of statements.
Green Thread are scheduled by the JVM. And in the Native Thread model, the threads are
scheduled by the OS. Green threads emulate multithreaded environments without relying on
any native OS capabilities. They run code in user space that manages and schedules threads;
Sun wrote green threads to enable Java to work in environments that do not have native
thread support.

In the Green Thread model, the OS doesn't know anything about the threads used in the
JVM. It's up to the JVM to handle all the details.
The burden of thread scheduling is on the programmer's shoulders.Green threads can't take
advantage of multiple CPUs, but they have the advantage of lighter weight for context
switching.
Execution only one job at a time is called single tasking. Executing several jobs at a
time is called multi tasking. In single tasking, the processor time is wasted, but in multi
tasking, we can utilize the processor time in an optimum way.
Difference between sleep() and wait() methods : both sleep() and wait() methods are
used to suspend a thread execution for a specified time. When sleep() method is
executed inside the synchronized block, the object is still under lock. When wait()
method is executed, it breaks the synchronized block, so that the object lock is removed
and it is available.
Generally, sleep() is used for making a thread to wait for some time. But wait() is used
in connection with notify() or notifyAll() methods in thread communication.
Thread Life Cycle :
A thread is created using new Thread() statement and is executed by start() method.
The thread enters runnable state and when sleep() or wait() methods are used or when
the thread is blocked on I/O, it then goes into not runnable state. From not runnable
state, the thread comes back to the runnable state and continue running the
statements. The thread dies when it comes out of run() method. These state transitions
of a thread are called Life Cycle of a thread.
The different states of threads are as follows:
1) New When a thread is instantiated it is in New state until the start() method is called on
the thread instance. In this state the thread is not considered to be alive.
2) Runnable The thread enters into this state after the start method is called in the thread
instance. The thread may enter into the Runnable state from Running state. In this state the
thread is considered to be alive.
3) Running When the thread scheduler picks up the thread from the Runnable threads
pool, the thread starts running and the thread is said to be in Running state.
4) Waiting/Blocked/Sleeping In these states the thread is said to be alive but not runnable.
The thread switches to this state because of reasons like wait method called or sleep method
has been called on the running thread or thread might be waiting for some i/o resource so
blocked.
5) Dead When the thread finishes its execution i.e. the run() method
execution completes, it is said to be in dead state. A dead state can not be started again. If a
start() method is invoked on a dead thread a runtime exception will occur.
Why do we need synchronization?
For an answer, consider this example: You write a Java program that uses a pair of
threads to simulate withdrawal/deposit of financial transactions. In that program, one
thread performs deposits while the other performs withdrawals. Each thread
manipulates a pair of shared variables, class and instance field variables, that identifies
the financial transaction's name and amount. For a correct financial transaction, each

thread must finish assigning values to the name and amountvariables (and print those
values, to simulate saving the transaction) before the other thread starts assigning
values to name and amount (and also printing those values).
Differences between threads and processes are:1. Threads share the address space of the process that created it; processes have their
own address.
2. Threads have direct access to the data segment of its process; processes have their
own copy of the data segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must
use interprocess communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent
process.
6. Threads can exercise considerable control over threads of the same process;
processes can only exercise control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the
behavior of the other threads of the process; changes to the parent process do not affect
child processes.
synchronized keyword can be applied to static/non-static methods or a block of code.
Only one thread at a time can access synchronized methods and if there are multiple
threads trying to access the same method then other threads have to wait for the
execution of method by one thread. Synchronized keyword provides a lock on the
object and thus prevents race condition.
Q. What happens if a start method is not invoked and the run method is directly
invoked?
Ans) If a thread has been instantiated but not started its is said to be in new state. Unless
until a start() method is invoked on the instance of the thread, it will not said to be alive. If
you do not call a start() method on the newly created thread instance thread is not considered
to be alive. If the start() method is not invoked and the run() method is directly called on the
Thread instance, the code inside the run() method will not run in a separate new thread but it
will start running in the existing thread.
Q. How many locks does an object have?------------- ONE
Ans) Each object has only one lock.
Q. Can a thread hold multiple locks at the same time? ------------ YES
Ans) Yes. Once a thread acquires a lock and enters into the synchronized method / block, it
may call another synchronized method and acquire a lock on another object.
Q4) Can a thread call multiple synchronized methods on the object of which it hold the
lock?

Ans) Yes. Once a thread acquires a lock in some object, it may call any other synchronized
method of that same object using the lock that it already holds.
Q5) Can static methods be synchronized?
Ans) Yes. As static methods are class methods and have only one copy of static data for the
class, only one lock for the entire class is required. Every class in java is represented by
java.lang.Class instance. The lock on this instance is used to synchronize the static methods.
Q6) Can two threads call two different static synchronized methods of the same class?
Ans) No. The static synchronized methods of the same class always block each other as only
one lock per class exists. So no two static synchronized methods can execute at the same time.
Q7)Does a static synchronized method block a non-static synchronized method?
Ans)No As the thread executing the static synchronized method holds a lock on the class and
the thread executing the non-satic synchronized method holds the lock on the object on which
the method has been called, these two locks are different and these threads do not block each
other.
Q8) Once a thread has been started can it be started again?
Ans) No. Only a thread can be started only once in its lifetime. If you try starting a thread
which has been already started once an IllegalThreadStateException is thrown, which is a
runtime exception. A thread in runnable state or a dead thread can not be restarted.
Q9) When does deadlock occur and how to avoid it?
Ans) When a locked object tries to access a locked object which is trying to access the first
locked object. When the threads are waiting for each other to release the lock on a particular
object, deadlock occurs .
Q10) What is a better way of creating multithreaded application? Extending Thread
class or implementing Runnable?
Ans) If a class is made to extend the thread class to have a multithreaded application then this
subclass of Thread can not extend any other class and the required application will have to be
added to this class as it can not be inherited from any other class. If a class is made to
implement Runnable interface, then the class can extend other class or implement other
interface.
Q11) Can the start() method of the Thread class be overridden? If yes should it be
overridden?
Ans) Yes the start() method can be overridden. But it should not be overridden as its
implementation in thread class has the code to create a new executable thread and is
specialised.
What is thread starvation?
Ans) In a multi-threaded environment thread starvation occurs if a low priority thread is not
able to run or get a lock on the resoruce because of presence of many high priority threads.
This is mainly possible by setting thread priorities inappropriately.
* We can implements thread in Java in two ways :
1. by extending java.lang.Thread extends Object implements Runnable
2. by implementing java.lang.Runnable Interface. (only one method called void
run())
If we implements Thread through Runnable Interface then call thread like this :
Student stu=new Student();
|o|
Student stu=new Student();

Thread t=new Thread(stu);


t.start();

|r|

new Thread(stu).start();

If we implements Thread through Thread class then call thread like this :
Student stu=new Student();
stu.start();
* static int activeCount() Returns the number of active threads in the current
threads ThreadGroup .
* logn getId() Returns the identifier (ID) of the thread.
* public final String getName() Returns the thread name.
* public final void setName(String) set the new name of the thread.
* public final void checkAccess() Determines if the currently running thread has
permission to modify this thread.
* public void destroy() Deprecated. This mehtod was originally designed to destroy
this thread without any cleanup.
* public static Thread currentThread() Returns the currently executing thread.
* public static void dumpStack() prints a stack trace of the current thread. This
method is used only for debugging.
* public static boolean holdsLock(Object obj) Returns true if and only if the current
thread holds the monitor lock on the specified object.
* public final void stop() Deprecated.
* public final void suspend()- Deprecated.
* public final void resume() Deprecated.
* public final void setDaemon(boolean) makes this thread as either a daemon thread
or user thread.
* public final boolean isDaemon() Returns true if thread is a daemon thread
otherwise false.
* public static native void sleep(long) currently executing thread to sleep for the
specified number of milliseconds.

* public static void sleep(long, int) Causes the currently executing thread to sleep
(cease execution) for the specified number of milliseconds plus the specified number of
nanoseconds, subject to the precision and accuracy of system timers and schedulers.
* public void interrupt() current thread interrupting itself.
* public boolean isInterrupt() Returns true if the current thread has been
interrupted; false otherwise.
* public void run() If this thread was constructed using a separate Runnable run
object, then that Runnable object's runmethod is called; otherwise, this method does
nothing and returns.
* public synchronized native void start() causes this thread to begin execution; the
JVM calls the run method of this thraed.
* public final void join() waits for this thread to die.
* public final synchronized void join(long) waits at most millis milliseconds for this
thread to die.
* public final synchronized void join(long, int) waits at most millis milliseconds plus
nanos nanoseconds for this thread to die..
* public String toString() (Override method) Returns a string representation of this
thread, including the threadname, priority and thread group.
* main thread always runs in a Java program by default. main thread priority is 5.
* Garbage Collector thread belongs to low-priority.
* Stop a thread First of all, we should create a boolean variable which stores false.
When the user wants to stop the thread, we should store true into the variable. The
status of the variable is checked in the run() method and if it is true, the thread executes
return statement and then stops.
* when a thread has locked an object and waiting for another object to be released by
another thread and the other thread is also waiting for the first thread to release the
first object, both the threads will continue waiting forever. This is called Thread
deadlock.
* Deamon thread is a low-priority thread that executes continuously in background
doing the garbage collection operation for the Java runtime system. Deamon thread are
service providers for other threads or objects. It generally provides a background
processing.

* Thread Priorities are used by the thread schedular to decide when each thread
should be allowed to run.
Set the Thread Prioties
* If we extends Thread class then we call run method like - new Student().start(); .
a lock can be acquired on a class. This lock is acquired on the class's Class object
Thread.start() method (native method) of Thread class actually does the job of running the
Thread.run() method in a thread. If we directly call Thread.run() method it will executed in
same thread, so does not solve the purpose of creating a new thread.
We need run() & start() method both because JVM needs to create a separate thread which
can not be differentiated from a normal method call. So this job is done by start method
native
implementation
which
has
to
be
explicitly
called.
Another advantage of having these two methods is we can have any object run as a thread if
it implements Runnable interface. This is to avoid Javas multiple inheritance problems
which will make it difficult to inherit another class with Thread.
--------------------------------------------------------------------------------------------------

Generic

Type

Generic Type A Generic type represents a class or an interface that is type-safe. It can
act on any data type.
Erasure Creating a non-generic version of a generic type by the Java compiler is
called Erasure.
Generic Class A generic class represents a class that is type-safe. This means a generic
class can act upon any data type. Similarly, a generic interface is also type-safe and
hence it can use any data type. Generic classes and generic interface are also called
Parameterized types because they use a parameter that determines which data type
they should work upon.
When a generic class or generic interface is written, the programmer need not rewrite
the same class or interface whenever he wants to use or the interface with a new data
type. The same class or interface can work with any data type.
Generic types are designed to act upon objects. Hence they can not work with primitive
data types.
Since, generic class acts on any data type, we can not specify a particular data type
when designing the class. In the place of the data type, we use a generic parameter like
<T>, or <GT> and write the class as
class Hello<T>{
class code;
}
Here, <T> is called generic parameter and it determines at the time of compilation,
which data type actually the programmer wants to use with the class.
Generic Method : we can make a method alone as generic method, by writing the
generic parameter before the method return type as:
<T> void display(){

}
Generic Interface :
-------------------------------------------------------------------------------------------

java.lang

Package

Object Class : default Super Class for All Java Class. Contains 11 Methods.
public class Object{
public final native class getClass();
public native int hashCode();
public String toString();
public boolean equals(Object);
protected void finalize() throws Throwable;
protected native Object clone() throws CloneNotSupportedException ;
public final native void notify();
public final native void notifyAll();
public final void wait() throws InterruptedException;
public final native void wait(long) throws InterruptedException;
public final void wait(long, int) throws InterruptedException;
}
System Class : (used to get the information about current System)
By using the System class we can interact with the default input or output device and other
part of the machine.
Inside the System class following are the properties available by using that we can interact
with the default input or output device.
public static final InputStream in;
public static final PrintStream out;
public static final PrintStream err;
When the JVM will be started then some default object will be created. Some Object
reference will be stored in the reference variable defined in the System class to interact with
the default input/output device. If we want we can change the reference to point some
another input or output device by using the following method with the System class.
public static void setIn(InputStream);
public static void setErr(printStream);
public static void setOut(printStream);
System class will be used to access the information of the System. The information will be
always some for one machine so the member of the System class is defined as static. In this
condition no need to create the object of the System class. So, the Constructor of the System
class is defined as private.
The Constructor of the System class is private so we can not create the object for the
System class.
Runtime Class : (in java.lang Package), implemented as Singleton class.

public class Runtime extends Object


* used to get the information about the current running JVM or to perform some operation
with JVM.
* The Constructor of the runtime class is defined as private So, We can not create of the
object of the
Runtime class explicitly.
* Inside the Runtime class almost all the methods are defined as non-static so to use the
method we need to use the object of Runtime class. We can use the following method to
access the object of Runtime class.
public static Runtime getRuntime();
* Every Java application has a single instance of class Runtime that allows the application to
interface with the environment in which the application is running.
Reflection :
Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at
runtime, without knowing the names of the classes, methods etc. at compile time. It is also
possible to instantiate new objects, invoke methods and get/set field values using reflection.
It's useful because it allows us to change the runtime behaviour depending on the meta
information of our program, that is, we can check the return type of a function and change
the way we handle the situation.
Using the facility of Reflection in our program we have to import java.lang.reflect Package.
There are following type of Class available in java.lang.reflect Package :
-------------------------------------------------------------------------------Field - A Field provides information about, and dynamic access to, a single field of a class or
an interface. The reflected field may be a class (static) field or an instance field.
Method - A Method provides information about, and access to, a single method on a class or
interface. The reflected method may be a class method or an instance method (including an
abstract method).
Constructor - Constructor provides information about, and access to, a single constructor for
a class.
Modifier The Modifier class provides static methods and constants to decode class and
member access modifiers. The sets of modifiers are represented as integers with distinct bit
positions representing different modifiers.
AccessibleObject - The AccessibleObject class is the base class for Field, Method and
Constructor objects. It provides the ability to flag a reflected object as suppressing default
Java language access control checks when it is used. The access checks--for public, default
(package) access, protected, and private members--are performed when Fields, Methods or
Constructors are used to set or get fields, to invoke methods, or to create and initialize new
instances of classes, respectively.
Array The Array class provides static methods to dynamically create and access Java
arrays.

Proxy Proxy provides static methods for creating dynamic proxy classes and instances, and
it is also the superclass of all dynamic proxy classes created by those methods.
ReflectPermission The Permission class for reflective operations. A ReflectPermission is a
named permission and has no actions. The only name currently defined is
suppressAccessChecks, which allows suppressing the standard Java language access checks
-- for public, default (package) access, protected, and private members -- performed by
reflected objects at their point of use.
There are following type of Interface available in java.lang.reflect Package :
-------------------------------------------------------------------------------InvocationHandler InvocationHandler is the interface implemented by the invocation
handler of a proxy instance.
Member Member is an interface that reflects identifying information about a single
member (a field or a method) or a constructor.
There are following type of Exception available in java.lang.reflect Package :
-------------------------------------------------------------------------------InvocationTargetException
MalformedParameterizedTypeException
UndeclaredThrowableException
If we want to load the class dynamically then we can use the following methods :
java.lang.Class
public static Class forName(String className);
public static Class forName(String className, boolean init, ClassLoader
loader);
If we want to create the object of the class dynamically, we can use the following
method :
public Object newInstance();
If we want to verify one object is of specific type or not then we can use the following
method :
public Object isInstance(Object obj);
If we want to access all the public methods defined in the current class or inherited
from the super class then we can use the following method :
public Method[] getMethods();
If we want to access all the methods defined in the current class referred by the class
type object, then we can use the following method :
public Method[] getDeclaredMethods();
To get the information about the fields we can use the following methods :
public Field[] getFields();

public Field[] getDeclaredFields();


To get the information about the Constructor we can use the following methods :
public Constructor[] getConstructors();
public Constructor[] getDeclaredConstructors();
To get the information about the Interface we can use the following methods :
public Class[] getInterfaces();
To get the information about the Modifier we can use the following methods :
public int getModifier();
To get the information about the Inner class we can use the following methods :
public Class[] getClasses();
public Class[] getDeclaredClasses();
Math :
* Math class is a final Class available in java.lang Package.
* Math class contains methods for performing basic numeric operations.
* all the methods of Math class are static.
* Important methods of Math class : sin(), cos(), tan(), log(), log10(), pow(), sqrt(), abs(),
ceil(), floor(), min(),
max(), round(), random(), toRadians(), toDegrees().
* random() method returns a random number between 0 and 1 no one can guess this
number.
----------------------------------------------------------------------------------------------------

Input-Output

* Stream are mainly useful to move data from one place to another place. This concept
can be used to receive
data from an input device and send data to an output data. Streams can be
categorized as input stream and
output stream.
* Input streams are streams which receive or read data while Output streams are
streams which send or write
data. All streams are represented by classes in java.io Package.
* Streams are Classified in two types Byte Streams and Character/Text Streams.
* Bytes Steams represents data in the form of individual bytes. Byte streams are used
to handle any type of
data like text, images, audio and video files.

* Character/Text Streams represents data as characters of each 2 bytes. It always store


and retrieve data in the
form of characters (or text) only.
* Buffer class provide a buffer (temporary block of memory) which is first filled with
characters and then all
the characters from the buffer can be at once written into the file. Buffered classes
should be used always in
connection to other stream classes.
* Default buffer size used by any buffered class : 512 bytes.
* Serialization : Java provides a mechanism, called object serialization where an object
can be represented as a
sequence of bytes that includes the object's data as well as information about the
object's type and the types
of data stored in the object. Used for transmit object across network.
# Most impressive is that the entire process is JVM independent, meaning an object
can be serialized on one
platform and deserialized on an entirely different platform.
# When serializing an object to a file, the standard convention in Java is to give the file
a .ser extension.
# The process of serializing an object is also called deflating or marshalling an
object. The opposite operation,
extracting a data structure from a series of bytes, is deserialization (which is also
called inflating or
unmarshalling).
# Serializable interface should be implemented by the class whose objects are to be
stored into the file.
# Serializable is a Marker Interface. Marking Interface is useful to mark the objects of
a class for a special
purpose. Serializable Interface marks the class objects as Serializable so that they
can be written into a file.
# If Serializable Interface is not implemented by the class, then writing that class
objects into a file will lead to
NoSerializableException.
*
------------------------------------------- Collection Framework --------------------------------------

* Collection Framework : A Collection Framework is a class library to handle groups


of objects. Collection framework is implemented in java.util Package.
* All the Collection classes in java.util Package are the implemented classes of different
interfaces :
Set <T>
List <T>
Queue <T>
Map <K,V>

HashSet<T>, LinkedHashSet<T>, TreeSet<T>


ArrayList<T>, LinkedList<T>, Stack<T>,
Vector<T>
LinkedList<T>
HashMap<K,V>, HashTable<K,V>,
TreeMap<K,V>, LinkedHashMap

* There are 4 ways to retrieve elements from a collection object :


1. for-each loop :
2. Iterator Interface (add JDK 1.2): Retrieve elements in forward direction, takes
the place of Enumeration.
Iterator differ from Enumerations - Remove element, Method name improved in
Iterator names are
easy to follow.
Method : public abstract void remove(); public abstract boolean hasNext(); public
abstract Object next();
3. ListIterator Interface : extends from Iterator, Retrieve elements in forward &
backward direction both.
public abstract void add(Object o); p a boolean hasNext();
p a boolean
hasPrevious();
p a Object next();
p a int nextIndex();
p a Object
previous();
p a int previousIndex();
p a void remove();
p a void
set(Object o);
Note : Iterator is applicable for every Collection implemented class object but
ListIterator is applicable only for List implemented class objects.
4. Enumeration Interface : (Legacy Interface, Introduced in JDK 1.0)
retrieve elements one by one, used to specify input streams to a SequenceInputStream.
We
can
get
Enumeration
Object
only
for
legacy
classes
(Vector,Stack,Hashtable,Properties,Dictionary)
Method : pubic abstract boolean hasMoreElements();
pubic abstract Object
nextElements();
enhancement in JDK 1.4 version of Collection Framework :
LinkedHashMap, IdentityHashMap.
Set- not null, not duplicate, ordered
A set represents a collection of elements.
Order of the elements may change in the

LinkedHashSet,

List- null, duplicate, not ordered


A List represents ordered collection of
elements. List preserves the order of

set. (Ordered)
not allow duplicate values.
Accessing elements by their index is not
possible.
not allow null elements.

elements in which they are entered.


Allow duplicate values.
Accessing elements by index is possible.
Allow null elements.

HashSet : class HashSet extends AbstractSet implements Set,Clonable,Serializable{}


* HashSet is not Synchronized, multiple thread can access HashSet concurrently.
*
We can Synchronized HashSet --------- Collections.SynchronizedSet(new
HashSet());
neither allows duplicate elements nor order or position its elements.
* HashSet default initial capacity is 16 and the default load factor is 0.75.
Note : loadfactor is determine the point where the capacity of HashSet would be
increased internally.
LinkedHashSet : class LinkedHashSet extends HashSet implements
Set,Cloneable,Serializable{
* extends from HashSet and does not contains any additional memebers on its own.
* LinkedHashSet maintains a linked list of the entries in the set, in the order in which
they were inserted.
* Contains 4 Construts.
TreeSet : class TreeSet extends AbstractSet implements
NavigableSet,Clonable,Serializable{}
* Objects are stored in Sorted and Ascending Order.
* underlaying data structure is Balanced Tree.
* not Synchronized, added in JDK 1.2
* Duplicate value is not allowed.
* use compareTo() method on elements.
* Insertion order is not preserved. (means order of data may change according to
data)
* Access and retrieval times are quite fast.
* best choice for storing large amount of sorted information that must be found
quickly.
* for an Empty TreeSet as first element null value can be inserted but after inserting
that first value if we are
trying to insert any other objects then we will get NullPointerException.
* For an non empty TreeSet if we are trying to insert null value at run time we will get
NullPointerException.
ArrayList : public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, Serializable
* grow memory dynamically.
* allows duplicate values.
* use equals() method on elements.

* ArrayList is not Synchronized this means that when more than one thread acts
simultanuously on the
ArrayList object, the result may be incorrect in some cases.
* providing fast random access and fast traversal.
Sort ArrayList :
Collections.sort(list);
for(int i=0; i<list.size(); i++){
System.out.println(list.get(i));
}
Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of
ArrayList<String> = new ArrayList<String>();
Ans) It is preferred because:
If later on code needs to be changed from ArrayList to Vector then only at the declaration
place we can do that.
The most important one If a function is declared such that it takes list. E.g void
showDetails(List list);
When the parameter is declared as List to the function it can be called by passing any
subclass of List like ArrayList,Vector,LinkedList making the function more flexible
Vector : public class Vector<E> extends AbstractList<E>
implements List<E>, RandomAccess,Cloneable, Serializable
* Vector size can grow or shrink as needed to accommodate adding and removing
items after the Vector has
been created.
* Vector is Synchronized. (thread safe)
* like Array, Vector component is accessed using integer index no.
* Vector default capacity is 10.
* Vector contains duplicate values.
* Vector implementation based on Resizable Array Data Structure.
* Vector use equals() method.

Difference between ArrayList & Vector :


ArrayList is not Synchronized. (not
thread safe)
Data is retrieved using the get()
method.
No default size.
ArrayList increases by half of its size
when its size is increased.
java.util.ArrayList was introduced in
java version1.2, as part of java
collections framework.
ArrayList is Faster than Vector.

Vector is Synchronized. (thread safe)


data is retrieved using the elementAt()
method.
Default size is 10.
Vector doubles the size of its array
when its size is increased.
java.util.Vector came along with the
first version of java development kit
(JDK 1.0).
Slower and Verctor is Legacy Class.

LinkedList : public class LinkedList<E> extends AbstractSequentialList<E>


implements List<E>, Queue<E>, Cloneable, Serializable
The LinkedList is implemented using nodes linked to each other. Each node contains a
previous node link, next node link, and value, which contains the actual data. When
new data is inserted, a node is inserted and the links of the surrounding nodes are
updated accordingly. When one is removed, linked list data structure, allowing easy
inserts/deletions anywhere in the structure, but really slow random accesses as the
access must start at an end to get to the specific position.
* Contains a group of elements in the form of nodes. Each node has 3 fields.
* Linked List conaitsn duplicate value.
* Linked List use equals() and compareTo() method.
* Linked List in not Synchronized.
Difference between ArrayList & Linked List :
ArrayList
Linked List
Method equals()
Method - equals() and compareTo().
Data Structure Resizable Array
Data Structure Linked List
Adding and deleting at the start and
Linked lists are faster for inserts and
middle of the ArrayList is slow,
deletes anywhere in the list, since all
because all the later elements have to
we do is update a few next and
be copied forward or backward. (Using
previous pointers of a node.
System.arrayCopy())
Fast random Access.
Slow random Access.
Each node contains extra memory for
Not required.
store previous and next node address.
Stack : public class Stack<E> extends Vector<E>
* The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends
class Vector with five
operations that allow a vector to be treated as a stack.
* The usual push and pop operations are provided, as well as a method to peek at the
top item on the stack, a
method to test for whether the stack is empty, and a method to search the stack for
an item and discover how
far it is from the top.
* When a stack is first created, it contains no items.
Queues : A Queue represents arrangements of elements in FIFO (First In First Out)
Order. This means that an element that is stored as a first element into the queue will
be removed first from the Queue.
Maps : Map is an Interface. Map store elements in the form of Key and Value pairs. If
key is provided its corresponding value can be obtained. Of course, the keys should
have a unique values.

HashMap : public class HashMap<K,V> extends AbstractMap<K,V> implements


Map<K,V>,
Cloneable, Serializable
* stores the elements in the form of key-value pairs.
* key should be unique we cant use duplicate data for keys.
* Hash map is not Synchronized.
* multiple threads can access HashMap object, So we may get unreliable results.
* 0.75 is the default load factor of HashMap.
Hashtable : public class Hashtable<K,V> extends Dictionary<K,V>
implements Map<K,V>, Cloneable, Serializable
* Hashtable is Synchronized.
* 0.75 is the default load factor of Hashtable.
HashMap (Java Class) JDK 1.2
Hashtable (Legacy Class) JDK 1.0
not Synchronized (not thread-safe)
Synchronized (thread-safe)
In the case of single thread, HashMap In case of Multiple threads, using
is faster than Hashtable.
Hashtable is advisable. With a single
thread, Hashtable become slower.
Allows to store null keys and null
Does not allow.
values.
Iterator in the HashMap is fail-fast.
Enumeration for the Hasthtable is not
This means Iterator will produce
fail-fast. This means even if
exception if concurrent updates are
concurrent updations are done to
made to the HashMap.
Hashtable, there will not be any
incorrect results produced by the
Enumeration.
HashMap does not guarantee that the Order is constant.
order of the map will remain constant
over time.
HashMap has more complex hashing
algorithm than Hashtable.
Performance is high.
Performance is slow.
Note : We can
HashMap());

Synchronized

HashMap

Collections.synchronizedMap(new

TreeMap :
public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable
* TreeMap can be used to store a group of objects as key-value pairs where all the
entries are arranged to some sorting order of Keys.
* the underlaying data structure is RED-BLACK Tree.
* use equals() and compareTo() method.
* Duplicates keys are not allowed but values can be duplicate.
* Insertion order is not preserved because insertion is based on some sorting order.

* contains null values.


* for non empty TreeMap if we are trying to insert null keys we will get
NullPointerException.
* The map is sorted according to the natural ordering of its keys, or by
a Comparator provided at map creation time, depending on which constructor is used.
LinkedHashMap : (same as HashMap, introduced in JDK 1.4, not Syncronized)
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
* LinkedHashMap is a child of HashMap.
* underlaying data structure is a combination of HashTable amd LinkedList.
* Insertion order is preserved.
* LinkedHashMap is not Synchronized.
* A special constructor is provided to create a linked hash map whose order of iteration
is the order in which
its entries were last accessed, from least-recently accessed to most-recently (accessorder).
Arrays : public class Arrays extends Object
* available in java.util Package.
* This class contains various methods for manipulating arrays (such as sorting and
searching).
* This class also contains a static factory that allows arrays to be viewed as lists.
* The methods in this class all throw a NullPointerException if the specified array
reference is null, except
where noted.
Calendar : (Abstract Class)
public abstract class Calendar extends Object
implements Serializable, Cloneable, Comparable<Calendar>
It provides methods for converting between a specific instant in time and a set
of calendar fields such as YEAR,MONTH, DAY_OF_MONTH, HOUR, and so on, and
for manipulating the calendar fields, such as getting the date of the next week. An
instant in time can be represented by a millisecond value that is an offset from
the Epoch, January 1, 1970 00:00:00.000 GMT (Gregorian).
The class also provides additional fields and methods for implementing a concrete
calendar system outside the package. Those fields and methods are defined asprotected.
Like other locale-sensitive classes, Calendar provides a class method, getInstance, for
getting a generally useful object of this type. Calendar's getInstance method returns
a Calendar object whose calendar fields have been initialized with the current date and
time:
Calendar cal = Calendar.getInstance();
A Calendar object can produce all the calendar field values needed to implement the
date-time formatting for a particular language and calendar style (for example,
Japanese-Gregorian, Japanese-Traditional). Calendar defines the range of values
returned by certain calendar fields, as well as their meaning. For example, the first

month of the calendar system has value MONTH == JANUARY for all calendars.
Other values are defined by the concrete subclass, such as ERA. See individual field
documentation and subclass documentation for details.
public class Date
extends Object
implements Serializable, Cloneable, Comparable<Date>
The class Date represents a specific instant in time, with millisecond precision.
StringTokenizer
public class StringTokenizer extends Object implements Enumeration<Object>
The StringTokenizer class allows an application to break a string into tokens. The
tokenization method is much simpler than the one used by the StreamTokenizerclass.
The StringTokenizer methods do not distinguish among identifiers, numbers, and
quoted strings, nor do they recognize and skip comments.
The set of delimiters (the characters that separate tokens) may be specified either at
creation time or on a per-token basis.
Class Locale
public final class Locale
extends Object implements Cloneable, Serializable
A Locale object represents a specific geographical, political, or cultural region. An operation
that requires a Locale to perform its task is called locale-sensitive and uses the Locale to
tailor information for the user. For example, displaying a number is a locale-sensitive
operation--the number should be formatted according to the customs/conventions of the
user's native country, region, or culture.
Create a Locale object using the constructors in this class:
Locale(String language);
Locale(String language, String country);
Locale(String language, String country, String variant);
-------------------------------------------------------------------------------------------------

Wrapper

Class

* A Wrapper class is a class whose object wraps or contains a primitive data type.
When we create an object to
a wrapper class, it contains a field and in this field, we can store a primitive data
type.
* java.lang Package provides all Wrapper Classes for each of the primitive data.
* All Wrapper class are Final & immutable so their state can not be changed.
* There are 8 Wrapper Class corresponding to primitive to data types
- Character, Byte, Short, Integer, Long, Float, Double, Boolean.

* Number is an abstract Super class whose subclasses are Byte, Short, Integer, Long,
Float, Double.
So the methods of Number class are commonly available in all these Subclasses.
* Character class has only one Construtor.

Character(char ch)

* Byte, Short, Integer, Long, Double, Boolean classes have two Constructors.
Byte(byte b) (String str)
* Float class has three Constructors.

Float(float f) (double d) (String str)

* Need of Wrapper Class :


Wrapper Class Convert primitive data types into objects and this is needed on
internet to communicate between two applications.
The Classes in java.util package handle only objects and hence wrapper class
help in this case also.
Boxing : Converting primitive datatype into object. Unboxing : Converting object into
primitive dataytpe
Autoboxing : Converting primitive into object form automatically. Done in generic
types. (JDK 1.5 Feature)
--------------------------------------------------------------------

StringBuffer,

StringBuilder,

String

StringBuffer : (final, thread-safe, mutable, synchronized, reliable result, take more


time than StringBuilder)
StringBuffer is a Final Class.
StringBuffer class objects are Mutable, so they can be modified.
Synchronized by default. (Synchronization means locking the object).
Implementing the Synchronization mechanisam will take some time for the JVM.
Hence StringBuffer will take more execution time than StringBuilder.
StringBuffers are safe for use by multiple threads. And Provides reliable result.
Memory Allocation :
Default Capacity : 16, next time : 16*2+2= 34, next time : 34*2+2=70, next time :
70*2+2=142
StringBuilder : (Final, Mutable, not Synchronized, Add new in JDK 1.5)
Added in JDK 1.5. Same as StringBuffer.
StringBuilder class objects are Mutable.
StringBuilder is not Synchronized, it allows several threads to act on it
simultaneously.
This class is designed for use as a drop-in replacement for StringBuffer in places
where the string buffer was being used by a single thread (as is generally the case)
Memory Allocation :

Default Capacity : 16, next time : 16*2+2= 34, next time : 34*2+2=70, next time :
70*2+2=142
String : (final, immutable)
public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence
* String is a Final Class so we can not extends String Class and can not Override
String class any methods.
* String class object are immutable and hence their contents can not be modified.
* String is a class in java.lang package. But in java, all classes are also considered as
data types. So we can take
String as a data type.
* Creating String Object without new Operator :
String str1 = Krishu;
[i]
Checks whether the String Literal is available in the Constant pool or not.
[ii] If String Literal is available in the pool then its address will be assigned to reference
variable.
[iii] If String Literal is not available in the pool then new String object will be created in
the pool and newly created String object address will be assigned to reference
variable.
* Creating String Object with new Operator :
String str1 = new String (Krishu);
[i]
Checks whether the String Literal is available in the pool or not.
[ii] If String Literal is available in the pool then ignores.
[iii] If String Literal is not available in the pool then new String object will be created in
the pool.
[iv] New String object will be created outside the pool and address of the object which is
outside the pool will be assigned to reference variable.
How to sort list of strings - case insensitive?
Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Field Summary
static CASE_INSENSITIVE_ORDER
Comparator<String> A Comparator that orders String objects as by compareToIgnoreCase.
Constructor Summary
String()
Initializes a newly created String object so that it represents an empty character sequence.
String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's default
charset.
String(byte[] bytes, Charset charset)

Constructs a new String by decoding the specified array of bytes using the specified charset.
String(byte[] ascii, int hibyte)
Deprecated. This method does not properly convert bytes into characters. As of JDK 1.1,
the preferred way to do this is via the String constructors that take a Charset, charset name,
or that use the platform's default charset.
String(byte[] bytes, int offset, int length)
Constructs a new String by decoding the specified subarray of bytes using the platform's
default charset.
String(byte[] bytes, int offset, int length, Charset charset)
Constructs a new String by decoding the specified subarray of bytes using the specified
charset.
String(byte[] ascii, int hibyte, int offset, int count)
Deprecated. This method does not properly convert bytes into characters. As of JDK 1.1,
the preferred way to do this is via the String constructors that take a Charset, charset name,
or that use the platform's default charset.
String(byte[] bytes, int offset, int length, String charsetName)
Constructs a new String by decoding the specified subarray of bytes using the specified
charset.
String(byte[] bytes, String charsetName)
Constructs a new String by decoding the specified array of bytes using the specified charset.
String(char[] value)
Allocates a new String so that it represents the sequence of characters currently contained in
the character array argument.
String(char[] value, int offset, int count)
Allocates a new String that contains characters from a subarray of the character array
argument.
String(int[] codePoints, int offset, int count)
Allocates a new String that contains characters from a subarray of the Unicode code point
array argument.
String(String original)
Initializes a newly created String object so that it represents the same sequence of characters
as the argument; in other words, the newly created string is a copy of the argument string.
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the
string buffer argument.
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the
string builder argument.
Method Summary
char charAt(int index)Returns the char value at the specified index.

int codePointAt(int index)Returns the character (Unicode code point) at the


specified index.
int codePointBefore(int index)Returns the character (Unicode code point) before
the specified index.
int codePointCount(int beginIndex, int endIndex)
Returns the number of Unicode code points in the specified text range of this
String.
int compareTo(String anotherString)Compares two strings lexicographically.
int compareToIgnoreCase(String str)Compares two strings lexicographically,
ignoring case differences.
String concat(String str)
string.

Concatenates the specified string to the end of this

boolean contains(CharSequence s)
sequence of char values.

Returns true if this string contains the specified

boolean contentEquals(CharSequence cs)Compares this string to the specified


CharSequence.
boolean contentEquals(StringBuffer sb)Compares this string to the specified
StringBuffer.
static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
boolean endsWith(String suffix)Tests if this string ends with the specified suffix.
boolean equals(Object anObject)Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
static String format(Locale l, String format, Object... args)
Returns a formatted string using the specified locale, format string, and
arguments.
static String format(String format, Object... args)
Returns a formatted string using the specified format string and arguments.
byte[] getBytes()
Encodes this String into a sequence of bytes using the platform's default
charset, storing the result into a new byte array.
byte[] getBytes(Charset charset)
Encodes this String into a sequence of bytes using the given charset, storing
the result into a new byte array.
void getBytes(int srcBegin, int srcEnd, byte[] dst, int dstBegin)

Deprecated. This method does not properly convert characters into bytes. As
of JDK 1.1, the preferred way to do this is via the getBytes() method, which
uses the platform's default charset.
byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing
the result into a new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
int hashCode()Returns a hash code for this string.
int indexOf(int ch)Returns the index within this string of the first occurrence of
the specified character.
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.
int indexOf(String str)Returns the index within this string of the first occurrence
of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
String intern()Returns a canonical representation for the string object.
boolean isEmpty()Returns true if, and only if, length() is 0.
int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified
character.
int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified index.
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the
specified substring.
int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified
substring, searching backward starting at the specified index.
int length()Returns the length of this string.
boolean matches(String regex)Tells whether or not this string matches the given
regular expression.
int offsetByCodePoints(int index, int codePointOffset)
Returns the index within this String that is offset from the given index by
codePointOffset code points.

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int
len)Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in
this string with newChar.
String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence
with the specified literal replacement sequence.
String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular
expression with the given replacement.
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular
expression with the given replacement.
String[] split(String regex)Splits this string around matches of the given regular
expression.
String[] split(String regex, int limit)Splits this string around matches of the given
regular expression.
boolean startsWith(String prefix)Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with
the specified prefix.
CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
String substring(int beginIndex)Returns a new string that is a substring of this
string.
String substring(int beginIndex, int endIndex)Returns a new string that is a
substring of this string.
char[] toCharArray()Converts this string to a new character array.
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the
default locale.
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the
given Locale.
String toString()This object (which is already a string!) is itself returned.
String toUpperCase()

Converts all of the characters in this String to upper case using the rules of the
default locale.
String toUpperCase(Locale locale)Converts all of the characters in this String to
upper case using the rules of the given Locale.
String trim()Returns a copy of the string, with leading and trailing whitespace
omitted.
static String valueOf(boolean b)Returns the string representation of the boolean argument.
static String valueOf(char c)Returns the string representation of the char argument.
static String valueOf(char[] data)Returns the string representation of the char array
argument.
static String valueOf(char[] data, int offset, int count)
Returns the string representation of a specific subarray of the char array
argument.
static String valueOf(double d)Returns the string representation of the double argument.
static String valueOf(float f)Returns the string representation of the float argument.
static String valueOf(int i)Returns the string representation of the int argument.
static String valueOf(long l)Returns the string representation of the long argument.
static String valueOf(Object obj)Returns the string representation of the Object argument.
--------------------------------------------------------------------------------------------------------------------------------------------Operator : An operator is a symbol that perform an operation on one, two or three
operands.
Arithmetic
Operator
Unary Operator
Assignment
Operator
Relational Operator
Logical Operator
Boolean Operator
Bitwise Operator

- (Unary Minus)

%
++

(total 5)
--

(total 3)

(total 1)

> >= < <= == !=


$$
||
!
& (and)
| (or)
! (not)
~ (bitwise Complement)
& (bitwise
AND)
| (bitwise OR)
^ (bitwise OXR)
<< (bitwise
left shift)
>> (bitwise right shift)
>>> (bitwise unsigned right shift)

(total 6)
( total 3)
(total 3)
(total 7)

Note :
* Positive numbers are represented in binary using 1s complement
notation.
* Negative numbers are represented in binary using 2s complement notation.

>> will protect the sign bit whereas the >>> operator will not protect the signn bit. It
always fills 0 in the sing bit.
Abstract Class :
* Abstract class contains All Properties like a normal class and 0 or more abstract
method.
* If any abstract method is not implemented, then that sub class should be declared as
abstract.
* Abstract class contains incomplete methods, it is not possible to estimate the total
memory required to create the
object, So, JVM can not create objects to an abstract class.
* We can not create object of abstract class but we can create a reference of abstract
type.
* The reference of abstract class can be used to refer to objects of its subclasses.
------------------------------------------------------------------------------------

JDK

1.5

New

Features

# Static Import : (New Added feature of JDK 1.5)


Syntax com.jlcindia.Student.*;
* access only static properties of give class.
* we can cant access any other methods or variables except static.

import static

List of JDK 1.5 New Features :


1. Static Imports
2. var args (Variable Arguments)
3. Enhanced for loop
4. autoboxing
5. generics
6. enums
7. annotations
8. New APIs

# var args (Variable Argument) : allows to pass variable no. of parameters.


void show(int no){
Note : only put (3 dots). If dots will be less or more than 3
then gives syntax error
for(int i:no){
System.out.println(i);
}
}
obj.show(10,20,30);
OK
obj.show(10,20,30,40,50);
OK
* Only one variable argument is allowed for one method.
* variable argument allowed must be the last argument.

* When a compatable or matching method is found with variable argument method


and fixed argument method, fixed argument method only takes the priority.
* When we define a method with var args then array will be created with variable no.
of argument and that array will be passed as parameter to method.
* in the variable argument we can pass mix data types of values.
# Enums :
* for every enum java.lang.Enum is Super class. Enum is an Abstract Class.
* we can't create object of enum but We can create reference object of enum.
* enum can contain static and instance block.
* enum can contain static method and instance method.
* enum can contain instance, static, final variable.
* enum can not contain abstract method.
* enum can contain constructors.
* enum can not declare as a abstract or static or final.
* enum can contain inner enum.
* enum can implement interface.
* enum can not extends another enum and class.
* enum can not declare as a private, protected only public should be declare.
# New APIs :
* StringBuilder * Formatter Its functionality is same as printf() function in C Language.
* Scanner - Its functionality is same as scanf() function in C Language.
* PriorityQueue It is representations a data structure to hold group of individual
objects prior to processing based on some priority. This queue orders elements
according to an order specified at construction time, which is specified either according
to their natural order (seeComparable), or according to a Comparator, depending on
which constructor is used. A priority queue does not permit null elements. A priority
queue relying on natural ordering also does not permit insertion of non-comparable
objects (doing so may result in ClassCastException).
The head of this queue is the least element with respect to the specified ordering. If
multiple elements are tied for least value, the head is one of those elements -- ties are
broken
arbitrarily.
The
queue
retrieval
operations poll, remove, peek,
and element access the element at the head of the queue.
A priority queue is unbounded, but has an internal capacity governing the size of an
array used to store the elements on the queue. It is always at least as large as the queue
size. As elements are added to a priority queue, its capacity grows automatically. The
details of the growth policy are not specified.
This class and its iterator implement all of the optional methods of
the Collection and Iterator interfaces.
The
Iterator
provided
in
method iterator() is not guaranteed to traverse the elements of the PriorityQueue in any
particular
order.
If
you
need
ordered
traversal,
consider
using Arrays.sort(pq.toArray()).
Its method based on first in first out basis. 3 methods introduced : peek(), poll(), offer()
It is a subclass of Collection Interface.

Constructor :
* Constructor is similar to a method that is used to initialize the instance variables of a
class.
* Constructor has the same name as the name of the class to which it belongs.
* Constructor automatically called and executed at the time of creating an object.
* When the programmer does not write any constructor in a class, the Java Compiler
writes a default Constructor and initialized the instance variables with the default
values.
* The access modifier of the default constructor is same as access modifier of the class
(public & default only).
A Constructor has the following Characteristics :
----------------------------------------------------- A Constructor does not return any value, not even void.
A Constructor is called and executed only once per object. This means when we create
an object, the constructor is called.
A Constructor declared only public, protected and private modifiers.
A Constructor does not declared static, final, abstract, synchronized, native, transient,
volatile, strictfp.
The access modifier for the default constructor will be same as access modifier of the
class.
If Constructor will be declared as private modifier then we can not create object of that
class.
If we are using the return type with the constructor then that will be treated as method,
that cant be used as Constructor.
Constructors are always executed by the same thread.
Constructors may include parameters of various types. When the constructor is
invoked using the new operator, the types must match those that are specified in the
constructor definition. JVM differentiates constructors on the basis of arguments
passed in the constructor.
If we don't define a constructor for a class, A default constructor with no arguments
will be called automatically by the JVM. The default constructor calls the default
parent constructor (super()) and initializes all instance variables to default value (zero
for numeric types, null for object references, and false for boolean).
this(...) - Calls another constructor in same class. Often a constructor with few
parameters will call a constructor with more parameters, giving default values for the
missing parameters. Use this to call other constructors in the same class.
super(...) - Use super() to call a constructor in a parent class. Calling the constructor
for the Superclass must be the first statement in the body of a constructor. If we are
satisfied with the default constructor in the Superclass, there is no need to make a call
to it because it will be supplied automatically.

If we want to invoke the Superclass parameterized constructor then we need to invoke


explicitly.
The order of invoking the Constructor will be first sub-class constructor then super
class constructor but the order of execution the constructor will be first superclass then
sub-class.
Differences between Default Constructor and Parameterized Constructor :
---------------------------------------------------------------------------------Default Constructor
Parameterized Constructor
does not have any parameters.
have 1 or more parameters.
Default Constructor is useful to initialize
Parameterized Constructor is useful to
all objects with same data.
initialize each object with different data.
When data is not passed at the time of
When data is passed at the time of
creating an object, default constructor is
creating an object, parameterized
called.
constructor is called.
More than one parameterized
only one default Constructor in a class.
constructors.
Differences between methods and constructors :
--------------------------------------------------------Constructor
Method
A Constructor is used to initialize the
A method is used for any general purpose
instance variables of a class.
processing or calculations.
A Constructors name and class name
A methods name and class name can be
should be same.
same or different.
called at the time or creating the object.
called after creating the object.
A Constructor is called only once per
called several times on the object.
object.
A Constructor is called and executed
A method is executed only when we call
automatically.
it.
can not return any value and not even
return any value according to the
void.
requirement and even void.
A Constructor can be declared only
A method can be declared any modifier.
public, protected and private modifier.
public final class Locale
extends Object
implements Cloneable, Serializable
A Locale object represents a specific geographical, political, or cultural region. An operation
that requires a Locale to perform its task is called locale-sensitive and uses the Locale to
tailor information for the user
Create a Locale object using the constructors in this class:
Locale(String language)

Locale(String language, String country)


Locale(String language, String country, String variant)

Interface
Allow
Not
Contains
duplicate
Synchronized
null
value
Allow
Contains
Synchronized duplicate
null
value

JDK

Order/
sorted

Methods
that can be
called on
elements

Data Str
on wh
impleme
is ba

1.2

Not order

equals()

Resizabl

1.0

Not order

equals()

Resizabl

List

List

or
cy
ss

List

ed
t

List<E>
Queue<E>
Deque<E>

Allow
Not
Contains
duplicate
Synchronized
null
value

1.2

Insertion/
Priority/
equals()
dequeue compareTo()
order

Set<E>

not
Not
Unique
Contains
Synchronized elements
null

1.2

No Order

equals()
hashCode()

Hashtab
Linked

ed
Set

Set<E>

Not
Unique
Synchronized elements

1.4

Insertion
order

equals()
hashCode()

Hash tab
doublylis

Set

Set<E>

Not
Unique
Synchronized elements

1.2

Sorted

compareTo()

Balance

Map

Map<K,V>

Not
Synchronized

Unique
Keys

1.2

No Order

equals()
hashCode()

Hash
using a

able
cy
ss

Map<K,V>

Synchronized

Unique
Keys

Set

ed
Map

Map

ity
ue
y

Not
Synchronized

Unique
Keys

Sorted
Map<K,V>
Not
Naviga
Synchronized
bleMap<K,V>

Unique
Keys

Map<K,V>

Linke

equals()
hashCode()

1.4

Key
insertion
order/
Access
order of
entries

equals()
hashCode()

Hash tab
doublylis

1.2

Stored in
equals()
key order compareTo()

Balance

eue
What is a ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded
by a program to create the program's appearance to the particular locale in which it is
being run.
1. What is fail-fast property?
At high level - Fail-fast is a property of a system or software with respect to its
response to failures. A fail-fast system is designed to immediately report any failure or
condition that is likely to lead to failure. Fail-fast systems are usually designed to stop
normal operation rather than attempt to continue a possibly-flawed process. When a
problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a nonintuitive technique: "failing immediately and visibly" sounds like it would make your
software more fragile, but it actually makes it more robust. Bugs are easier to find and
fix, so fewer go into production. In Java, Fail-fast term can be related to context of
iterators. If an iterator has been created on a collection object and some other thread
tries to modify the collection object "structurally", a concurrent modification
exception will be thrown. It is possible for other threads though to invoke "set"
method since it doesn't modify the collection "structurally". However, if prior to
calling "set", the collection has been modified structurally,
"IllegalArgumentException" will be thrown.
Annonims class no construcgor
1. Set & List interface extend Collection, so Why doesn't Map interface extend
Collection?
Though the Map interface is part of collections framework, it does not extend
collection interface. This is by design, and the answer to this questions is best
described in Sun's FAQ Page: This was by design. We feel that mappings are not
collections and collections are not mappings. Thus, it makes little sense for Map to
extend the Collection interface (or vice versa). If a Map is a Collection, what are the
elements? The only reasonable answer is "Key-value pairs", but this provides a very
limited (and not particularly useful) Map abstraction. You can't ask what value a given
key maps to, nor can you delete the entry for a given key without knowing what value
it maps to. Collection could be made to extend Map, but this raises the question: what
are the keys? There's no really satisfactory answer, and forcing one leads to an
unnatural interface. Maps can be viewed as Collections (of keys, values, or pairs), and
this fact is reflected in the three "Collection view operations" on Maps (keySet,
entrySet, and values). While it is, in principle, possible to view a List as a Map
mapping indices to elements, this has the nasty property that deleting an element from
the List changes the Key associated with every element before the deleted element.
That's why we don't have a map view operation on Lists.

Why String is immutable or final in Java


1)Imagine StringPool facility without making string immutable , its not possible at all
because in case of string pool one string object/literal e.g. "Test" has referenced by many
reference variables , so if any one of them change the value others will be automatically gets
affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A
will also be "TEST" which is not desirable.
2)String has been widely used as parameter for many java classes e.g. for opening network
connection you can pass hostname and port number as stirng , you can pass database URL as
string for opening database connection, you can open any file by passing name of file as
argument to File I/O classes.
In case if String is not immutable , this would lead serious security threat , I mean some one
can access to any file for which he has authorization and then can change the file name either
deliberately or accidentally and gain access of those file.
3)Since String is immutable it can safely shared between many threads ,which is very
important for multithreaded programming and to avoid any synchronization issues in Java.
4) Another reason of Why String is immutable in Java is to allow String to cache its
hashcode , being immutable String in Java caches its hashcode and do not calculate every
time we call hashcode method of String, which makes it very fast as hashmap key to be used
in hashmap in Java. This one is also suggested by Jaroslav Sedlacek in comments below.
5) Another good reason of Why String is immutable in Java suggested by Dan Bergh
Johnsson on comments is: The absolutely most important reason that String is immutable is
that it is used by the class loading mechanism, and thus have profound and
fundamental security aspects.
Had String been mutable, a request to load "java.io.Writer" could have been changed to load
"mil.vogoon.DiskErasingWriter"

Das könnte Ihnen auch gefallen