You are on page 1of 54

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

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
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 references—soft, 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
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
* 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,

* 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 (don’t assign the same reference that we have passed as
* 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
* 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.

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

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

Boolean literals. * Static Inner class contains both static members and non-static members. the outer class makes the package more streamlined. * Anonymous Inner Class contains static declaration.Inner Class -----------------------------------------------------* Instance Inner class can not contain static property. Character literals. * Local Inner Class may be abstract and contains abstract methods. (total 5 literals) ------------------------------------------------. * Method Local Inner Class can not have static declaration and can not contain static property. String literals. Float literals. 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. * A Method can contain more than one Class but can not contain any Interface. * We can perform Inheritance Operation on Method Local Inner Class.e. 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. Ex : Char c=’A’ (‘A’ is literal) Integer literals. The inner class shares a special relationship with the outer class i. Nesting the inner class code where it is used (inside the outer class) makes the code more readable and maintainable. 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.e. * If we want to access local variable in Anonymous Inner Class or Method Local Inner Class then local variable must be declared as final. * Only static member of the Outer class can be accessed inside Static Inner Class. So the outer class members which are going to be used by the inner class can be made private and . 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.* Literals : A literal represents a value that is stored into a variable directly. * Anonymous Inner Class will be sub class to some other class or interface always.

} }. If inner classes are used each component gets its own event handler and each event handler implicitly knows the component it is working for. One way is to write a separate class B or to write an inner class B inside class A.the inner class members can be hidden from the classes in the same package. Inner classes are best used in the event handling mechanism and to implement the helper classes. class superClass{ void doSomething() { System. If a class A is written requires another class B for its own use.g. Inner classes get limited support of ide/tools as compared to the top level classes. Here anon is the reference which is of type superClass which is the class extended by the .println(“Doing something in the Anonymous class”). } } class hasAnonymous{ superClass anon = new superClass(){ void doSomething() { System.println(“Doing something in the Super class”). 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.out. For all the classes created by JVM and loaded in the memory. Button btn1 = new Button("Submit"). so working with the inner classes is sometimes annoying for the developer. e. Using inner class increases the total number of classes being used by the application. } } ). Btn. there are two ways to do this. Q8) What are different types of anonymous classes? Ans 1) Plain old anonymous class type one– e.out.g. 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.addActionListener(new ActionListener(){/br> Public void actionPerformed(ActionEvent ae){ submitClicked(). 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. This increases the level of encapsulation. 2. jvm has to perform some tasks like creating the object of type class. Advantage of writing the inner class B in the class A is you can avoid having a separate class.

} }). this anonymous class is the implementer of the interface Vehicle. } class serveMeal{ Eatable food = new Eatable(){ public void prepareSweets(){ //come implementation code goes here } }.anonymous class i.e. } } Anonymous class is defined as the argument of the method getTheBeautifilCar(). } class Car { void getType(Vehical v) { } } class BeautifulCars { void getTheBeautifilCar() { Car c = new Car ().g. 3) Argument defined anonymous class – e. class EnclosingOuter { class Inner{ } .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 . Q9) If you compile a file containing inner class how many . The anonymous implementer class of the interface Eatable implements its method prepareSweets() inside it. 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.println("It has four wheels"). interface Vehicle { void getNoOfWheels().out. The method doSomething() is the super class method overridden by the anonymous class.g. c.class file for each inner class an a . The method of class Car getTheBeautifilCar() expects the argument as an object of type Vehicle. superclass of the anonymous class. 2) Plain old anonymous class type two – interface Eatable{ public void prepareSweets().class file for the outer class is created.getType (new Vehicle () { public void getNoOfWheels () { System. } food is reference variable of type Eatable interface which refers to the anonymous class which is the implementer of the interface Eatable. e. So first we create an object of Car referenced by the variable ‘c’.

EnclosingOuter.out. } } Here the method getNoOfInnerClasses() is called on the outer class’s instance through this outer class instance the inner class instance in is created. outer class’s current instance from inside the inner class? Ans) The outer this reference i.println(“No Of Inner classes is : “+ in. 1) class OtherThanOuter{ EnclosingOuter out = new EnclosingOuter(). e. 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. public void getNoOfInnerClasses(){ Inner in = new Inner(). } class Inner{ public int getNoOfClassesFromOuter(){ return noInnerClass. the outer class’ current instance’ reference can be refered using ‘OuterClassName.g.Inner (). System.this’. class EnclosingOuter { class Inner{ } } To create the instance of inner class from class other than the enclosing Two files EnclosingOuter.e.e. class EnclosingOuter { private int noInnerClass = 1.class will be created. } Q12) How to refer to the outer this i.g . E.Inner in = Inner(). Though a separate inner class file is generated. the inner class file is not accessible in the usual way like.class EnclosingOuter$Inner.getNoOfClassesFromOuter()). % 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.Inner out = new EnclosingOuter.} If you compile the above code with command % javac EnclosingOuter. } 2) class OtherThanOuter{ EnclosingOuter.

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. Reason: The local variables are not guaranteed to live as long as the local inner class object. a method local inner class object can not access the method local variable. Q15) Can a method local inner class access the local final variables?Why? Ans) Yes. therefore the method local inner class object can not access the method local variable. Q14) Can the method local inner class object access method’s local variables? Ans) No. their scope is limited only code inside the method they are declared in. To access the method local variables.this). The method local variable live on stack and exist only till the method lives.class EnclosingOuter { class Inner{ System. Because the final variables are stored on heap and they live as long as the method local inner class object may live.out.out. //outer class instance } } To refer the inner class reference from within the inner class use this.println(“Inner class reference is “ + this). Q17) Can a local class declared inside a static method have access to the instance members of the outer class? . 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.println(“Outer class reference is “ + EnclosingOuter. Q16) Which modifiers can be applied to the method local inner class? Ans) Only abstract or final keyword isallowed. the variable has to be declared as final. // inner class instance System. So we can not be sure that the local variables will live till the method local inner class object lives.

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

" 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. Used for natural storing order.Ans) No. obj2). public boolean equals(Object). Constains only two method : Constains only one method : public int compare(Object obj1. . Comparable (Interface) available in java.e. An anonymous class can either extend a class or implement a single interface. You have a set of objects where you want to sort it in both ascending and decending order.g. Used for implementing customized sorting. Comparator could be used to sort a collection by custom sorting. Difference between Comparable and Comparator : Both are used for the same purpose(to Sort) but in different contexts. Object public int compareTo(Object obj)." This is compare myself with another object. SortedXXX kind of collections need its objects to satisfy the Comparable type. Implementing Comparator means "I can Implementing Comparable means "I can compare two other objects. . Comparator (Interface) available in java. you could compare people by age.util package. Comparable interface has to be implemented by a Class to make it comparable. If the anonymous class is extending a class then it becomes the implementer of all the interfaces implemented by its superclass automatically.lang package. name etc.

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

* The catch block throw the exception caught by itself This is called rethrowing of the exception by catch block. If they are not.  Exception can be Built-in or User Defined but Error is always Built-in. 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. * Difference between Error and Exception :  Exception is an error which can be handled at runtime but Error is an error which can not handled. * 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. try{ . * We can catch more than one Exception in a single catch block. except those of type ERROR or Runtime Exception.  * Throw : # We can throw an Exception explicitly.  Exception can be checked or unchecked but Errors are always unchecked. throws keyword but not with Error.  Exception are related to the application and Error is related to the environment in which the application is running.  * Throws :  # A throws cause lists the types of exceptions that a method meight throw.  # This is necessary for all exceptions.  For Handling Exception we can use try. a  compile-time error will result. * Unchecked Exception / Runtime Exception : The Exceptions that are checked by JVM at runtime. Checked Exception force the programmer to catch them explicitly in trycatch block.  # All other Exceptions that a method can throw must be declared in the throws clause. catch. using ‘throw’ statement.* Checked Exception / Compiletime Exception : The Exceptions that are checked at Compilition Time by the Java Compiler. though we can find out the class of the exception occurred.

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

Q3) Can static block throw exception? Ans) Yes. printing the name of each method as it works its way down the call stack from the top.Ans) If the exception is not caught by any of the method in the method’s stack till you get to the main() method. Return type can be anything. 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. 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. static block can throw only Runtime exception or can use a try-catch block to catch checked exception.RuntimeException is the superclass of those exceptions that can be thrown during the normal operation of the Java Virtual Machine. ------------------------------------------------------------------------------------------------- Polymorphism Polymorphism is a process of one form behaving differently in different class. 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 . 2. When we are overloading the methods we need to remember the following rules : 1. Method Overloading: Writing multiple methods inside the class with same name is called as Method Overloading. logged and application can exit. Typically scenario will be if JDBC connection is created in static block and it fails then exception can be caught. Run-time/Dynamic Polymorphism: We can achieve Run-time Polymorphism using Method Overriding and Dynamic Dispatch. It prints the most recently entered method first and continues down.exit() is not done. If System. This method prints the stack trace from where the exception occurred. the main method throws that exception and the JVM halts its execution. This check will be done by compiler at the compile time only. Method name must be same. . 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.

