Академический Документы
Профессиональный Документы
Культура Документы
1) Inheritance
2) Data Abstraction
3) Encapsulation
4) Polymorphism
A B C D
This is the general way of multiple inheritance. Suppose class A having a get() method
and class B also having a get() method the object of class E tries to access get()
method the JVM gets confused because it doesnt know which method to call because
class E is having two parent classes.
1) Single Polymorphism
2) Multiple Polymorphism
In single polymorphism we will have only one super class, where as in multiple
polymorphism we have more than one super classes. Java achieves Polymorphism by
method overloading and method overriding.
2. Features Of java
1) Simple
2) Robust
3) Secure
4) Distributed
5) Multi Threaded
6) Portable
7) Architecture neutral
8) Object Oriented
9) Interpreted
4) Distributed: In java one object can communicate with another object which is in
another location or on another machine. So java can be used effectively in distributed
systems also.
5) Multi-Threaded: Java uses the concept of threads which gives support for
concurrent processing.
6) Portable & Architecture neutral: When we develop any program by using either
C or C++ the result may be different based on the different machines because of the
different architectures of the machines.
This will be a disadvantage in developing the applications when we use the machines
of different architectures, where as java does not worry about the architecture of the
machine because JVM takes care of all the thigs.
7) Object Oriented: With out any doubt java is purely object oriented.
So what ever may be the operating system we are using we can have same
byte code irrespective of O.S and architecture.
Enhancements in jdk1.5:
Garbage collection ergonomics: Provides for the automatic detection and choice
of the client or server runtime compiler, which enhances performance on server-class
machines.
Image I/O: Performance and memory usage improvements have been made when
reading and writing JPEG images
for(int i : numbers)
sum+=numbers[i];
limitations:
9 For each loop is not useful for filtering.
9 It is not useful for loops to replace the elements in the list or arrays.
9 This should use only for reading the elements of list.
Varargs:
Prior to varargs, a method that take an arbitrary number of values required you to
create an array and put the values into the array prior to invoking the method. But varargs
varargs feature automates and hides the process.
Syntax:
method_name (datatype args){}
The three periods after the final parameter's type indicate that the final argument may
be passed as an array or as a sequence of arguments. Varargs can be used only in the final
argument position.
Example:
When used correctly varargs can really clean up some ugly code. The following
example shows method that takes a variable number of String arguments:
main(String code);
main(String code, String arg );
main(String code, String arg,arg1,arg2);
main(String code, String arg,arg1,arg2);
The interesting item to discuss about varargs is the compatibility you get if you
replace the first four examples with a new, vararged one as follows:
All varargs are source compatiblethat is, if you recompile all callers of the main()
method, you can just replace all four methods directly.
Static Import: In order to access static members, it is necessary to qualify references with
the class they came from.
For example:
double r = Math.cos(Math.PI * theta)
The static import construct allows unqualified access to static members without
inheriting from the type containing the static members.
Once the static members have been imported, they may be used without qualification:
Note:
Use Static Import when you require frequent access to static members from one or
two classes.
If you overuse the static import feature, it can make your program unreadable and
unmaintainable, polluting its namespace with all the static members you import.
Conclusion:
The static import declaration imports static members from classes, allowing them to
be used without class qualification.
Generics provides a way for you to communicate the type of a collection to the
compiler, so that it can be checked.
Example:
ArrayList list = new ArrayList();
list.add(0, new Integer(42));
int total = ((Integer)list.get(0)).intValue();
The cast to Integer on the last line is an example of the typecasting issues that generic
types aim to prevent. The compiler cannot pick up type mismatches at compile time. The first
notification of a problem is a ClassCastException at runtime.
Using Genrics:
Conclusion:
AutoBoxing/UnBoxing:
Converting between primitive types, like int, boolean, and their equivalent Object-
based counterparts like Integer and Boolean, can require unnecessary amounts of extra
coding, especially if the conversion is only needed for a method call to the Collections API,
for example.
Before:
ArrayList list = new ArrayList();
list.add(0, new Integer(42));
int total = ((Integer)list.get(0)).intValue();
After:
ArrayList list = new ArrayList();
list.add(0, 42);
int total = list.get(0);
The 5.0 version leaves the conversion required to transition to an Integer and
back to the compiler.
Annotations:
The metadata feature in J2SE 5.0 provides the ability to associate additional data
alongside Java classes, interfaces, methods, and fields. This additional data, or annotation, can
be read by the javac compiler or other tools, and depending on configuration can also be
stored in the class file and can be discovered at runtime using the Java reflection API.
Built in Annotations:
SuppressWarnings.
Deprecated.
Override.
SuppressWarnings:
@SuppressWarnings("deprecation")
public static void selfDestruct()
{
Thread.currentThread().stop();
}
Deprecated:
Override:
Override indicates that the method it annotates should be overriding a method with
the same signature in a superclass:
@Override
public int hashCode() {
...
}
Take the above exampleif you were to fail to capitalize the "C" in hashCode, you wouldn't get
an error at compile time, but at runtime, your method would not be called as you expected. By
adding the Override tag, the compiler complains if it doesn't actually perform an override.
This also helps in the case where the superclass changes. If, say, a new parameter were added
to this method and the method itself were renamed, then the subclass will suddenly fail to
compile, as it no longer overrides anything in the super.
Scanner: Java.util.Scanner class simplifies the reading of input data from variety of sources
such as keyboard ,file etc., To read data from standard input console we have to create
Scanner Object as follows.
Example:
while (s.hasNext()) {
System.out.println(s.next());
}
Scanner uses white spaces to separate tokens.To use separator invoke useDelimiter, specifying
regular expression.
Example:
4. CLASS
Definition: A class is a blueprint of any real world entity from which many instances are
Created.
This blueprint can contain:
Static Block
Member Declaration
Method Definitions
// constructors
// Method definitions
Static Block: Static block will be executed before invoking the constructor.
It should always be in the beginning of the class definition.
Member variable declaration: The variables can be primitive type, derived, or user-defined
(class) type.
The declaration takes the following form:
1. A class can not be declared private, or protected unless it is defined inside another
class.
i.e., only inner classes can have private and protected access-specifiers.
2. A class can take the modifiers abstract, final but can not have static modifier.
3. A class can extend utmost one class. i.e., a class can have only one direct base-class at
any time.
4. A class can implement any number of interfaces along with extending one class.
There are 3 variations of class
1. class keyword
Definition:
An abstract class is a class that is declared abstractit may or may not include
abstract methods. Abstract classes cannot be instantiated, but they can be sub classed.
(Or)
A Class which have zero or more Abstract methods. Abstract class is a mixture of
class and Interface
{
<Access modifier> {static} <data type> <variable names.>
Static {
-----------------
} Comment [v1]: Abstract Class allows
Static Block
<constructor>{
-----------------
} Comment [v2]: We can write
Constructor
..
..
}
For Eg:-
abstract class AbstractClassDemo {
-----------------
}
Defining at least one Abstract method in a class
For Eg:-
abstract class AbstractClassDemo {
-----------------
public abstract void get(); Comment [v5]: Get() method is
abstract method
}
For Eg:-
abstract class AbstractDemo {
------------------
-----------------
}
class derived extends AbstractDemo{
----------------
----------------
AbstractDemo demo=new derived(); Comment [v6]: Here we are creating
a reference to the Abstract class with the
} derived class
Abstract class also extends another class without overriding or declaring the
abstract methods
Abstract class also implements the interfaces without implementing the
method.
6. Interface
Defining an interface:
We cant use static keyword before the methods in interface because all the methods of
interface are abstract, so we cant use static with abstract methods.
--- We cant use any access specifier except public (optional) for methods in interface
because all the methods of interface are by default public, but we should specify public
to methods while implementing in class.
An interface can extend any other interface but can not extend any class.
We can use both abstract and interface at a time but no specific use, because interface
itself is fully abstract.
We can access the variables (constants) of interface directly by using interface name
because all variables of interface are by default static.
We can get the reference of an interface by using the object of the class which
implements that interface.
E.g., InterfaceDemo demo = new Demo (); as in following sample code.
--- With this reference we can access the methods which belong to interface but not
to the class, this feature is available to secure the methods of class, as shown in the
below sample code.
Sample code 1:
interface InterfaceDemo {
int count = 100;
static int scount = 200;
Sample code 2:
import java.util.*;
Description: In the above example we are trying to call the methods hasNext() and next() of
the interface Iterator. Here ArrayList class inherits the method iterator() from
java.util.AbstractList, which is its super class.
iterator method of AbstractList class:
public Iterator<E> iterator()
It returns an iterator over the elements in this list in proper sequence. This
implementation returns a straight forward implementation of the Iterator interface, relying on
the backing list (here our ArrayList: al)s size(), get(int), and remove(int) methods.
We are use methods of many interfaces like this, all of them are being done internally,
in the similar way as we discussed, so we can call this feature as Hidden Feature of
Interface.
Sample code3:
public interface ItfInnerDemo{
InnerDemo id = new InnerDemo();
public void printId(InnerDemo id);
class InnerDemo{
InnerDemo(){
System.out.println("1 Object Create");
}
}
}
Using class.forName ()
Example:
Using Serializable
8. Rules of Overloading
1. Polymorphism is supported by java using the concept of over loading.
2. Over loading means we can define number of methods with the same name but with
different parameter list.
3. While overloading a method we consider only the parameter list not the return type of
the method.
static {
main("bajrang");
main("ash","jai");
main("ash","jai","sam");
}
for(String str:args){
new Overload(str);
}
}
}
In the above code we are overloading both the constructor and the main method, and we
can observe that we are not considered with the return type of the method.
So we can say that we can have the overloaded methods in interfaces also.
In the above code we defined two methods one is getMethods with no parameters
another which takes two integers as parameters. These two methods are said to be
overloaded.
The only difference that we can find in this code from above one is only at the 4th line. The
method int getMethod(int a,int b) is same as above one but only difference is the return
type. when we try to compile this code well get an error saying that getMethod( int a,int b)
is already defined.
So we can state that we will not consider the return type in overloading.
The methods having same parameter list but with different return type are not
over loaded.
9. Packages
Definition:
A package is a grouping of related classes and interfaces providing access
protection and name space management.
Package Creation:
Packages are created with package keyword.
There can be only one package statement in each source file.
Package names are written in lowercase letters.
Example:
package graphics;
public class Rectangle
{
Public static void main(String args)
{System.out.println(package demo);}
}
Compile:
javac Rectangle.java d .
Execute:
java pack.Rectangle;
Importing packages:
The classes and interfaces that comprise a package are called package members.
There are three ways to use package members.
To import a specific member into the current file, put an import statement at the
beginning of the file ,but after the package statement.
Rectangle class from the graphics package created in the previous section.
import graphics.Rectangle;
To import all the types contained in a particular package, use the import statement with
the asterisk (*) wildcard character.
import graphics.*;
import graphics.Rectangle.*;
Note: Above both statements wont show impact on the class.when we create an object to
that class its details gets imported.
Advantages:
Packages avoids naming conflicts.
Packages organizes source code effectively.
Note: If we have multiple classes and interfaces only one can be public,and it must have
the same name as source file.
10. Final Keyword
1. A final class can not be extended.
}
}
6. If an object is declared as final, we can not change the reference which it is referring
to, but we can perform all the operations available with that object.
this keyword is non-static Object, it is used to call the member variables and methods of same
Class.
E.g.:-
Class ThisDemo{
ThisDemo(){
this.get();
}
ThisDemo(String arg){
this();
}
public void get(){
System.out.println(Example of This Keyword);
}
}
Rules to be followed while using this Object:
Usually it refers to the same class.
We can have this keyword any where in the class.
It cannot be referred by static context i.e., static block, static variables , static methods
static{
//non-static variable this cannot be referenced from a static context
//System.out.println(this.count);
//System.out.println(this.ncount);
}
public ThisDemo(){
//this();c-error :recursive constructor invocation
System.out.println(this.count);
System.out.println(this.ncount);
}
}
class Demo{
//Demo();rt-error :recursive constructor invocation
//Demo demo = new Demo();
static{
}
Demo(){
System.out.println(this);
}
Demo(String args){
//super();
this();
}
public static void main(String... args){
Demo demo = new Demo("bajrang");
}
}
}
Example:
public class DefaultStatic {
DefaultStatic demo;
DefaultStatic() {
Demo=getInstance();
System.out.println(demo);
}
public static void main(String args[]) {
DefaultStatic demo1=new DefaultStatic();
System.out.println(demo1);
DefaultStatic demo2=new DefaultStatic();
System.out.println(demo2);
}
public DefaultStatic getInstance() {
Comment [v11]: Here we are creating
return DefaultStatic.this;
the instance for the class
}
13. Static Keyword
Contents:
) Introduction
) Example program
) Overview
Introduction:
To make class variables and methods static they should be preceeded with the keyword
static.
Static variables are shared by all the objects so only one copy is created.
Static variables can be accessed with class name without creating an object.
Static variables can be defined in class , abstract class and interface.
Gets executed only once when the class is loaded into the memory.
Variables declared in a static block cant be accesed outside the block.
Cannot use final with static block.
Static block can be defined in class , abstract class but not in interface.
Overriding:
A new feature in java 5 to import only static methods and variables of any class.
Eg :
import static java.lang.System.out;
import static java.lang.Meth.abs;
We cant use static methods in interface because all the methods of interface are
abstract.
We can access static variables defined in interface using interface name.
Static with transient:
Transient and static when used together , the transient is ignored and the object can be
saved or serialized.
Overview:
Class:
Does Applies
Class NO
Static Member Variables YES
Non-Static Member Variables YES
static block YES
Constructor NO
Static Methods YES
Non-static Methods YES
Abstract Class:
Does Applies
Class NO
Interface
Does Applied
Interface NO
Thread is part of a program that runs independently or along with other threads to
accomplish a task.
Most programs written today run as a single thread, causing problems when multiple
events or actions need to occur at the same time.
Let's say, for example, a program is not capable of drawing pictures while reading
keystrokes. The program must give its full attention to the keyboard input lacking the
ability to handle more than one event at a time. The ideal solution to this problem is the
seamless execution of two or more sections of a program at the same time.
The performance benefit of allowing multiple threads to run at the same time is realized
mainly on multi-processing systems.
Single threaded programs have one path of execution, and multi-threaded programs
have two or more paths of execution.
The easiest way to create a thread is to create a class that implements the Runnable
interface.
To implement Runnable, a class need only implement a single method called run(),
which is declared like this : public void run(){}.
After the new thread is created, we need to call its start () method that is declared in
Thread class.
Here while creating an instance of Thread class we are providing the object of our class
as parameter to Thread () constructor.
This allows the start () method of Thread class to execute our run () method.
This is because Thread class internally implements Runnable interface.
So it will define its own run () method.
At the compilation time the JVM assumes that the start () method of Thread class is
trying to execute (call) its own run () method.
And at the runtime start () method calls our run () method through the object we
have passed as a parameter.
The above program show how a start () of Thread class is calling the run () of our
class.
Thread class have many other methods other than that is shown above.
The second way to create a thread is to create a new class that extends Thread, and
then create an instance of that class.
The extending class must override the run () method, which is the entry point for the
new thread. It must also call start () to begin execution of the new thread.
Example program is as follows
public class ThreadDemo extends Thread{
public void run(){
System.out.println("Inside the run()");
}
At this point, we might be wondering why Java has two ways to create child threads,
and which approach is better.
The Thread class defines several methods that can be overridden by a derived class.
Of these methods, the only one that mush be overridden is run (). And this method is
required to be defined when implementing Runnable interface.
And when you are not overriding any of the other methods of Thread class then it will
be simple to implement Runnable interface.
15. Synchronization
Contents :
) Definition:
) Synchronized Keyword
) Rules of Synchronized Keyword
) Synchronized Block
) Rules of Synchronized Block
) When to use What
) Source Code
Definition:
When two or more threads need access to a shared resource, they need some way to
ensure that the resource will be used by only one thread at a time. The process by
which this is achieved is called synchronization. You can synchronize your code in
either of two ways. First way is to use synchronized methods. The second way to
use synchronized block(statement).
Synchronized keyword:
The synchronized keyword is the means by which java provides the thread-safety to
the methods. It means methods defined with synchronized keyword can not be
accessed concurrently by threads.
Example:
Synchronized Block:
While creating synchronized methods within classes that you create is an easy and
effective means of achieving synchronization, it will not work in all cases. Imagine that
you want to synchronize access to objects of a class that was not designed for
multithreaded access. That is, the class does not use synchronized methods.
Example is ArrayList. In this case, we can use synchronized block.
Syntax:
synchronized(object) {
// statements to be synchronized
}
Example:
.
static ArrayList<String> al = new ArrayList<String>();
synchronized(al){
al.add("Ashish");
al.add("Scam");
al.add("jaison");
}
.
9 synchronized block can also be written inside the methods(static as well as not
static methods).
Example:
import java.util.*;
public class SyncDemo{
static int scount = 100;
int count = 100;
static{
}
SyncDemo(){
}
interface SyncDemoInf{
public void set();
}
abstract class SyncDemoAbs{
public synchronized void set(){
}
Class:
Synchronized Synchronize()
Keyword Statement
Class X X
Static Member Variables X X
Non-Static Member Variables X X
static block X
Constructor X
Static Methods
Non-static Methods
Abstract Class:
Synchronized Synchronize()
Keyword Statement
Class X X
Static Member Variables X X
Non-Static Member Variables X X
Static block X
Constructor X
Static Methods
Non-static Methods
Abstract Methods X X
Interface
Does Applied
Interface X
Member variables X
Method Declarations X
16. Serialization
Contents:
) Definition:
) Serializable Interface
) Useful classes in Serialization
ObjectInputStream
ObjectOutputStream
) Example
Definition
Only an object that implements the Serializable interface can be saved and
restored by the serialization facilities. The Serializable interface defines no members.
It is simply used to indicate that a class may be serialized. If a class is serializable, all
of its subclasses are also serializable.
1. ObjectOutputStream:
Constructor of ObjectOutputStream:
Syntax of writeObject:
Constructor of ObjectInputStream:
Syntax of readObject:
Example:
oos.writeObject(object1);
.
Contents :
) Definitions.
) Types of Exceptions.
) Different ways of writing try, catch and finally blocks.
) Rules.
) Flow of trycatch.finally blocks.
) Throw and Throws.
Definition:
The try block identifies a block of code in which an exception can occur.
The catch block identifies a block of code, known as an exception handler, that
can handle a particular type of exception.
The finally block identifies a block of code that is guaranteed to execute, and is
the right place to close files, recover resources, and otherwise clean up after the
code enclosed in the try block.
The try statement should contain at least one catch block or a finally block and may
have multiple catch blocks.
1) try {
2) try {
} finally {
3) try{
}catch(ExceptionType name){
4) try {
}catch(Exception e){
}
}
5) try {
}catch(Exception e){
}
}
6) try {
---------------
---------------
try{
}catch(Exception e){
}
} catch (ExceptionType name) {
---------------
---------------
try{
}catch(Exception e){
}
}
Rules:
Throw: The throw keyword is used to throw an object as a reference. Here some
other object is going to handle the Exception
Rules :
We can use throw keyword in static and non-static methods, static block
and in constructor
We cannot use throw in variable declarations
If we use throw, the calling object must be written in try...catch block or
throws an Exception if it is Unchecked Exception.
When we use throw it should be always instance of Throwable
Throws: when throws is used then we there is no need to write the trycatch
block. And the throws keyword is used to throw an exception
Rules:
We can use throws keyword for constructor, static and non static methods
We cannot use throws keyword for static block and in variable declarations
We can use throws keyword in interfaces. i.e for abstract methods
JavaBean class has empty constructor and properties which are accessed by get/set (getters
and setters) methods.
Simple Example:
In the above example for each and every property we have to write one setter and
getter method and by using Getters and Setters .But by using the following method we can
write only once setter and getter methods for any number of properties.
class Demo{
public String name;
private String password;
private String email;
public String address;
public int no;