Академический Документы
Профессиональный Документы
Культура Документы
For
example creating a class Vehicle and injecting properties into it. E.g
public class Vehicle {
public String colour;
public String model;
}
Encapsulation - The encapsulation is achieved by combining the methods and attribute into
a class. The class acts like a container encapsulating the properties. The users are exposed
mainly public methods.The idea behind is to hide how thinigs work and just exposing the
requests a user can do.
Association - Association is a relationship between two classes. In this relationship the
object of one instance perform an action on behalf of the other class. The typical behaviour
can be invoking the method of other class and using the member of the other class.
public class MyMainClass{
public void init(){
new OtherClass.init();
}
}
Aggregation - Aggregation has a relationship between two classes. In this relationship the
object of one class is a member of the other class. Aggregation always insists for a direction.
public class MyMainClass{
OtherClass otherClassObj = new OtherClass();
}
Composition - Composition is a special type of aggregation relationship with a difference
that its the compulsion for the OtherClassobject (in previous example) to exist for the
existence of MyMainClass.
15) How to find the size of an object?
Ans)The heap size of an object can be found using Runtime.totalMemory()-Runtime.freeMemory() .
Q9) How to change the heap size of a JVM?
Ans) The old generation's default heap size can be overridden by using the -Xms and -Xmx
switches to specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program
Q10) What is difference between instanceof and isInstance(Object obj)?
adheres to the Java specifications ( IEEE-754 floating-point specification ) and returns the
consistent value independent of the platform. That is, if you want the answers from your
code (which uses floating point values) to be consistent in all platforms, then you need to
specify the strictfp modifier
Q4) What is volatile keyword?
Ans) In general each thread has its own copy of variable, such that one thread is not
concerned with the value of same variable in the other thread. But sometime this may not be
the case. Consider a scenario in which the count variable is holding the number of times a
method is called for a given class irrespective of any thread calling, in this case irrespective
of thread access the count has to be increased. In this case the count variable is declared as
volatile. The copy of volatile variable is stored in the main memory, so every time a thread
access the variable even for reading purpose the local copy is updated each time from the
main memory. The volatile variable also have performance issues.
* Cloning the Class objects :
The process of creating the exact copy of an existing object is called cloning. In
cloning, already an object should exist and when we clone the objects, a bit wise copy
of the object will result. The original object and the cloned object will be exactly the
same bit to bit. If the original object has some data in it, it also automatically comes
into cloned object.
There are two types of cloning :
1. Shallow Cloning
2. Deep Cloning
When the cloned object is modified, same modification will also affect the original
object. This is called shallow cloning In shallow copy the object is copied without its
contained objects. Shallow clone only copies the top level structure of the object not the
lower levels. It is an exact bit copy of all the attributes.
Object class has a method clone() which does shallow cloning.
When the cloned object is modified, if the original object is not modified, then it is
called deep cloning.
In deep copy the object is copied along with the objects it refers to. Deep clone copies all
the levels of the object from top to the bottom recursively.
Disadvantages of using Serialization to achieve deep cloning
Serialization is more expensive than using object.clone().
Not all objects are serializable.
Serialization is not simple to implement for deep cloned object..
* Static and Transient Variable can not be serialized. (transient only used with
variables)
* A native method is a method that is implemented in a language other than Java. (only
used with only methods)
* A native method and abstract method have no body.
are not a keyword.
* Sub Class object contains copy of super class object so members of super class
available in Sub Class.
* A top level class can not be declared as private, protected, static, native, synchronized,
volatile, transient.
* Externalizable is an Interface that extends Serializable Interface. And sends data into
Streams in
Compressed Format. It has two methods, writeExternal(ObjectOuput
out) and readExternal(ObjectInput in)
public interface Externalizable
extends Serializable
Only the identity of the class of an Externalizable instance is written in the serialization
stream and it is the responsibility of the class to save and restore the contents of its
instances. The writeExternal and readExternal methods of the Externalizable interface
are implemented by a class to give the class complete control over the format and
contents of the stream for an object and its supertypes. These methods must explicitly
coordinate with the supertype to save its state. These methods supercede customized
implementations of writeObject and readObject methods.
Object Serialization uses the Serializable and Externalizable interfaces. Object
persistence mechanisms can use them as well. Each object to be stored is tested for the
Externalizable interface. If the object supports Externalizable, the writeExternal
method is called. If the object does not support Externalizable and does implement
Serializable, the object is saved using ObjectOutputStream.
When an Externalizable object is reconstructed, an instance is created using the public
no-arg constructor, then the readExternal method called. Serializable objects are
restored by reading them from an ObjectInputStream.
An Externalizable instance can designate a substitution object via the writeReplace and
readResolve methods documented in the Serializable interface.
* In JDK 1.4
only added).
- 51 Keywords
* In JDK 1.5
52 Keywords (enum is
Class is a user defined data types. It is a group of Java methods and variables. It is the
place where the properties and functionality of the specific type of object will be
defined. We can say that class as the structure of an object. If we defining one class, we
can define any number of objects depends on our requirement.
A Class contains variables, methods, constructors, blocks, class, interface, enum.
Object is the instance of the class. It is a run time entity. It has the separate memory
location, where the data of the specific type (user defined type) will be stored. We can
create any number of objects of the specific type.
* Keyword super refer super class members from a sub class .
* super is used to access super class variables, methods, constructors.
* Use super() always refers to the superclass immediately above the calling class.
* super() will the first statement of any constructor.
* Keyword this refer the current class object.
* this(...) - Calls another constructor in same class.
JVM (Java Virtual Machine) :
# A Java virtual machine (JVM) is a virtual machine capable of executing Java
bytecode.
# JVM's are not platform independent. JVM's are platform specific run time
implementation provided by the vendor.
As we all aware when we compile a Java file, output is not an 'exe' but it's a '.class' file.
'.class' file consists of Java byte codes which are understandable by JVM. Java Virtual
Machine interprets the byte code into the machine code depending upon the underlying
operating system and hardware combination. It is responsible for all the things like
garbage collection, array bounds checking, etc.
The JVM is called "virtual" because it provides a machine interface that does not
depend on the underlying operating system and machine hardware architecture. This
independence from hardware and operating system is a cornerstone of the write-once
run-anywhere value of Java programs.
There are different JVM implementations are there. These may differ in things like
performance, reliability, speed, etc. These implementations will differ in those areas
where Java specification doesnt mention how to implement the features, like how the
garbage collection process works is JVM dependent, Java spec doesnt define any
specific way to do this
JDK (Java Development Kit)
# JDK is Java Development Kit which is for development purpose and it includes
execution environment also.
Java Developer Kit contains tools needed to develop the Java programs, and JRE to
run the programs. The tools include compiler (javac.exe), Java application launcher
(java.exe), Appletviewer, etc
Compiler converts java code into byte code. Java application launcher opens a JRE,
loads the class, and invokes its main method.
You need JDK, if at all you want to write your own programs, and to compile the m.
For running java programs, JRE is sufficient.
JRE is targeted for execution of Java files
i.e. JRE = JVM + Java Packages Classes(like util, math, lang, awt,swing etc)+runtime
libraries.
JDK is mainly targeted for java development. I.e. You can create a Java file (with the
help of Java packages), compile a Java file and run a java file
* Literals : A literal represents a value that is stored into a variable directly. Ex : Char
c=A (A is literal)
Integer literals, Float literals, Character literals, String literals, Boolean literals. (total 5
literals)
------------------------------------------------- Inner Class
-----------------------------------------------------* Instance Inner class can not contain static property. Instance Inner class can access
Outer class any
type of property.
* All the Members of Instance Inner Class can not be access inside the outer class
directly but allowed
through the Inner class object.
* Static Inner class contains both static members and non-static members.
* Only static member of the Outer class can be accessed inside Static Inner Class.
* Method Local Inner Class can not have static declaration and can not contain static
property.
* A Method can contain more than one Class but can not contain any Interface.
* We can perform Inheritance Operation on Method Local Inner Class.
* Local Inner Class may be abstract and contains abstract methods.
* Anonymous Inner Class will be sub class to some other class or interface always.
* Anonymous Inner Class contains static declaration.
* If we want to access local variable in Anonymous Inner Class or Method Local Inner
Class then local
variable must be declared as final.
Q5) Does a static nested class have access to the enclosing class' non-static methods or
instance variables?
Ans) No .
Q6)What are the advantages of Inner classes?
Ans) The embedding of inner class into the outer class in the case when the inner class is to be
used only by one class i.e. the outer class makes the package more streamlined. Nesting the
inner class code where it is used (inside the outer class) makes the code more readable and
maintainable.
The inner class shares a special relationship with the outer class i.e. the inner class has access
to all members of the outer class and still have its own type is the main advantages of Inner
class. Advantage of inner class is that they can be hidden from the other classes in the same
package and still have the access to all the members (private also) of the enclosing class. So
the outer class members which are going to be used by the inner class can be made private and
the inner class members can be hidden from the classes in the same package. This increases
the level of encapsulation.
If a class A is written requires another class B for its own use, there are two ways to do this.
One way is to write a separate class B or to write an inner class B inside class A. Advantage of
writing the inner class B in the class A is you can avoid having a separate class. Inner classes
are best used in the event handling mechanism and to implement the helper classes. The
advantage of using inner class for event handling mechanism is that the use of if/else to select
the component to be handled can be avoided. If inner classes are used each component gets its
own event handler and each event handler implicitly knows the component it is working for.
e.g.
Button btn1 = new Button("Submit");
Btn.addActionListener(new ActionListener(){/br>
Public void actionPerformed(ActionEvent ae){ submitClicked(); }
} );
The advantage of using static nested class is that to instantiate a static nested class you need
not create an instance of the enclosing class which reduces the number of objects the
application creates at runtime.
Q7)What are disadvantages of using inner classes?
Ans) 1. Using inner class increases the total number of classes being used by the application.
For all the classes created by JVM and loaded in the memory, jvm has to perform some tasks
like creating the object of type class. Jvm may have to perform some routine tasks for these
extra classes created which may result slower performance if the application is using more
number of inner classes. 2. Inner classes get limited support of ide/tools as compared to the
top level classes, so working with the inner classes is sometimes annoying for the developer.
Q8) What are different types of anonymous classes?
Ans 1) Plain old anonymous class type one
e.g.
class superClass{
void doSomething() {
System.out.println(Doing something in the Super class);
}
}
class hasAnonymous{
superClass anon = new superClass(){
void doSomething() {
System.out.println(Doing something in the Anonymous class);
}
};
Here anon is the reference which is of type superClass which is the class extended by the
anonymous class i.e. superclass of the anonymous class. The method doSomething() is the
super class method overridden by the anonymous class.
2) Plain old anonymous class type two
interface Eatable{
public void prepareSweets();
}
class serveMeal{
Eatable food = new Eatable(){
public void prepareSweets(){ //come implementation code goes here }
};
}
food is reference variable of type Eatable interface which refers to the anonymous class
which is the implementer of the interface Eatable. The anonymous implementer class of the
interface Eatable implements its method prepareSweets() inside it.
3) Argument defined anonymous class e.g.
interface Vehicle {
void getNoOfWheels();
}
class Car {
void getType(Vehical v) { }
}
class BeautifulCars {
void getTheBeautifilCar() {
Car c = new Car ();
c.getType (new Vehicle () {
public void getNoOfWheels () {
System.out.println("It has four wheels");
}
});
}
}
Anonymous class is defined as the argument of the method getTheBeautifilCar(), this
anonymous class is the implementer of the interface Vehicle. The method of class Car
getTheBeautifilCar() expects the argument as an object of type Vehicle. So first we create an
object of Car referenced by the variable c. On this object of Car we call the method
getTheBeautifilCar() and in the argument we create an anonymous class in place which is the
implementer of interface Vehicle hence of type Vehicle.
Q9) If you compile a file containing inner class how many .class files are created and
what are all of them accessible in usual way?
Ans) If a inner class enclosed with an outer class is compiled then one .class file for each inner
class an a .class file for the outer class is created. e.g.
class EnclosingOuter {
class Inner{ }
}
If you compile the above code with command
% javac EnclosingOuter.java
Two files
EnclosingOuter.class
EnclosingOuter$Inner.class
will be created. Though a separate inner class file is generated, the inner class file is not
accessible in the usual way like,
% java EnclosingOuter$Inner
Q10) How to access the inner class from code within the outer class?
Ans) The inner class is instantiated only through the outer class instance.
class EnclosingOuter {
private int noInnerClass = 1;
public void getNoOfInnerClasses(){
Inner in = new Inner();
System.out.println(No Of Inner classes is : + in.getNoOfClassesFromOuter());
}
class Inner{
public int getNoOfClassesFromOuter(){ return noInnerClass; }
}
Here the method getNoOfInnerClasses() is called on the outer classs instance through this
outer class instance the inner class instance in is created.
Q11) How to create an inner class instance from outside the outer class instance code?
Ans) To create an instance of the inner class you must have the instance of its enclosing
class.
e.g. class EnclosingOuter {
class Inner{ }
}
To create the instance of inner class from class other than the enclosing class.
1) class OtherThanOuter{
EnclosingOuter out = new EnclosingOuter();
EnclosingOuter.Inner in = out.new Inner();
}
2) class OtherThanOuter{
EnclosingOuter.Inner out = new EnclosingOuter.Inner (); }
Q12) How to refer to the outer this i.e. outer classs current instance from inside the
inner class?
Ans) The outer this reference i.e. the outer class current instance reference can be refered
using OuterClassName.this. E.g
class EnclosingOuter {
class Inner{
System.out.println(Inner class reference is + this); // inner class instance
System.out.println(Outer class reference is + EnclosingOuter.this); //outer class instance
}
}
To refer the inner class reference from within the inner class use this.
Q13) Which modifiers can be applied to the inner class?
Ans) Following are modifiers that can be applied to the inner:
public
private
abstract
final
protected
strictfp
static turns the inner class into static nested class.
Q14) Can the method local inner class object access methods local variables?
Ans) No, a method local inner class object can not access the method local variable.
Reason: The local variables are not guaranteed to live as long as the local inner class object.
The method local variable live on stack and exist only till the method lives, their scope is
limited only code inside the method they are declared in. But the local inner class object
created within the method lives on heap and it may exist even after the method ends if in case
the reference of this local inner class is passed into some other code and is stored in an
instance variable. So we can not be sure that the local variables will live till the method local
inner class object lives, therefore the method local inner class object can not access the
method local variable. To access the method local variables, the variable has to be declared as
final.
Q15) Can a method local inner class access the local final variables?Why?
Ans) Yes. Because the final variables are stored on heap and they live as long as the method
local inner class object may live.
Q16) Which modifiers can be applied to the method local inner class?
Ans) Only abstract or final keyword isallowed.
Q17) Can a local class declared inside a static method have access to the instance
members of the outer class?
Ans) No. There is no this reference available in the static method .The static method class can
not have access to any members of the outer class other than static members.
Q18) Can a method which is not in the definition of the superclass of an anonymous class
be invoked on that anonymous class reference?
Ans) No. Compilation will fail.As the reference variable type of the anonymous class will be
of superclass which will not know of any method defined inside the anonymous class the
compilation will fail.
e.g. class SuperClass{
void doSomething() {
System.out.println("In the Super class");
}
}
class hasAnonymous{
SuperClass anon = new SuperClass(){
void doSomething() {
System.out.println("In the Anonymous class");
}
void doStuff() {
System.out.println("An Anonymous class method not present in superClass");
}
};
public void doIt(){
anon.doSomething(); // legal superClass has this method
anon.doStuff(); // Not legal }
}
The above code does not compile as the superClass does not know about the anonymous class
method doStuff().
Q19) Can an anonymous class define method of its own?
Ans) Yes. But there will be no way by which the methods defined in the anonymous class
which are not present in its superclass be invoked. As only those methods which are defined in
the suprclass which the anonymous class extends be invoked defining the methods in the
anonymous class will be of no use.
Q20) Can an anonymous class implement multiple interfaces directly?
Ans) No. An anonymous class can implement only one interface. If the anonymous class is
extending a class then it becomes the implementer of all the interfaces implemented by its
superclass automatically.
Q21) Can an anonymous class implement an interface and also extend a class at the same
time?
Ans) No. An anonymous class can either extend a class or implement a single interface. If the
anonymous class is extending a class then it becomes the implementer of all the interfaces
implemented by its superclass automatically.
Difference between Comparable and Comparator :
Both are used for the same purpose(to Sort) but in different contexts. Comparable
interface has to be implemented by a Class to make it comparable. SortedXXX kind of
collections need its objects to satisfy the Comparable type. Comparator could be used
to sort a collection by custom sorting. You have a set of objects where you want to sort
it in both ascending and decending order.
Comparable (Interface)
available in java.lang package.
Used for natural storing order.
Comparator (Interface)
available in java.util package.
Used for implementing customized sorting.
Constains only two method :
Constains only one method :
public int compare(Object obj1, Object
public int compareTo(Object obj);
obj2);
public boolean equals(Object);
Implementing Comparator means "I can
Implementing Comparable means "I can
compare two other objects." This is
compare myself with another object." This typically useful when there are multiple
is typically useful when there's a single
ways of comparing two instances of a type
natural default comparison.
- e.g. you could compare people by age,
name etc.
---------------------------------------------------------------------------------------------------------
Interface
@ The class which implements the interface needs to provide implementation of all methods
declared in the interface. But it is not necessary that call all the interface variables in the
class.
@ All methods by default public and abstract. And all variables by deafult public, static and
final.
@ We can not use private, protected, static, final access modifier with the interface name,
we can only use public and abstract access modifier. If not mention then it will be default.
@ We can not specify the Instance variable, Instance method, Static Method, Constructor,
Instance Block, Static Block, Concrete Method in Interface.
@ An interface reference can point to objects of its implementing classes.
@ An interface can extends from one or many interfaces. A class can extend only one class
but implements any number of interfaces. An Interface can not implements or extends any
Class.
@ When a class is implementing two or more interfaces which contain same variable then
matching variable should not reffer directly. Always matching variable must access with the
interface name using dot/period (.) operator.
@ When a class is implementing two or more interfaces which contain same method
signature, we must override the method only once in sub class.
@ An interface can be declared in side the another interface and a top-level class only.
@ An interface can not be declared in side the method and inner-class.
@ when interface declared inside a class or Interface only public, protected, private, static &
abstract are permitted. Final not allowed.
@ Nested Interface can be implemented by any class (package level, nested or inner) as
long as the access modifiers permit visibility.
@ as with regular package level interfaces variables defined inside are considered to be
constants (static, public) regardless of whether the modifiers are specified like the package
level interfaces they can declare nested classes and interfaces
------------------------------------------> Exception Handling
<---------------------------------------------
* Throws :
# A throws cause lists the types of exceptions that a method meight throw.
# This is necessary for all exceptions, except those of type ERROR or Runtime
Exception.
# All other Exceptions that a method can throw must be declared in the throws
clause. If they are not, a
* Throw :
# We can throw an Exception explicitly, using throw statement.
* We can catch more than one Exception in a single catch block.
* It is not considered as a good practice to write a single catch to catch all the
exceptions because If we use the
Superclass Exception in the catch block then we will not get the valuable information
about each of the
exception thrown during the execution, though we can find out the class of the
exception occurred. Also it will
reduce the readability of the code as the programmer will not understand what is the
exact reason for putting
the try-catch block.
* The catch block throw the exception caught by itself This is called rethrowing of the
exception by catch block.
try{
}
Catch(Exception E){
throw FileNotFound(); // called rethrowing
}
* Once the control switches to the catch block does not it return back to the try block to
execute the balance code.
* There should not be any line of code present between the try and the catch/finally
block.
* All the exceptions inherit a method printStackTrace() from the Throwable class. This
method prints the stack trace from where the exception occurred. It prints the most
recently entered method first and continues down, printing the name of each method
as it works its way down the call stack from the top.
* Exception object will be garbage collected after Exception Handling.
* The subclass exception should precede the base class exception when used within the
catch clause.
*
*
*
Q8) What is difference between ClassNotFoundException and
NoClassDefFoundError?
Ans) A ClassNotFoundException is thrown when the reported class is not found by the
ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be
loaded from another class which was loaded in a parent classloader and hence the class from
the child classloader is not visible.
Consider if NoClassDefFoundError occurs which is something like
java.lang.NoClassDefFoundError
src/com/TestClass
does not mean that the TestClass class is not in the CLASSPATH. It means that the class
TestClass was found by the ClassLoader however when trying to load the class, it ran into an
error reading the class definition. This typically happens when the class in question has static
blocks or members which use a Class that's not found by the ClassLoader. So to find the
culprit, view the source of the class in question (TestClass in this case) and look for code
using static blocks or static members.
Q20) What happens if the exception is never caught and throws down the method stack?
Ans) If the exception is not caught by any of the method in the methods stack till you get to the
main() method, the main method throws that exception and the JVM halts its execution.
Q21) How do you get the descriptive information about the Exception occurred during the
program execution?
Ans) All the exceptions inherit a method printStackTrace() from the Throwable class. This
method prints the stack trace from where the exception occurred. It prints the most recently
entered method first and continues down, printing the name of each method as it works its way
down the call stack from the top.
Polymorphism
- True
- True
- True (Dynamic Dispatch)
- False
will be garbage collected, it is not possible to predict when object finalizers will be run. Java
programmers, therefore, should avoid writing code for which program correctness depends
upon the timely finalization of objects. For example, if a finalizer of an unreferenced object
releases a resource that is needed again later by the program, the resource will not be made
available until after the garbage collector has run the object finalizer. If the program needs
the resource before the garbage collector has gotten around to finalizing the unreferenced
object, the program is out of luck.
Take help from another copy something is not OK
Sometime some object may refused GC for cleaning the memory.
When object hold the reference to resource like Database Connection, Connection to
file, Connection to printer etc. than that object will not allow GC to recleaned the
memory and GC also cant force that object.
Before invoking GC someone has to close all the resources properly.
JVM is responsible to invoke runFinalization() to clean the resources before invoking
etc.
JVM Tasks :
[i]
JVM has to detect the unused objects time to time and has to prepare the unused object
list.
[ii] When memory shortage problem is detected then JVM has to do the following :
* System.runFinalization();
* System.gc();
runFinalization() : This method is responsible to invoking finalize() method on all unused
object.
finalize() : This method is responsible for releasing the resources.
gc() : This method is responsible for cleaning the memory of all unused objects.
Note : As a developer we can call runFinalization() method and gc() method but not
guarantee for cleanup i.e. we cant force garbage collector.
----------------------------------------------**
**----------------------------------------------
MultiThreading
* threads are light-weight because they utilize minimum resources of the system. This
means they take
less memory and less processor time.
* A thread represents a separate path of execution of a group of statements.
Green Thread are scheduled by the JVM. And in the Native Thread model, the threads are
scheduled by the OS. Green threads emulate multithreaded environments without relying on
any native OS capabilities. They run code in user space that manages and schedules threads;
Sun wrote green threads to enable Java to work in environments that do not have native
thread support.
In the Green Thread model, the OS doesn't know anything about the threads used in the
JVM. It's up to the JVM to handle all the details.
The burden of thread scheduling is on the programmer's shoulders.Green threads can't take
advantage of multiple CPUs, but they have the advantage of lighter weight for context
switching.
Execution only one job at a time is called single tasking. Executing several jobs at a
time is called multi tasking. In single tasking, the processor time is wasted, but in multi
tasking, we can utilize the processor time in an optimum way.
Difference between sleep() and wait() methods : both sleep() and wait() methods are
used to suspend a thread execution for a specified time. When sleep() method is
executed inside the synchronized block, the object is still under lock. When wait()
method is executed, it breaks the synchronized block, so that the object lock is removed
and it is available.
Generally, sleep() is used for making a thread to wait for some time. But wait() is used
in connection with notify() or notifyAll() methods in thread communication.
Thread Life Cycle :
A thread is created using new Thread() statement and is executed by start() method.
The thread enters runnable state and when sleep() or wait() methods are used or when
the thread is blocked on I/O, it then goes into not runnable state. From not runnable
state, the thread comes back to the runnable state and continue running the
statements. The thread dies when it comes out of run() method. These state transitions
of a thread are called Life Cycle of a thread.
The different states of threads are as follows:
1) New When a thread is instantiated it is in New state until the start() method is called on
the thread instance. In this state the thread is not considered to be alive.
2) Runnable The thread enters into this state after the start method is called in the thread
instance. The thread may enter into the Runnable state from Running state. In this state the
thread is considered to be alive.
3) Running When the thread scheduler picks up the thread from the Runnable threads
pool, the thread starts running and the thread is said to be in Running state.
4) Waiting/Blocked/Sleeping In these states the thread is said to be alive but not runnable.
The thread switches to this state because of reasons like wait method called or sleep method
has been called on the running thread or thread might be waiting for some i/o resource so
blocked.
5) Dead When the thread finishes its execution i.e. the run() method
execution completes, it is said to be in dead state. A dead state can not be started again. If a
start() method is invoked on a dead thread a runtime exception will occur.
Why do we need synchronization?
For an answer, consider this example: You write a Java program that uses a pair of
threads to simulate withdrawal/deposit of financial transactions. In that program, one
thread performs deposits while the other performs withdrawals. Each thread
manipulates a pair of shared variables, class and instance field variables, that identifies
the financial transaction's name and amount. For a correct financial transaction, each
thread must finish assigning values to the name and amountvariables (and print those
values, to simulate saving the transaction) before the other thread starts assigning
values to name and amount (and also printing those values).
Differences between threads and processes are:1. Threads share the address space of the process that created it; processes have their
own address.
2. Threads have direct access to the data segment of its process; processes have their
own copy of the data segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must
use interprocess communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent
process.
6. Threads can exercise considerable control over threads of the same process;
processes can only exercise control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the
behavior of the other threads of the process; changes to the parent process do not affect
child processes.
synchronized keyword can be applied to static/non-static methods or a block of code.
Only one thread at a time can access synchronized methods and if there are multiple
threads trying to access the same method then other threads have to wait for the
execution of method by one thread. Synchronized keyword provides a lock on the
object and thus prevents race condition.
Q. What happens if a start method is not invoked and the run method is directly
invoked?
Ans) If a thread has been instantiated but not started its is said to be in new state. Unless
until a start() method is invoked on the instance of the thread, it will not said to be alive. If
you do not call a start() method on the newly created thread instance thread is not considered
to be alive. If the start() method is not invoked and the run() method is directly called on the
Thread instance, the code inside the run() method will not run in a separate new thread but it
will start running in the existing thread.
Q. How many locks does an object have?------------- ONE
Ans) Each object has only one lock.
Q. Can a thread hold multiple locks at the same time? ------------ YES
Ans) Yes. Once a thread acquires a lock and enters into the synchronized method / block, it
may call another synchronized method and acquire a lock on another object.
Q4) Can a thread call multiple synchronized methods on the object of which it hold the
lock?
Ans) Yes. Once a thread acquires a lock in some object, it may call any other synchronized
method of that same object using the lock that it already holds.
Q5) Can static methods be synchronized?
Ans) Yes. As static methods are class methods and have only one copy of static data for the
class, only one lock for the entire class is required. Every class in java is represented by
java.lang.Class instance. The lock on this instance is used to synchronize the static methods.
Q6) Can two threads call two different static synchronized methods of the same class?
Ans) No. The static synchronized methods of the same class always block each other as only
one lock per class exists. So no two static synchronized methods can execute at the same time.
Q7)Does a static synchronized method block a non-static synchronized method?
Ans)No As the thread executing the static synchronized method holds a lock on the class and
the thread executing the non-satic synchronized method holds the lock on the object on which
the method has been called, these two locks are different and these threads do not block each
other.
Q8) Once a thread has been started can it be started again?
Ans) No. Only a thread can be started only once in its lifetime. If you try starting a thread
which has been already started once an IllegalThreadStateException is thrown, which is a
runtime exception. A thread in runnable state or a dead thread can not be restarted.
Q9) When does deadlock occur and how to avoid it?
Ans) When a locked object tries to access a locked object which is trying to access the first
locked object. When the threads are waiting for each other to release the lock on a particular
object, deadlock occurs .
Q10) What is a better way of creating multithreaded application? Extending Thread
class or implementing Runnable?
Ans) If a class is made to extend the thread class to have a multithreaded application then this
subclass of Thread can not extend any other class and the required application will have to be
added to this class as it can not be inherited from any other class. If a class is made to
implement Runnable interface, then the class can extend other class or implement other
interface.
Q11) Can the start() method of the Thread class be overridden? If yes should it be
overridden?
Ans) Yes the start() method can be overridden. But it should not be overridden as its
implementation in thread class has the code to create a new executable thread and is
specialised.
What is thread starvation?
Ans) In a multi-threaded environment thread starvation occurs if a low priority thread is not
able to run or get a lock on the resoruce because of presence of many high priority threads.
This is mainly possible by setting thread priorities inappropriately.
* We can implements thread in Java in two ways :
1. by extending java.lang.Thread extends Object implements Runnable
2. by implementing java.lang.Runnable Interface. (only one method called void
run())
If we implements Thread through Runnable Interface then call thread like this :
Student stu=new Student();
|o|
Student stu=new Student();
|r|
new Thread(stu).start();
If we implements Thread through Thread class then call thread like this :
Student stu=new Student();
stu.start();
* static int activeCount() Returns the number of active threads in the current
threads ThreadGroup .
* logn getId() Returns the identifier (ID) of the thread.
* public final String getName() Returns the thread name.
* public final void setName(String) set the new name of the thread.
* public final void checkAccess() Determines if the currently running thread has
permission to modify this thread.
* public void destroy() Deprecated. This mehtod was originally designed to destroy
this thread without any cleanup.
* public static Thread currentThread() Returns the currently executing thread.
* public static void dumpStack() prints a stack trace of the current thread. This
method is used only for debugging.
* public static boolean holdsLock(Object obj) Returns true if and only if the current
thread holds the monitor lock on the specified object.
* public final void stop() Deprecated.
* public final void suspend()- Deprecated.
* public final void resume() Deprecated.
* public final void setDaemon(boolean) makes this thread as either a daemon thread
or user thread.
* public final boolean isDaemon() Returns true if thread is a daemon thread
otherwise false.
* public static native void sleep(long) currently executing thread to sleep for the
specified number of milliseconds.
* public static void sleep(long, int) Causes the currently executing thread to sleep
(cease execution) for the specified number of milliseconds plus the specified number of
nanoseconds, subject to the precision and accuracy of system timers and schedulers.
* public void interrupt() current thread interrupting itself.
* public boolean isInterrupt() Returns true if the current thread has been
interrupted; false otherwise.
* public void run() If this thread was constructed using a separate Runnable run
object, then that Runnable object's runmethod is called; otherwise, this method does
nothing and returns.
* public synchronized native void start() causes this thread to begin execution; the
JVM calls the run method of this thraed.
* public final void join() waits for this thread to die.
* public final synchronized void join(long) waits at most millis milliseconds for this
thread to die.
* public final synchronized void join(long, int) waits at most millis milliseconds plus
nanos nanoseconds for this thread to die..
* public String toString() (Override method) Returns a string representation of this
thread, including the threadname, priority and thread group.
* main thread always runs in a Java program by default. main thread priority is 5.
* Garbage Collector thread belongs to low-priority.
* Stop a thread First of all, we should create a boolean variable which stores false.
When the user wants to stop the thread, we should store true into the variable. The
status of the variable is checked in the run() method and if it is true, the thread executes
return statement and then stops.
* when a thread has locked an object and waiting for another object to be released by
another thread and the other thread is also waiting for the first thread to release the
first object, both the threads will continue waiting forever. This is called Thread
deadlock.
* Deamon thread is a low-priority thread that executes continuously in background
doing the garbage collection operation for the Java runtime system. Deamon thread are
service providers for other threads or objects. It generally provides a background
processing.
* Thread Priorities are used by the thread schedular to decide when each thread
should be allowed to run.
Set the Thread Prioties
* If we extends Thread class then we call run method like - new Student().start(); .
a lock can be acquired on a class. This lock is acquired on the class's Class object
Thread.start() method (native method) of Thread class actually does the job of running the
Thread.run() method in a thread. If we directly call Thread.run() method it will executed in
same thread, so does not solve the purpose of creating a new thread.
We need run() & start() method both because JVM needs to create a separate thread which
can not be differentiated from a normal method call. So this job is done by start method
native
implementation
which
has
to
be
explicitly
called.
Another advantage of having these two methods is we can have any object run as a thread if
it implements Runnable interface. This is to avoid Javas multiple inheritance problems
which will make it difficult to inherit another class with Thread.
--------------------------------------------------------------------------------------------------
Generic
Type
Generic Type A Generic type represents a class or an interface that is type-safe. It can
act on any data type.
Erasure Creating a non-generic version of a generic type by the Java compiler is
called Erasure.
Generic Class A generic class represents a class that is type-safe. This means a generic
class can act upon any data type. Similarly, a generic interface is also type-safe and
hence it can use any data type. Generic classes and generic interface are also called
Parameterized types because they use a parameter that determines which data type
they should work upon.
When a generic class or generic interface is written, the programmer need not rewrite
the same class or interface whenever he wants to use or the interface with a new data
type. The same class or interface can work with any data type.
Generic types are designed to act upon objects. Hence they can not work with primitive
data types.
Since, generic class acts on any data type, we can not specify a particular data type
when designing the class. In the place of the data type, we use a generic parameter like
<T>, or <GT> and write the class as
class Hello<T>{
class code;
}
Here, <T> is called generic parameter and it determines at the time of compilation,
which data type actually the programmer wants to use with the class.
Generic Method : we can make a method alone as generic method, by writing the
generic parameter before the method return type as:
<T> void display(){
}
Generic Interface :
-------------------------------------------------------------------------------------------
java.lang
Package
Object Class : default Super Class for All Java Class. Contains 11 Methods.
public class Object{
public final native class getClass();
public native int hashCode();
public String toString();
public boolean equals(Object);
protected void finalize() throws Throwable;
protected native Object clone() throws CloneNotSupportedException ;
public final native void notify();
public final native void notifyAll();
public final void wait() throws InterruptedException;
public final native void wait(long) throws InterruptedException;
public final void wait(long, int) throws InterruptedException;
}
System Class : (used to get the information about current System)
By using the System class we can interact with the default input or output device and other
part of the machine.
Inside the System class following are the properties available by using that we can interact
with the default input or output device.
public static final InputStream in;
public static final PrintStream out;
public static final PrintStream err;
When the JVM will be started then some default object will be created. Some Object
reference will be stored in the reference variable defined in the System class to interact with
the default input/output device. If we want we can change the reference to point some
another input or output device by using the following method with the System class.
public static void setIn(InputStream);
public static void setErr(printStream);
public static void setOut(printStream);
System class will be used to access the information of the System. The information will be
always some for one machine so the member of the System class is defined as static. In this
condition no need to create the object of the System class. So, the Constructor of the System
class is defined as private.
The Constructor of the System class is private so we can not create the object for the
System class.
Runtime Class : (in java.lang Package), implemented as Singleton class.
Proxy Proxy provides static methods for creating dynamic proxy classes and instances, and
it is also the superclass of all dynamic proxy classes created by those methods.
ReflectPermission The Permission class for reflective operations. A ReflectPermission is a
named permission and has no actions. The only name currently defined is
suppressAccessChecks, which allows suppressing the standard Java language access checks
-- for public, default (package) access, protected, and private members -- performed by
reflected objects at their point of use.
There are following type of Interface available in java.lang.reflect Package :
-------------------------------------------------------------------------------InvocationHandler InvocationHandler is the interface implemented by the invocation
handler of a proxy instance.
Member Member is an interface that reflects identifying information about a single
member (a field or a method) or a constructor.
There are following type of Exception available in java.lang.reflect Package :
-------------------------------------------------------------------------------InvocationTargetException
MalformedParameterizedTypeException
UndeclaredThrowableException
If we want to load the class dynamically then we can use the following methods :
java.lang.Class
public static Class forName(String className);
public static Class forName(String className, boolean init, ClassLoader
loader);
If we want to create the object of the class dynamically, we can use the following
method :
public Object newInstance();
If we want to verify one object is of specific type or not then we can use the following
method :
public Object isInstance(Object obj);
If we want to access all the public methods defined in the current class or inherited
from the super class then we can use the following method :
public Method[] getMethods();
If we want to access all the methods defined in the current class referred by the class
type object, then we can use the following method :
public Method[] getDeclaredMethods();
To get the information about the fields we can use the following methods :
public Field[] getFields();
Input-Output
* Stream are mainly useful to move data from one place to another place. This concept
can be used to receive
data from an input device and send data to an output data. Streams can be
categorized as input stream and
output stream.
* Input streams are streams which receive or read data while Output streams are
streams which send or write
data. All streams are represented by classes in java.io Package.
* Streams are Classified in two types Byte Streams and Character/Text Streams.
* Bytes Steams represents data in the form of individual bytes. Byte streams are used
to handle any type of
data like text, images, audio and video files.
LinkedHashSet,
set. (Ordered)
not allow duplicate values.
Accessing elements by their index is not
possible.
not allow null elements.
* ArrayList is not Synchronized this means that when more than one thread acts
simultanuously on the
ArrayList object, the result may be incorrect in some cases.
* providing fast random access and fast traversal.
Sort ArrayList :
Collections.sort(list);
for(int i=0; i<list.size(); i++){
System.out.println(list.get(i));
}
Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of
ArrayList<String> = new ArrayList<String>();
Ans) It is preferred because:
If later on code needs to be changed from ArrayList to Vector then only at the declaration
place we can do that.
The most important one If a function is declared such that it takes list. E.g void
showDetails(List list);
When the parameter is declared as List to the function it can be called by passing any
subclass of List like ArrayList,Vector,LinkedList making the function more flexible
Vector : public class Vector<E> extends AbstractList<E>
implements List<E>, RandomAccess,Cloneable, Serializable
* Vector size can grow or shrink as needed to accommodate adding and removing
items after the Vector has
been created.
* Vector is Synchronized. (thread safe)
* like Array, Vector component is accessed using integer index no.
* Vector default capacity is 10.
* Vector contains duplicate values.
* Vector implementation based on Resizable Array Data Structure.
* Vector use equals() method.
Synchronized
HashMap
Collections.synchronizedMap(new
TreeMap :
public class TreeMap<K,V> extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable
* TreeMap can be used to store a group of objects as key-value pairs where all the
entries are arranged to some sorting order of Keys.
* the underlaying data structure is RED-BLACK Tree.
* use equals() and compareTo() method.
* Duplicates keys are not allowed but values can be duplicate.
* Insertion order is not preserved because insertion is based on some sorting order.
month of the calendar system has value MONTH == JANUARY for all calendars.
Other values are defined by the concrete subclass, such as ERA. See individual field
documentation and subclass documentation for details.
public class Date
extends Object
implements Serializable, Cloneable, Comparable<Date>
The class Date represents a specific instant in time, with millisecond precision.
StringTokenizer
public class StringTokenizer extends Object implements Enumeration<Object>
The StringTokenizer class allows an application to break a string into tokens. The
tokenization method is much simpler than the one used by the StreamTokenizerclass.
The StringTokenizer methods do not distinguish among identifiers, numbers, and
quoted strings, nor do they recognize and skip comments.
The set of delimiters (the characters that separate tokens) may be specified either at
creation time or on a per-token basis.
Class Locale
public final class Locale
extends Object implements Cloneable, Serializable
A Locale object represents a specific geographical, political, or cultural region. An operation
that requires a Locale to perform its task is called locale-sensitive and uses the Locale to
tailor information for the user. For example, displaying a number is a locale-sensitive
operation--the number should be formatted according to the customs/conventions of the
user's native country, region, or culture.
Create a Locale object using the constructors in this class:
Locale(String language);
Locale(String language, String country);
Locale(String language, String country, String variant);
-------------------------------------------------------------------------------------------------
Wrapper
Class
* A Wrapper class is a class whose object wraps or contains a primitive data type.
When we create an object to
a wrapper class, it contains a field and in this field, we can store a primitive data
type.
* java.lang Package provides all Wrapper Classes for each of the primitive data.
* All Wrapper class are Final & immutable so their state can not be changed.
* There are 8 Wrapper Class corresponding to primitive to data types
- Character, Byte, Short, Integer, Long, Float, Double, Boolean.
* Number is an abstract Super class whose subclasses are Byte, Short, Integer, Long,
Float, Double.
So the methods of Number class are commonly available in all these Subclasses.
* Character class has only one Construtor.
Character(char ch)
* Byte, Short, Integer, Long, Double, Boolean classes have two Constructors.
Byte(byte b) (String str)
* Float class has three Constructors.
StringBuffer,
StringBuilder,
String
Default Capacity : 16, next time : 16*2+2= 34, next time : 34*2+2=70, next time :
70*2+2=142
String : (final, immutable)
public final class String
extends Object
implements Serializable, Comparable<String>, CharSequence
* String is a Final Class so we can not extends String Class and can not Override
String class any methods.
* String class object are immutable and hence their contents can not be modified.
* String is a class in java.lang package. But in java, all classes are also considered as
data types. So we can take
String as a data type.
* Creating String Object without new Operator :
String str1 = Krishu;
[i]
Checks whether the String Literal is available in the Constant pool or not.
[ii] If String Literal is available in the pool then its address will be assigned to reference
variable.
[iii] If String Literal is not available in the pool then new String object will be created in
the pool and newly created String object address will be assigned to reference
variable.
* Creating String Object with new Operator :
String str1 = new String (Krishu);
[i]
Checks whether the String Literal is available in the pool or not.
[ii] If String Literal is available in the pool then ignores.
[iii] If String Literal is not available in the pool then new String object will be created in
the pool.
[iv] New String object will be created outside the pool and address of the object which is
outside the pool will be assigned to reference variable.
How to sort list of strings - case insensitive?
Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
Field Summary
static CASE_INSENSITIVE_ORDER
Comparator<String> A Comparator that orders String objects as by compareToIgnoreCase.
Constructor Summary
String()
Initializes a newly created String object so that it represents an empty character sequence.
String(byte[] bytes)
Constructs a new String by decoding the specified array of bytes using the platform's default
charset.
String(byte[] bytes, Charset charset)
Constructs a new String by decoding the specified array of bytes using the specified charset.
String(byte[] ascii, int hibyte)
Deprecated. This method does not properly convert bytes into characters. As of JDK 1.1,
the preferred way to do this is via the String constructors that take a Charset, charset name,
or that use the platform's default charset.
String(byte[] bytes, int offset, int length)
Constructs a new String by decoding the specified subarray of bytes using the platform's
default charset.
String(byte[] bytes, int offset, int length, Charset charset)
Constructs a new String by decoding the specified subarray of bytes using the specified
charset.
String(byte[] ascii, int hibyte, int offset, int count)
Deprecated. This method does not properly convert bytes into characters. As of JDK 1.1,
the preferred way to do this is via the String constructors that take a Charset, charset name,
or that use the platform's default charset.
String(byte[] bytes, int offset, int length, String charsetName)
Constructs a new String by decoding the specified subarray of bytes using the specified
charset.
String(byte[] bytes, String charsetName)
Constructs a new String by decoding the specified array of bytes using the specified charset.
String(char[] value)
Allocates a new String so that it represents the sequence of characters currently contained in
the character array argument.
String(char[] value, int offset, int count)
Allocates a new String that contains characters from a subarray of the character array
argument.
String(int[] codePoints, int offset, int count)
Allocates a new String that contains characters from a subarray of the Unicode code point
array argument.
String(String original)
Initializes a newly created String object so that it represents the same sequence of characters
as the argument; in other words, the newly created string is a copy of the argument string.
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the
string buffer argument.
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the
string builder argument.
Method Summary
char charAt(int index)Returns the char value at the specified index.
boolean contains(CharSequence s)
sequence of char values.
Deprecated. This method does not properly convert characters into bytes. As
of JDK 1.1, the preferred way to do this is via the getBytes() method, which
uses the platform's default charset.
byte[] getBytes(String charsetName)
Encodes this String into a sequence of bytes using the named charset, storing
the result into a new byte array.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
int hashCode()Returns a hash code for this string.
int indexOf(int ch)Returns the index within this string of the first occurrence of
the specified character.
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified
character, starting the search at the specified index.
int indexOf(String str)Returns the index within this string of the first occurrence
of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified
substring, starting at the specified index.
String intern()Returns a canonical representation for the string object.
boolean isEmpty()Returns true if, and only if, length() is 0.
int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified
character.
int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified
character, searching backward starting at the specified index.
int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the
specified substring.
int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified
substring, searching backward starting at the specified index.
int length()Returns the length of this string.
boolean matches(String regex)Tells whether or not this string matches the given
regular expression.
int offsetByCodePoints(int index, int codePointOffset)
Returns the index within this String that is offset from the given index by
codePointOffset code points.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int
len)Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in
this string with newChar.
String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target sequence
with the specified literal replacement sequence.
String replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular
expression with the given replacement.
String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular
expression with the given replacement.
String[] split(String regex)Splits this string around matches of the given regular
expression.
String[] split(String regex, int limit)Splits this string around matches of the given
regular expression.
boolean startsWith(String prefix)Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset)
Tests if the substring of this string beginning at the specified index starts with
the specified prefix.
CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
String substring(int beginIndex)Returns a new string that is a substring of this
string.
String substring(int beginIndex, int endIndex)Returns a new string that is a
substring of this string.
char[] toCharArray()Converts this string to a new character array.
String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the
default locale.
String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the
given Locale.
String toString()This object (which is already a string!) is itself returned.
String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the
default locale.
String toUpperCase(Locale locale)Converts all of the characters in this String to
upper case using the rules of the given Locale.
String trim()Returns a copy of the string, with leading and trailing whitespace
omitted.
static String valueOf(boolean b)Returns the string representation of the boolean argument.
static String valueOf(char c)Returns the string representation of the char argument.
static String valueOf(char[] data)Returns the string representation of the char array
argument.
static String valueOf(char[] data, int offset, int count)
Returns the string representation of a specific subarray of the char array
argument.
static String valueOf(double d)Returns the string representation of the double argument.
static String valueOf(float f)Returns the string representation of the float argument.
static String valueOf(int i)Returns the string representation of the int argument.
static String valueOf(long l)Returns the string representation of the long argument.
static String valueOf(Object obj)Returns the string representation of the Object argument.
--------------------------------------------------------------------------------------------------------------------------------------------Operator : An operator is a symbol that perform an operation on one, two or three
operands.
Arithmetic
Operator
Unary Operator
Assignment
Operator
Relational Operator
Logical Operator
Boolean Operator
Bitwise Operator
- (Unary Minus)
%
++
(total 5)
--
(total 3)
(total 1)
(total 6)
( total 3)
(total 3)
(total 7)
Note :
* Positive numbers are represented in binary using 1s complement
notation.
* Negative numbers are represented in binary using 2s complement notation.
>> will protect the sign bit whereas the >>> operator will not protect the signn bit. It
always fills 0 in the sing bit.
Abstract Class :
* Abstract class contains All Properties like a normal class and 0 or more abstract
method.
* If any abstract method is not implemented, then that sub class should be declared as
abstract.
* Abstract class contains incomplete methods, it is not possible to estimate the total
memory required to create the
object, So, JVM can not create objects to an abstract class.
* We can not create object of abstract class but we can create a reference of abstract
type.
* The reference of abstract class can be used to refer to objects of its subclasses.
------------------------------------------------------------------------------------
JDK
1.5
New
Features
import static
Constructor :
* Constructor is similar to a method that is used to initialize the instance variables of a
class.
* Constructor has the same name as the name of the class to which it belongs.
* Constructor automatically called and executed at the time of creating an object.
* When the programmer does not write any constructor in a class, the Java Compiler
writes a default Constructor and initialized the instance variables with the default
values.
* The access modifier of the default constructor is same as access modifier of the class
(public & default only).
A Constructor has the following Characteristics :
----------------------------------------------------- A Constructor does not return any value, not even void.
A Constructor is called and executed only once per object. This means when we create
an object, the constructor is called.
A Constructor declared only public, protected and private modifiers.
A Constructor does not declared static, final, abstract, synchronized, native, transient,
volatile, strictfp.
The access modifier for the default constructor will be same as access modifier of the
class.
If Constructor will be declared as private modifier then we can not create object of that
class.
If we are using the return type with the constructor then that will be treated as method,
that cant be used as Constructor.
Constructors are always executed by the same thread.
Constructors may include parameters of various types. When the constructor is
invoked using the new operator, the types must match those that are specified in the
constructor definition. JVM differentiates constructors on the basis of arguments
passed in the constructor.
If we don't define a constructor for a class, A default constructor with no arguments
will be called automatically by the JVM. The default constructor calls the default
parent constructor (super()) and initializes all instance variables to default value (zero
for numeric types, null for object references, and false for boolean).
this(...) - Calls another constructor in same class. Often a constructor with few
parameters will call a constructor with more parameters, giving default values for the
missing parameters. Use this to call other constructors in the same class.
super(...) - Use super() to call a constructor in a parent class. Calling the constructor
for the Superclass must be the first statement in the body of a constructor. If we are
satisfied with the default constructor in the Superclass, there is no need to make a call
to it because it will be supplied automatically.
Interface
Allow
Not
Contains
duplicate
Synchronized
null
value
Allow
Contains
Synchronized duplicate
null
value
JDK
Order/
sorted
Methods
that can be
called on
elements
Data Str
on wh
impleme
is ba
1.2
Not order
equals()
Resizabl
1.0
Not order
equals()
Resizabl
List
List
or
cy
ss
List
ed
t
List<E>
Queue<E>
Deque<E>
Allow
Not
Contains
duplicate
Synchronized
null
value
1.2
Insertion/
Priority/
equals()
dequeue compareTo()
order
Set<E>
not
Not
Unique
Contains
Synchronized elements
null
1.2
No Order
equals()
hashCode()
Hashtab
Linked
ed
Set
Set<E>
Not
Unique
Synchronized elements
1.4
Insertion
order
equals()
hashCode()
Hash tab
doublylis
Set
Set<E>
Not
Unique
Synchronized elements
1.2
Sorted
compareTo()
Balance
Map
Map<K,V>
Not
Synchronized
Unique
Keys
1.2
No Order
equals()
hashCode()
Hash
using a
able
cy
ss
Map<K,V>
Synchronized
Unique
Keys
Set
ed
Map
Map
ity
ue
y
Not
Synchronized
Unique
Keys
Sorted
Map<K,V>
Not
Naviga
Synchronized
bleMap<K,V>
Unique
Keys
Map<K,V>
Linke
equals()
hashCode()
1.4
Key
insertion
order/
Access
order of
entries
equals()
hashCode()
Hash tab
doublylis
1.2
Stored in
equals()
key order compareTo()
Balance
eue
What is a ResourceBundle class?
The ResourceBundle class is used to store locale-specific resources that can be loaded
by a program to create the program's appearance to the particular locale in which it is
being run.
1. What is fail-fast property?
At high level - Fail-fast is a property of a system or software with respect to its
response to failures. A fail-fast system is designed to immediately report any failure or
condition that is likely to lead to failure. Fail-fast systems are usually designed to stop
normal operation rather than attempt to continue a possibly-flawed process. When a
problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a nonintuitive technique: "failing immediately and visibly" sounds like it would make your
software more fragile, but it actually makes it more robust. Bugs are easier to find and
fix, so fewer go into production. In Java, Fail-fast term can be related to context of
iterators. If an iterator has been created on a collection object and some other thread
tries to modify the collection object "structurally", a concurrent modification
exception will be thrown. It is possible for other threads though to invoke "set"
method since it doesn't modify the collection "structurally". However, if prior to
calling "set", the collection has been modified structurally,
"IllegalArgumentException" will be thrown.
Annonims class no construcgor
1. Set & List interface extend Collection, so Why doesn't Map interface extend
Collection?
Though the Map interface is part of collections framework, it does not extend
collection interface. This is by design, and the answer to this questions is best
described in Sun's FAQ Page: This was by design. We feel that mappings are not
collections and collections are not mappings. Thus, it makes little sense for Map to
extend the Collection interface (or vice versa). If a Map is a Collection, what are the
elements? The only reasonable answer is "Key-value pairs", but this provides a very
limited (and not particularly useful) Map abstraction. You can't ask what value a given
key maps to, nor can you delete the entry for a given key without knowing what value
it maps to. Collection could be made to extend Map, but this raises the question: what
are the keys? There's no really satisfactory answer, and forcing one leads to an
unnatural interface. Maps can be viewed as Collections (of keys, values, or pairs), and
this fact is reflected in the three "Collection view operations" on Maps (keySet,
entrySet, and values). While it is, in principle, possible to view a List as a Map
mapping indices to elements, this has the nasty property that deleting an element from
the List changes the Key associated with every element before the deleted element.
That's why we don't have a map view operation on Lists.