True . A obj1=new B(). 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.False Q. The Same method is refined to perform a sub class method overrides (replace) the different task.  Interms of order of Parameter. Overriding.  Interms of nos. 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. . super class method.  Sub class method return type must be same as Super class method return type. Method Overriding: Implementing Super class method in the sub class with same method signature is called as method overriding.True (Dynamic Dispatch) . Dynamic Dispatch : The process of assigning Sub class object to Super class reference variable is called as Dynamic Dispatch. method return type In method overriding. classes.True . of Parameter. Method Overloading a done in the same Method Overriding is done in Super and Sub class. 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. implementation (body) for the same feature. In method overloading. B obj1=new A(). object used to call the method. should also be same. Method Overloading is code refinement. B obj2=new B(). 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.  Sub class method parameter must be same as Super class method parameters. class A{ } class B extends A{} A obj1=new A().3. method return type can be same or different. What is method signature ? Ans : Method signature represents the method name along with method parameters. Method Overriding is code replacement. .  Sub class method access modifier must be same or higher than Super class access modifier. Parameter must be changed in any one of the following three ways:  Interms of types of Parameter.

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

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 run any finalizers of objects being freed. The Java programmer must keep in mind that it is the garbage collector that runs finalizers on objects. A second advantage of garbage collection is that it helps ensure program integrity. Garbage collection is an important part of Java's security strategy. Why garbage collection? JVM is responsible to cleaning the Memory. run transparently alongside the execution of the program. This activity will likely require more CPU time than would have been required if the program explicitly freed unnecessary memory. Garbage collection is the process of automatically freeing objects that are no longer referenced by the program. In the process of freeing unreferenced objects. in most cases. and finalize and free unreferenced objects on the fly.gc() can be invoked. Because it is not generally possible to predict exactly when unreferenced objects . Fortunately. The JVM's heap stores all objects created by an executing Java program. Giving this job to the JVM has several advantages : First. Plus. very good garbage collection algorithms have been developed. it can make programmers more productive. which will fire off a garbage collection at that time. Can we take private methods and final methods as same? Ans : Yes. 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. 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. Because Java's garbage collector runs in its own thread. In addition. and memory for new objects is allocated on the heap at run time.Q. Java programmers are unable to accidentally (or purposely) crash the JVM by incorrectly freeing memory. and adequate performance can be achieved for all but the most demanding of applications. 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. if a programmer really wants to explicitly request a garbage collection at some point. programmers in a garbagecollected environment have less control over the scheduling of CPU time devoted to freeing objects that are no longer needed.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. --------------------------------------------. System. it will. Objects are created by Java's "new" operator.gc() or Runtime.

And in the Native Thread model. it is not possible to predict when object finalizers will be run. If the program needs the resource before the garbage collector has gotten around to finalizing the unreferenced object. This means they take less memory and less processor time.gc(). finalize() : This method is responsible for releasing the resources. the program is out of luck. Sun wrote green threads to enable Java to work in environments that do not have native thread support. Green threads emulate multithreaded environments without relying on any native OS capabilities. ----------------------------------------------** **---------------------------------------------- MultiThreading * threads are light-weight because they utilize minimum resources of the system. * A thread represents a separate path of execution of a group of statements.  JVM is responsible to invoke runFinalization() to clean the resources before invoking etc.  When object hold the reference to resource like Database Connection. They run code in user space that manages and schedules threads. gc() : This method is responsible for cleaning the memory of all unused objects. Connection to printer etc. Connection to file. than that object will not allow GC to recleaned the memory and GC also can’t force that object. [ii] When memory shortage problem is detected then JVM has to do the following : * System.  Before invoking GC someone has to close all the resources properly. the resource will not be made available until after the garbage collector has run the object finalizer. runFinalization() : This method is responsible to invoking finalize() method on all unused object. we can’t force garbage collector. 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.runFinalization(). Note : As a developer we can call runFinalization() method and gc() method but not guarantee for cleanup i. * System. JVM Tasks : [i] JVM has to detect the unused objects time to time and has to prepare the unused object list.will be garbage collected.e. the threads are scheduled by the OS. therefore. Java programmers. Green Thread are scheduled by the JVM. Take help from another copy something is not OK  Sometime some object may refused GC for cleaning the memory.

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

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

by extending java. A thread in runnable state or a dead thread can not be restarted. Only a thread can be started only once in its lifetime. these two locks are different and these threads do not block each other. The static synchronized methods of the same class always block each other as only one lock per class exists.Thread extends Object implements Runnable 2. |o| Student stu=new Student(). As static methods are class methods and have only one copy of static data for the class. 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. Every class in java is represented by java. it may call any other synchronized method of that same object using the lock that it already holds. 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. But it should not be overridden as it’s implementation in thread class has the code to create a new executable thread and is specialised.lang. 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.Class instance. which is a runtime exception. 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. * We can implements thread in Java in two ways : 1. This is mainly possible by setting thread priorities inappropriately. If you try starting a thread which has been already started once an IllegalThreadStateException is thrown. 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. deadlock occurs . Q5) Can static methods be synchronized? Ans) Yes.lang. Q8) Once a thread has been started can it be started again? Ans) No. (only one method called void run()) If we implements Thread through Runnable Interface then call thread like this : Student stu=new Student().lang. When the threads are waiting for each other to release the lock on a particular object. then the class can extend other class or implement other interface.Runnable Interface.Ans) Yes. only one lock for the entire class is required. . Q6) Can two threads call two different static synchronized methods of the same class? Ans) No. The lock on this instance is used to synchronize the static methods. If a class is made to implement Runnable interface. Once a thread acquires a lock in some object. by implementing java. So no two static synchronized methods can execute at the same time.

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

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

<T> is called ‘generic parameter’ and it determines at the time of compilation. We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call.* Thread Priorities are used by the thread schedular to decide when each thread should be allowed to run. . which data type actually the programmer wants to use with the method it will executed in same thread. or <GT> and write the class as class Hello<T>{ class code. we can not specify a particular data type when designing the class. a lock can be acquired on a class. generic class acts on any data type. Since. by writing the generic parameter before the method return type as: <T> void display(){ . This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread. } Here. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. When a generic class or generic interface is written. Hence they can not work with primitive data types. the programmer need not rewrite the same class or interface whenever he wants to use or the interface with a new data type. Set the Thread Prioties * If we extends Thread class then we call run method like . -------------------------------------------------------------------------------------------------- Generic Type Generic Type – A Generic type represents a class or an interface that is type-safe. we use a generic parameter like <T>. a generic interface is also type-safe and hence it can use any data type. So this job is done by start method native implementation which has to be explicitly called. The same class or interface can work with any data type. Erasure – Creating a non-generic version of a generic type by the Java compiler is called Erasure. Similarly. It can act on any data type.start() method (native method) of Thread class actually does the job of running the Thread.start(). Generic types are designed to act upon objects. Generic classes and generic interface are also called ‘Parameterized types’ because they use a parameter that determines which data type they should work upon. This means a generic class can act upon any data type. This lock is acquired on the class's Class object Thread. If we directly call Thread. In the place of the data type. so does not solve the purpose of creating a new Student().run() method in a thread. Generic Method : we can make a method alone as generic method. Generic Class – A generic class represents a class that is type-safe.

public static final PrintStream out. When the JVM will be started then some default object will be created. In this condition no need to create the object of the System class. public String toString().lang Package Object Class : default Super Class for All Java Class. Runtime Class : (in java. System class will be used to access the information of the System. public static void setIn(InputStream).} Generic Interface : ------------------------------------------------------------------------------------------- java. protected void finalize() throws Throwable. public static void setErr(printStream). The information will be always some for one machine so the member of the System class is defined as static. public static void setOut(printStream). public static final PrintStream err. public final native void notifyAll(). The Constructor of the System class is private so we can not create the object for the System class. 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. } 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 class Object{ public final native class getClass(). public final native void wait(long) throws InterruptedException. implemented as Singleton class. Contains 11 Methods. public static final InputStream in. So.lang Package). int) throws InterruptedException. public native int hashCode(). public final native void notify(). public boolean equals(Object). . public final void wait(long. the Constructor of the System class is defined as private. Some Object reference will be stored in the reference variable defined in the System class to interact with the default input/output device. public final void wait() throws InterruptedException. protected native Object clone() throws CloneNotSupportedException .

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

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

ceil(). This concept can be used to receive data from an input device and send data to an output data. cos(). All streams are represented by classes in java. * Bytes Steams represents data in the form of individual bytes. round().public Field[] getDeclaredFields(). audio and video files. Byte streams are used to handle any type of data like Package. public Class[] getDeclaredClasses(). ---------------------------------------------------------------------------------------------------- Input-Output * Stream are mainly useful to move data from one place to another place. min(). floor().  To get the information about the Interface we can use the following methods : public Class[] getInterfaces(). max(). images. toDegrees(). abs(). * Important methods of Math class : sin(). pow(). public Constructor[] getDeclaredConstructors().lang Package. * Math class contains methods for performing basic numeric operations. random().  To get the information about the Modifier we can use the following methods : public int getModifier(). * Streams are Classified in two types – ‘Byte Streams’ and ‘Character/Text Streams’. sqrt(). * Input streams are streams which receive or read data while Output streams are streams which send or write data.  To get the information about the Inner class we can use the following methods : public Class[] getClasses(). Streams can be categorized as ‘input stream’ and ‘output stream’. * random() method returns a random number between 0 and 1 no one can guess this number. Math : * Math class is a final Class available in java. * all the methods of Math class are static. . tan(). log10().  To get the information about the Constructor we can use the following methods : public Constructor[] getConstructors(). toRadians(). log().

then writing that class objects into a file will lead to NoSerializableException. # Serializable interface should be implemented by the class whose objects are to be stored into the file. It always store and retrieve data in the form of characters (or text) only. extracting a data structure from a series of bytes. * Default buffer size used by any buffered class : 512 bytes. Used for transmit object across network. * Serialization : Java provides a mechanism. # If Serializable Interface is not implemented by the class. the standard convention in Java is to give the file a . 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.* Character/Text Streams represents data as characters of each 2 bytes. The opposite operation. meaning an object can be serialized on one platform and deserialized on an entirely different platform. # When serializing an object to a file. # Serializable is a Marker Interface. * 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.ser extension. # Most impressive is that the entire process is JVM independent.Collection Framework -------------------------------------- . # The process of serializing an object is also called deflating or marshalling an object. is deserialization (which is also called inflating or unmarshalling). 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.

IdentityHashMap. We can get Enumeration Object only for legacy classes (Vector. Method : public abstract void remove().util Package are the implemented classes of different interfaces : Set <T> List <T> Queue <T> Map <K. 4.V>.Dictionary) Method : pubic abstract boolean hasMoreElements(). Order of the elements may change in the LinkedHashSet. p a int previousIndex(). ListIterator Interface : extends from Iterator. public abstract boolean hasNext(). p a boolean hasPrevious(). public abstract Object next(). p a void set(Object o). Iterator differ from Enumerations .0) retrieve elements one by one. LinkedList<T>. p a Object previous(). not duplicate. duplicate.Hashtable.4 version of Collection Framework : LinkedHashMap. p a int nextIndex(). Introduced in JDK 1. Collection framework is implemented in java.2): Retrieve elements in forward direction. Retrieve elements in forward & backward direction both. * All the Collection classes in java. LinkedHashMap * There are 4 ways to retrieve elements from a collection object : 1. for-each loop : 2. Set. Method name improved in Iterator names are easy to follow. List preserves the order of .* Collection Framework : A Collection Framework is a class library to handle groups of objects. Enumeration Interface : (Legacy Interface. 3.V>. not ordered A List represents ordered collection of elements. p a boolean hasNext(). ordered A set represents a collection of elements.Properties. public abstract void add(Object o).not null. Iterator Interface (add JDK 1. p a void remove().V>. takes the place of Enumeration. used to specify input streams to a SequenceInputStream. LinkedHashSet<T>.util Package. Note : Iterator is applicable for every Collection implemented class object but ListIterator is applicable only for List implemented class objects. pubic abstract Object nextElements(). p a Object next().Remove element.null. Vector<T> LinkedList<T> HashMap<K. enhancement in JDK 1. List. HashTable<K. Stack<T>. TreeMap<K. TreeSet<T> ArrayList<T>.Stack.V> HashSet<T>.

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

* Vector use equals() method. (thread safe) * like Array. * Vector default capacity is 10.out. * Vector implementation based on ‘Resizable Array’ Data Structure. Difference between ArrayList & Vector : ArrayList is not Synchronized. ArrayList increases by half of its size when its size is increased.util. No default size. Slower and Verctor is Legacy Class.0). * providing fast random access and fast traversal. (thread safe) data is retrieved using the elementAt() method. RandomAccess. i<list. ArrayList is Faster than Vector. Serializable * Vector size can grow or shrink as needed to accommodate adding and removing items after the Vector has been created.LinkedList making the function more flexible Vector : public class Vector<E> extends AbstractList<E> implements List<E>.Cloneable.* ArrayList is not Synchronized this means that when more than one thread acts simultanuously on the ArrayList object.get(i)).Vector came along with the first version of java development kit (JDK 1. Vector component is accessed using integer index no. * Vector is Synchronized. When the parameter is declared as List to the function it can be called by passing any subclass of List like ArrayList.Vector.ArrayList was introduced in java version1.util. as part of java collections framework. java.sort(list). The most important one – If a function is declared such that it takes list. for(int i=0. (not thread safe) Data is retrieved using the get() method. Vector doubles the size of its array when its size is increased. Default size is 10. instead of ArrayList<String> = new ArrayList<String>(). . java. 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. i++){ System. the result may be incorrect in some cases.println(list. E. * Vector contains duplicate values.g void showDetails(List list). Vector is Synchronized. } Why is it preferred to declare: List<String> list = new ArrayList<String>().size().2. Sort ArrayList : Collections.

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

With a single thread. HashMap does not guarantee that the Order is constant.V>. Synchronized HashMap : Collections. Note : We can HashMap()). * multiple threads can access HashMap object. Cloneable. Hashtable become slower. Hashtable is advisable.V>. there will not be any incorrect results produced by the Enumeration. HashMap (Java Class) – JDK 1. Serializable * stores the elements in the form of key-value pairs. Cloneable. * use equals() and compareTo() method. * 0. order of the map will remain constant over time. * Duplicates keys are not allowed but values can be duplicate. * Insertion order is not preserved because insertion is based on some sorting order. 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. This means even if exception if concurrent updates are concurrent updations are done to made to the HashMap.V> extends Dictionary<K. Enumeration for the Hasthtable is not This means Iterator will produce fail-fast.synchronizedMap(new TreeMap : public class TreeMap<K.75 is the default load factor of Hashtable.75 is the default load factor of HashMap.0 not Synchronized (not thread-safe) Synchronized (thread-safe) In the case of single thread. * the underlaying data structure is RED-BLACK Tree. * 0.V> implements NavigableMap<K. So we may get unreliable results. HashMap has more complex hashing algorithm than Hashtable. using is faster than Hashtable. Iterator in the HashMap is fail-fast. Performance is high.V> extends AbstractMap<K.V> extends AbstractMap<K. Performance is slow.V> implements Map<K. * key should be unique we can’t use duplicate data for keys. Serializable * Hashtable is Synchronized.HashMap : public class HashMap<K.2 Hashtable (Legacy Class) – JDK 1. values. . * Hash map is not Synchronized.V> implements Map<K. Hashtable. Cloneable.V>. Allows to store null keys and null Does not allow. Hashtable : public class Hashtable<K. HashMap In case of Multiple threads.

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

we can store a primitive data type. String variant). or cultural region. See individual field documentation and subclass documentation for details. Class Locale public final class Locale extends Object implements Cloneable. Integer.lang Package provides all Wrapper Classes for each of the primitive data. When we create an object to a wrapper class.month of the calendar system has value MONTH == JANUARY for all calendars. The tokenization method is much simpler than the one used by the StreamTokenizerclass. region. Double. Other values are defined by the concrete subclass. nor do they recognize and skip comments. . Byte. political. StringTokenizer public class StringTokenizer extends Object implements Enumeration<Object> The StringTokenizer class allows an application to break a string into tokens. Long.Character. with millisecond precision. * All Wrapper class are Final & immutable so their state can not be changed. displaying a number is a locale-sensitive operation--the number should be formatted according to the customs/conventions of the user's native country. String country. The StringTokenizer methods do not distinguish among identifiers. Serializable A Locale object represents a specific geographical. Short. Boolean. The set of delimiters (the characters that separate tokens) may be specified either at creation time or on a per-token basis. * There are 8 Wrapper Class corresponding to primitive to data types . String country). Comparable<Date> The class Date represents a specific instant in time. such as ERA. and quoted strings. Locale(String language. it contains a field and in this field. Cloneable. 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. * java. Float. public class Date extends Object implements Serializable. Create a Locale object using the constructors in this class: Locale(String language). ------------------------------------------------------------------------------------------------- Wrapper Class * A Wrapper class is a class whose object wraps or contains a primitive data type. Locale(String language. or culture. numbers.

thread-safe.5 Feature) -------------------------------------------------------------------- StringBuffer. And Provides reliable result. mutable. Add new in JDK 1. Mutable. So the methods of Number class are commonly available in all these Subclasses.  StringBuilder class objects are Mutable. not Synchronized. next time : 70*2+2=142 StringBuilder : (Final.5. StringBuilder. synchronized. Integer. 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. Unboxing : Converting object into primitive dataytpe Autoboxing : Converting primitive into object form automatically. so they can be modified. Long.* Number is an abstract Super class whose subclasses are – Byte.  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 : . * Character class has only one Construtor.  StringBuilder is not Synchronized. (Synchronization means locking the object). Done in generic types. Character(char ch) * Byte. Long. it allows several threads to act on it simultaneously.  StringBuffer class objects are Mutable.util package handle only objects and hence wrapper class help in this case also. reliable result. Double. take more time than StringBuilder)  StringBuffer is a Final Class. Byte(byte b) (String str) * Float class has three Constructors.  Implementing the Synchronization mechanisam will take some time for the JVM. Short. Boxing : Converting primitive datatype into object. Float.  Synchronized by default.5)  Added in JDK 1. (JDK 1.  StringBuffers are safe for use by multiple threads. Boolean classes have two Constructors. Integer. String StringBuffer : (final. next time : 34*2+2=70. Same as StringBuffer. Double. Hence StringBuffer will take more execution time than StringBuilder. next time : 16*2+2= 34.  Memory Allocation : Default Capacity : 16.  The Classes in java. Short.

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

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

byte[] dst. args) Returns a formatted string using the specified format string and arguments. int codePointCount(int beginIndex. boolean equals(Object anObject)Compares this string to the specified object. int dstBegin) . static String copyValueOf(char[] data) Returns a String that represents the character sequence in the array specified. Returns true if this string contains the specified boolean contentEquals(CharSequence cs)Compares this string to the specified CharSequence. format string. byte[] getBytes(Charset charset) Encodes this String into a sequence of bytes using the given charset. byte[] getBytes() Encodes this String into a sequence of bytes using the platform's default charset. storing the result into a new byte array. Concatenates the specified string to the end of this boolean contains(CharSequence s) sequence of char values. int compareToIgnoreCase(String str)Compares two strings lexicographically. static String copyValueOf(char[] data.. String concat(String str) string. boolean contentEquals(StringBuffer sb)Compares this string to the specified StringBuffer. int offset. boolean equalsIgnoreCase(String anotherString) Compares this String to another String. int count) Returns a String that represents the character sequence in the array specified. storing the result into a new byte array. String format. ignoring case differences. static String format(String format. int codePointAt(int index)Returns the character (Unicode code point) at the specified index. Object.. static String format(Locale l. int codePointBefore(int index)Returns the character (Unicode code point) before the specified index. boolean endsWith(String suffix)Tests if this string ends with the specified suffix.. args) Returns a formatted string using the specified locale. int compareTo(String anotherString)Compares two strings lexicographically. ignoring case considerations.. int endIndex) Returns the number of Unicode code points in the specified text range of this String. void getBytes(int srcBegin. and arguments. Object.

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

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

int offset. . String trim()Returns a copy of the string. static String valueOf(char[] data)Returns the string representation of the char array argument. static String valueOf(long l)Returns the string representation of the long argument. two or three operands. static String valueOf(double d)Returns the string representation of the double argument. * Negative numbers are represented in binary using 2’s complement notation. static String valueOf(float f)Returns the string representation of the float argument.Converts all of the characters in this String to upper case using the rules of the default locale. static String valueOf(char c)Returns the string representation of the char argument. String toUpperCase(Locale locale)Converts all of the characters in this String to upper case using the rules of the given Locale. with leading and trailing whitespace omitted. int count) Returns the string representation of a specific subarray of the char array argument. static String valueOf(boolean b)Returns the string representation of the boolean argument. --------------------------------------------------------------------------------------------------------------------------------------------Operator : An operator is a symbol that perform an operation on one.(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 1’s complement notation. static String valueOf(Object obj)Returns the string representation of the Object argument. static String valueOf(char[] data. static String valueOf(int i)Returns the string representation of the int argument. Arithmetic Operator Unary Operator Assignment Operator Relational Operator Logical Operator Boolean Operator Bitwise Operator + - * .

20. Enhanced for loop 4. * If any abstract method is not implemented.20. annotations 8.40. If dots will be less or more than 3 then gives syntax error for(int i:no){ System. it is not possible to estimate the total memory required to create the object.5) Syntax com.Student.5 New Features # Static Import : (New Added feature of JDK 1. * variable argument allowed must be the last enums 7.50).jlcindia. OK obj. New API’s # var args (Variable Argument) : allows to pass variable no. * access only static properties of give class.30.*. * Abstract class contains incomplete methods. autoboxing 5. of parameters. then that sub class should be declared as ‘abstract’. .‘>>’ will protect the sign bit whereas the >>> operator will not protect the signn bit. Static Imports 2. * we can can’t access any other methods or variables except static.out.5 New Features : 1. * The reference of abstract class can be used to refer to objects of its subclasses. OK * Only one variable argument is allowed for one method.30). } } void show(int …no){ Note : only put … (3 dots). ------------------------------------------------------------------------------------ JDK 1.println(i). import static List of JDK 1. So. generics 6. JVM can not create objects to an abstract class. Abstract Class : * Abstract class contains All Properties like a normal class and 0 or more abstract method. It always fills 0 in the sing bit. * We can not create object of abstract class but we can create a reference of abstract type. var args (Variable Arguments) 3.

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

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

processing or calculations. A Constructor is called and executed A method is executed only when we call automatically. parameterized called. A Constructor is called only once per called several times on the object. it. Serializable A Locale object represents a specific geographical. or cultural region. When data is not passed at the time of When data is passed at the time of creating an object. If we want to invoke the Superclass parameterized constructor then we need to invoke explicitly. public. object. have 1 or more parameters. can not return any value and not even return any value according to the void. 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) . protected and private modifier. Differences between Default Constructor and Parameterized Constructor : ---------------------------------------------------------------------------------Default Constructor Parameterized Constructor does not have any parameters. initialize each object with different data. A Constructor’s name and class name A method’s name and class name can be should be same. political. called after creating the object. public final class Locale extends Object implements Cloneable. called at the time or creating the object.  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. constructors. constructor is called. Default Constructor is useful to initialize Parameterized Constructor is useful to all objects with same data. same or different. More than one parameterized only one default Constructor in a class. A Constructor can be declared only A method can be declared any modifier. requirement and even void. default constructor is creating an object. 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.

2 Not order equals() Resizabl 1.2 Insertion/ Priority/ equals() dequeue compareTo() order Set<E> not Not Unique Contains Synchronized elements null 1.2 Sorted compareTo() Balance Map Map<K.2 No Order equals() hashCode() Hashtab Linked ed Set Set<E> Not Unique Synchronized elements 1.V> Linke equals() hashCode() 1.Locale(String language. String country) Locale(String language.2 Stored in equals() key order compareTo() Balance .4 Insertion order equals() hashCode() Hash tab doublylis Set Set<E> Not Unique Synchronized elements 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.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. 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. String country.V> Unique Keys Map<K.V> Not Synchronized Unique Keys 1.4 Key insertion order/ Access order of entries equals() hashCode() Hash tab doublylis 1.

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

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