Вы находитесь на странице: 1из 43

Digitally signed by Ashish Mishra

Ashish Mishra DN: cn=Ashish Mishra, c=IN, email=ashish.mishra16@gmail.com


Reason: I am the author of this document
Date: 2007.04.07 09:16:02 +05'30'

1. OOP (Object Oriented Programming Methodology)

Three generations of programming languages. They are

1) Procedural oriented programming


2) Object oriented programming
3) Aspect oriented programming

Below are the basic concepts of object oriented programming methodology.

1) Inheritance
2) Data Abstraction
3) Encapsulation
4) Polymorphism

1) Inheritance:Inheritance the ability of child classes to derive the properties from


the parent class. Java doesnt support multiple inheritance, it supports only multilevel
inheritance.

java internally using the concept of multiple inheritance by using interfaces.

Why Java doesnt suport multiple inheritance?

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) We cant override the methods in this structure.


2) We cant use super to access the super class constructor.

So we avoided the usage of multiple inheritance in java, instead we can use


interfaces.

3) Data Abstraction: Data abstraction is nothing but hiding the implementation


details. We can hide the implementation of the methods which a particular object is
not required.

4) Encapsulation: Encapsulation is nothing but binding the data. This is achieved by


using the access specifiers.
How we are binding?

When we are defining a private variable we can access that variable


only by using a method of that class. This is nothing but binding.

4) Polymorphism:Polymorphism is nothing but multiple behaviors of objects by


using the methods. We are having two types of polymorphisms.

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.

We can do static polymorphism by using method overloading, dynamic polymorphism


by method overriding.

2. Features Of java

Following are the features of java.

1) Simple
2) Robust
3) Secure
4) Distributed
5) Multi Threaded
6) Portable
7) Architecture neutral
8) Object Oriented
9) Interpreted

1) Simple: Java is simple for programming. No pointers, case-sensitive.

2) Robust: In general robust means powerful. Java is powerful because it is having


advantages of Automatic memory management and just-in-time compiler.

3) Secure: Java is developed by using C so internally java uses the concept of


pointers, but developers are not given privilege to use pointers. Only JVM can use
pointers. So we cant access the memory locations.

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.

8) Interpreted: Different operating systems will have different compilers for


generating the compiled code. But the interpreter used by the JVM to produce the
byte code is same for all operating systems.

So what ever may be the operating system we are using we can have same
byte code irrespective of O.S and architecture.

3. New Features Of Java (jdk1.5)

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.

StringBuilder class: The addition of a new class StringBuilder that works


essentially as an unsynchronized StringBuffer for performance enhancement.

Java 2DTM technology: These Java 2D performance enhancements have spin-off


performance benefits in other areas of functionality such as Swing/JFC.

Image I/O: Performance and memory usage improvements have been made when
reading and writing JPEG images

New Features of JDK 5.0:

Enhance For Loop.


Varargs.
Static Import.
Generics.
Autoboxing/Unboxing.
Annotations.
Scanner.
For Each Loop:
The new enhanced for loop provides a simple, consistent syntax for iterating over
collections and arrays.
Initialization expression is evaluated only once inside the loop.
Syntax:
for( data type : arrays or collections)
{..}
Example:

Without for each loop:

//Returns the sum of elements in the numbers array.


int sum(int[] numbers)
{
int sum = 0;
for (int i=0; i < numbers.length ; i++)
sum += numbers[i];
return sum;
}

with for each loop:

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:

main(String code, Stringargs){}

All varargs are source compatiblethat is, if you recompile all callers of the main()
method, you can just replace all four methods directly.

Note: Avoid overloading a varargs method, or it will be difficult for programmers to


figure out which overloading gets called.

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.

import static java.lang.Math.PI;


or
import static java.lang.Math.*;

Once the static members have been imported, they may be used without qualification:

double r = cos(PI * theta);

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: The Collections API provides common functionality like LinkedLists,


ArrayLists and HashMaps that can be used by more than one Java type.
When we take an element out of a Collection, you must cast it to the type of element
that is stored in the collection. Besides being inconvenient, this is unsafe. The compiler does
not check that your cast is the same as the collection's type, so the cast can fail at run time.

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:

ArrayList list<Integer> = new ArrayList<Integer>();


list.add(0, new Integer(42));
int total = list.get(0)).intValue();
No casts are needed and in this example trying to add a String object to an Integer typed
collection would be caught at compile time.

Conclusion:

Generic types therefore enable an API designer to provide common


functionality that can be used with multiple data types and which also can be checked for type
safety at compile time.

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.

The autoboxing and auto-unboxing of Java primitives produces code that is


more concise and easier to follow. In the next example an int is being stored and then
retrieved from an ArrayList.

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:

This annotation turns off compiler warnings at a class or method level.


Sometimes you know better than the compiler that your code must use a deprecated method,
or perform some action that cannot be statically determined to be typesafe but in fact is:

@SuppressWarnings("deprecation")
public static void selfDestruct()
{
Thread.currentThread().stop();
}

Deprecated:

Unfortunately, Deprecated is a little less useful. It's meant to replace the


@deprecated javadoc tag, but since it doesn't have any fields, there's no way to suggest to the
user of a deprecated class or method

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.

Scanner scanner=new Scanner(System.in);

Scanner sc = new Scanner(new File("FileName"));

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:

String input = "1 fish 2 fish red fish blue fish";


Scanner s = new Scanner(input).useDelimiter("\\s*fish\\s*");
System.out.println(s.nextInt());
System.out.println(s.nextInt());
System.out.println(s.next());
System.out.println(s.next());
s.close();

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

General Structure of a Class:

[Access-specifier] [Modifier] class <class-name>


[extends <base-class>
implements <interface1>, <interface2>]
{
Static { //static block
...................
.
}

// Variables, (inner)classes declaration

// constructors

// Method definitions

// Abstract method declarations (if any)

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:

[<Access-specifier>] [<Modifier>] <type-name> <identifier> [= value];

General Rules to construct a well-defined class:

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

2. class ------- (System. class)

3. class. class ---- object of type class


5. Abstract Class
Contents :
) Definition:
) Structure of Abstract Class
) How to make Class as Abstract
) Rules of Abstract Class
) Illegal combinations of Abstract and Keywords
) Legal combinations of Abstract and Keywords.
) Example of Abstract Class.

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

Structure or Syntax of Abstract Class:

Public abstract class <classname> extends <classname>


Implements

{
<Access modifier> {static} <data type> <variable names.>

Static {
-----------------
} Comment [v1]: Abstract Class allows
Static Block

<constructor>{
-----------------
} Comment [v2]: We can write
Constructor

<Access modifier> {static} <return type> <methodname>(<argument list>){


-----------------
} Comment [v3]: In Abstract Class we
can write static and Non Static Methods

public abstract <return type> <methodname>(<argument list>);


protected Comment [v4]: Abstract Method
means only declaration no body

..
..
}

How to make class as Abstract:

We can make class as Abstract in 2 ways

By placing abstract keyword before a class

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
}

Rules of Abstract Class:

In Abstract Class, we write only prototype declaration of Abstract Method,


we cannot write body of the function
Once we declare abstract method in Abstract class then that method must be
override in the derived class.
We cannot create instance directly to the Abstract class, we can create
reference through the derived class

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.

Illegal Combinations of Abstract with Keywords:

1 We cannot write Abstract and Final to the Methods and Classes.


1 We cannot write Abstract and Private to the Methods and Classes.
1 We cannot write Abstract and Synchronized to the Methods and Classes.
1 We cannot write Abstract and Static to the Methods and Classes.
Legal Combination of Abstract with Keywords:

9 We can write Abstract and Public to the Methods and Classes.


9 We can write Abstract and Protected to the Methods.

6. Interface

Actual structures of Class, Abstract Class and Interface :

Class Abstract class Interface

Member variables Member variables Member variables


(static & non-static) (static & non-static) (by default final static)
Static block Static block Abstract methods
Constructor Constructor
Methods Methods
(static & non-static) (static & non-static)
Abstract methods

Defining an interface:

interface keyword is used to define an interface.

E.g., interface InterfaceDemo {


}

Points regarding interfaces:

Interface is a collection of constants and abstract methods.


Interface is not an active thing, it is just like a prototype that we should implement
according to our requirement.
It is a contract between class and interface that the class, which implements the
interface, should implement all the methods of that interface.
By default all the variables of an interface are final static.
Abstract method means having no method body / implementation.

Rules to be followed while dealing with interfaces:

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;

public void get();


}

class Demo implements InterfaceDemo {


public Demo (){
System.out.println("Demo");
System.out.println (InterfaceDemo.count);
}
public void get() {
System.out.println("get()");
}

Public void set(){


System.out.println (Demo. set());
}

public static void main(String... args){


InterfaceDemo demo = new Demo();
demo.get ();
demo.set(); //cerror: cannot find symbol, method set()
System.out.println (demo.count);
}
}//end of InterfaceDemo.
--- Hidden feature of interface:
How can we use the methods of interface, like Iterator, which do not have method body
and which are not implemented manually in our program??? The answer for this question is
briefly explained using below sample code.

Sample code 2:
import java.util.*;

public class ALDemo{


public static void main(String args) {
ArrayList<String> al = new ArrayList<String>();
al.add("one");
al.add("two");
al.add("three");
Iterator itr = al.iterator();
While(itr.hasNext ()) //calling hasNext() method of iterator interface.
{
System.out.println(itr.next()); //calling next() method of iterator
//interface.
}
}
}//end of ALDemo
Output:
one
two
three

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.

Writing classes in interface:

We can write inner classes inside interfaces


A sample code is as shown below.

Sample code3:
public interface ItfInnerDemo{
InnerDemo id = new InnerDemo();
public void printId(InnerDemo id);
class InnerDemo{
InnerDemo(){
System.out.println("1 Object Create");
}
}
}

7. Ways of Creating Instances/ Objects for a Class


There are 6 ways to create an instance for the Class. They are

Using New Operator


Using class.forName()
Using clone()
Using this object
Using class
Using Serializable

Using New Operator

<Classname> <objectname>=new <classname> (<argument list>);


For eg:-
class Sample {
Void get () {
System.out.println (In get () method);
}
}

Public class Demo {


Public static void main (String args []) {
Sample s=new Sample (); Comment [v7]: Creating a instance
using new keyword
s.get ();
}

Using class.forName ()

Class c = Class.forName (Employee);


Employee obj = c.newInstance (); Comment [v8]: By using
class.forname we can create the new
instance
Using Clone()

Creating exact copy of an object.


Employee e2 = e1.clone (); Comment [v9]: Using Clone method

we can create instance for the class


Using this object

Demo demo=Demo. this;


// this object is a hidden member variable in each class.

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() {
return DefaultStatic.this; Comment [v10]: Here we are creating
the instance for the class
}
Using class

DefaultStaic demo=DefaultStaic.class.newInstance ();

Using Serializable

By using Serializable also we can create an instance for the class

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.

4. We can overload main method also.

5. We can overload both methods and constructors.

6. We can use overloaded methods in interfaces also.

7. We can have overloaded methods in abstract classes also.

1) Example for overloading a method.

public class Overload {


public Overload(Object... obj){
for(Object ob:obj){
System.out.println(ob);
}
}

static {
main("bajrang");
main("ash","jai");
main("ash","jai","sam");
}

public final static void main(String... args){

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.

2) Now check the below code

public interface interfacedemo {


int a=10;
void getMethod();
void getMethod(String name);
}

So we can say that we can have the overloaded methods in interfaces also.

3) Check the below code

public interface interfacedemo {


int a=10;
void getMethod(int a,int b);
void getMethod();

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.

4) Example which is not overloading.

public interface interfacedemo {


int a=10;
void getMethod(int a,int b);
int getMethod(int a,int b);

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.

Note : Method Signature consist of method name n parameters


along with it order of parameters, it doesnt include modifiers,
return type, and exceptions
8. Method Overriding
1. Sub-class overrides the methods of the base class.
2. The method signature should be same in both sub-class as well as base-class.
3. The return type of methods should be same.
4. The parameters of the method should be same, along with their ordering.
5. Final method cant be overridden.
6. Private method cant be overridden. Since when u writing a private method in base
class, it is not visible to outside the class. When u write a private method with same
signature in sub-class, it is local to sub-class, not overriding a base-class method.
7. Protected methods can be overridden.
8. public static void main(String args[ ]) method can be overridden.
9. You can change the access specifier in sub-class, but the scope of method should not
be narrowed. Like if method in base-class has protected access specifier, then sub-
class cant have private as its access specifier for the overridden method. But it can
have protected, as well as public as its access specifier.
10. Static method can be overridden, but the precaution should be taken care that both
base-class as well as sub-class have static keyword in overridden method. If only one
of them is having static, it will throw compile time error.
11. Regarding Accessing the methods:
a. If You are creating a sub-class object like BaseClass bc=new SubClass();.
Then You can access the methods of base-class only not the methods of the
child class.
b. But If You are creating a sub-class object like SubClass sc=new SubClass();.
Then You can access the methods of base-class as well as the methods of the
child class.
c. This is not allowed
Subclass sc = new BaseClass();
12. To avoid the overriding, do the following
a. Add final keyword for method.
b. Add private keyword with the method. By doing so, the method will not be
visible outside the class.

Rules to Avoid the Inheritance:


1. Add the final keyword with the class. Classes with the final keyword can not be
extended.
2. Provide a private constructor for the class. This also prevents the class from being
overridden.
Important Points to note:
1. Constructors cant be overridden. Since when u write a constructor in sub-class, it will
treat as method. It will give compile time error saying missing return type.

2. Final, Synchronized can not be given with constructor.

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.

Referring to a package member by its qualified name.


Import the package member.
Import the members entire package.

Referring to a package member by its qualified name:


If you are trying to use a member from a different package and that package has not
been imported, you must use the member's fully qualified name, which includes the package
name.

example: Rectangle class from the graphics package


created in the previous section.

graphics.Rectangle rec=new graphics.Rectangle();

Import the package member.

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;

Import the members entire package.

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.

Final Class Demo{


.
..
}

Class FinalDemo extends Demo{ //throws an error




}

2. The value of a final variable can not be altered.

final int count = 100; //declaring a final variable


or final static int count = 100;

count = count+10; // is not allowed.

It is a replacement for the keyword const in C++/C.

3. A method , declared as final can not be overridden in the subsequent subclasses.

Public class Demo{

Final Public void get(){

}
}

Public class FinalDemo extends Demo{

Public void get(){ // is not allowed.


}
}

4. Constructors can not be declared as final.

5. static block can not be declared as final.

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.

Final Demo demo = new Demo();


Demo demo1 = new Demo();

demo = dem01; // is not allowed.


demo.get();
Eg: final ArrayList al = new ArrayList();

The methods addElement(), removeElement() can equally be applied even if


its final object, but any attempt to change the reference of al is an error.

al = new ArrayList(); // is not valid.

11. super keyword


In java we use super in two ways

super ---------- object


super () ---------- constructor

About super object


It refers to super class object
It is used to call the member variables and methods of the super class

Rules to be followed while using super object


It cannot referred the static block, static variables and static methods
It can refer the nonstatic variables and nonstatic methods
It can be used inside the Constructor

About super () Constructor


It is used to call the super class constructor
By using this we can call more than one constructor having different parameters

Rules to be followed while using super ()


By using this we can call super class constructor but it must be in first line
We cant use super() inside the static block and static methods
It cannot refer the static variables
It doesnt allow inside non-static methods
This() and super() , in these two we can use only one at a time in side the constructor

Clear idea about super keyword inside a class


Class structure super Object super() Constructor
Static block We cant use We cant use

Static Variable We can use but we cant We cant use


refer
Nonstatic variable We can use We cant use

Constructor We can use We can use

Non static Methods We can use We cant use

Static methods We cant use We cant use


12. this keyword

In java we use this in three ways

this ---------- object


this () ----------constructor
this ------------member variable

About this 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

About this () Constructor:-


It is used for calling the constructor of same class.
e.g.:-
Class A{
A(){
}
A(int a) {
A();
}
Rules to be followed while using this ():
It is valid only inside the Constructors
It is used to call the constructors of same class, and must be first line.
It cannot be used inside static context or in any other method, other than Constructor.

Specified block this Object this() Constructor


Static context Not valid Not valid
Variable valid Not valid
Constructor valid valid
Non static Methods valid Not valid
Static methods Not valid Not valid

Eg:- just have a look on this program

public class ThisDemo{


private int count = 100;
private int ncount = this.count;

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);
}

public ThisDemo(String s){


//System.out.println(s);
// c-error :call to this must be first statement in constructor
this();
}

public static void main(String... a){


ThisDemo demo = new ThisDemo("bajrang");

//non-static variable this cannot be referenced from a static context


//int count = this.count;
demo.get();
}
public void get(){
int count = this.ncount;

System.out.println("Inside count "+count);


}

}
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");
}

public void get(){

}
}

About this member variable:-


this member variable is used to create an instance for the class
Demo demo=Demo. this;
// this object is a hidden member variable in each class.

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

) Rules when classes declared as static

) Rules when variables declared as static

) Rules when static members are overridden

) Rules for static block

) Rules when methods declared as static

) Rules when static members are used in abstract class

) Rules when static members are used in interface

) Static with transient


) Importing only static members of a class

) Example program

) Overview

Introduction:

To make class variables and methods static they should be preceeded with the keyword
static.

Variables declared as 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.

Methods declared as static :

Static methods are also shared by all the objects.


They can only access static data.
They can call only other static methods.
They cannot refer to this or super.
They can be called using the class name outside the class.
Final can be used along with static members of a class.
Static Block :

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.

Classes declared as static:

Only inner classes can be declared as static.

Overriding:

Static methods can be overridden.


In the super class if a method is declared as static then in child class that method
should have the modifier as static while overriding.

Import static members of a class :

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;

public class StaticDemo


{
public static void main(String args[])
{
out.println(static import);
out.println(abs(37.89));
}
}

Rules for static members in abstract class:

We cannot have abstract and static together.

Rules for static members in interface:

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

Static Member Variables YES


Non-Static Member Variables YES
Static block YES
Constructor NO
Static Methods YES
Non-static Methods YES
Abstract Methods NO

Interface
Does Applied

Interface NO

Member variables YES


Method Declarations NO
14. Multithreading
What is a Thread?

A thread is a path of execution through a program.

Thread is part of a program that runs independently or along with other threads to
accomplish a task.

Its a sequence of code that is executing.

Why to Use Threads?

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.

A thread allows us to do this.

Its light in weight.

The performance benefit of allowing multiple threads to run at the same time is realized
mainly on multi-processing systems.

Different threads run on different processors, so they can run simultaneously.


What is Multithreading?

Multithreading is multitasking within a single program. It allows multiple streams of


execution to take place concurrently within the same program, each stream processing
a different transaction.

Single threaded programs have one path of execution, and multi-threaded programs
have two or more paths of execution.

Types of Threads in Java:

Java Provides Two types of threads.


Daemon Threads: These are threads that exist for the purpose of providing a
certain service. These threads are run (executed) by JVM itself. They support
the user threads.
User Threads: These are threads that are written by the programmer to
perform specific task.

How JVM handles these threads:

1. When JVM starts it invokes Daemon threads.


2. Then it invokes User threads.
3. When the last User thread in executed completely the JVM shutdowns (stops) execution
of Daemon threads.

How to Use Multithread in Java:

Using Multithread in Java can be achieved by either of the following methods.


1. Implementing Runnable Interface.
2. Extending Thread class.

1. Multithread by Implementing Runnable Interface

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 creating a class that implements Runnable, we have to instantiate an object of


class Thread. Thread td = new Thread(Runnable threadObject).

Here threadObject is instance of the class that implements Runnable ineterface.

After the new thread is created, we need to call its start () method that is declared in
Thread class.

In essence, start () executes a call to run () method.


How is that start () of Thread class executes run () of our 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.

For example we can imagine that Thread class is defined as follows:


public class Thread{
Object obj;

public Thread(Object obj){


this.obj = obj;
}

public void start(){


obj.run();
}
}

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.

Example program is as follows


public class ThreadDemo implements Runnable{
public void run(){
System.out.println("Inside the run()");
}

public static void main(String... args){


Thread th = new Thread(new ThreadDemo()) ;
th.start();
}
}

2. Multithread by Extending Thread class

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()");
}

public static void main(String... args){


ThreadDemo th = new ThreadDemo();
th.start();
}
}

When to Use What:

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:

public synchronized void set(){


//do something here..
}

Rules of Synchronized Keyword:

9 synchronized keyword can be only used with the methods.


9 synchronized keyword can not be used with class, interface, and abstract class.
9 synchronized keyword can not be used with the methods declared inside an
interface.
9 synchronized can not be used with abstract keyword.

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.

This is the general form of the synchronized statement:

Syntax:
synchronized(object) {
// statements to be synchronized
}

Here, object is a reference to the object being synchronized. A synchronized block


ensures that a call to a method that is a member of object occurs only after the
current thread has successfully entered objects monitor.

Example:

.
static ArrayList<String> al = new ArrayList<String>();

synchronized(al){
al.add("Ashish");
al.add("Scam");
al.add("jaison");
}
.

Rules of Synchronized Block:

9 synchronized block can be used inside static block.


9 synchronized block can be written inside the constructor.

9 synchronized block can also be written inside the methods(static as well as not

static methods).

9 synchronized block can not be written inside an interface.

9 synchronized block can be written inside the abstract class.

When to use what:

9 It is better to use to synchronized block if there is no need to make the


complete method to be synchronized.
9 synchronized block is handy when dealing with classes which are not thread-
safe and we want to synchronized the access to the object of that class.
Source Code:

Example:

import java.util.*;
public class SyncDemo{
static int scount = 100;
int count = 100;

static ArrayList<String> al = new ArrayList<String>();

static{
}

SyncDemo(){
}

public static void main(String... args){


synchronized(al){
al.add("Ashish");
al.add("Scam");
al.add("jaison");
}
}

public synchronized void set(){


}
}

interface SyncDemoInf{
public void set();
}
abstract class SyncDemoAbs{
public synchronized void set(){
}

//abstract synchronized void get();


// illegal combination of abstract and synchronized
}

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

Serialization is the process of writing the state of an object to a byte


stream. This is useful when you want to save the state of your program to a persistent
storage area, such as a file, database, etc. At a later time, you may restore these
objects by using the process of deserialization. This is one way we can create objects.
Variables that are declared as transient are not saved by the serialization facilities.

Serializable Interface: A Marker Interface

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.

Useful classes in Serialization:

1. ObjectOutputStream:

ObjectOutputStream is responsible for writing objects to a stream. This class


extends ObjectStream. An ObjectOutputStream writes primitive data types and graphs
of Java objects to an OutputStream.

Constructor of ObjectOutputStream:

ObjectOutputStream(OutputStream outStream) throws IOException

The method writeObject is used to write an object to the stream.

Syntax of writeObject:

public void writeObject(Object obj)


2. ObjectInputStream :

ObjectInputStream is responsible for reading objects from a stream. An


ObjectInputStream deserializes primitive data and objects previously written using an
ObjectOutputStream.

Constructor of ObjectInputStream:

ObjectInputStream(InputStream inStream) throws IOException,


StreamCorruptedException

The method readObject is used to read an object from the stream.

Syntax of readObject:

public Object readObject()

Example:

//Writing an object of class MyClass to File


..
MyClass object1 = new MyClass("Hello", -7, 2.7e10);

System.out.println("object1: " + object1);

FileOutputStream fos = new FileOutputStream("serial");

ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(object1);
.

//Reading the object of class MyClass from File


MyClass object2;

FileInputStream fis = new FileInputStream("serial");

ObjectInputStream ois = new ObjectInputStream(fis);

object2 = (MyClass) ois.readObject();


17. Exception Handling in Java

Contents :

) Definitions.
) Types of Exceptions.
) Different ways of writing try, catch and finally blocks.
) Rules.
) Flow of trycatch.finally blocks.
) Throw and Throws.

Definition:

An exception is an event, which occurs during the execution of a program, that


disrupts the normal flow of the program's instructions. A program can catch exceptions by
using a combination of the try, catch, and finally blocks.

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.

Types of Exceptions: There are 2 types of Exceptions

Checked Exception: Checked exceptions are subject to the Catch or


Specify Requirement. All exceptions are checked exceptions, except for
those indicated by Error, Runtime Exception, and their subclasses. Here
we write the code in trycatch block.

Unchecked Exception: Here there is no need to write the code in


trycatch block. If there is an exception then that exception will
automatically caught and display a corresponding error message
Different ways of writing try, catch and finally blocks

1) try {

} catch (ExceptionType name) {

2) try {

} finally {

3) try{

}catch(ExceptionType name){

} catch (ExceptionType name) {

4) try {

} catch (ExceptionType name) {


---------------
---------------
try{

}catch(Exception e){

}
}
5) try {

} finally (ExceptionType name) {


---------------
---------------
try{

}catch(Exception e){
}
}
6) try {
---------------
---------------
try{

}catch(Exception e){

}
} catch (ExceptionType name) {
---------------
---------------
try{

}catch(Exception e){

}
}
Rules:

We cannot write try block in Variable Declaration


We can write try block in
Static block
Constructor
Static methods
Non-static methods
We can declare variables in try block, but the scope of that variable is only with in
that block.
Finally block will be executed at the end.

Throw and throws Keywords:

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

18. Bean Implementation


How To Implement Bean with only two methods, Whether There May be any no of
Properties.

JavaBean is a Java class which is written according to well-known rules.

JavaBean class has empty constructor and properties which are accessed by get/set (getters
and setters) methods.

Getters and setters have to be named like get[PropertyName]/set[PropertyName].

Simple Example:

public class MyFirstJavaBean implements Serializable {


private int id;
private String name;
public MyFirstJavaBean () {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Note:

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;

public void set(String key, Object value) throws Exception{


this.getClass().getField(key).set(this,value);
}

public Object get(String key) throws Exception{


return this.getClass().getField(key).get(this);
}
public static void main(String... args) throws Exception{
Demo demo = new Demo();
demo.set("no",100);
demo.set("name","bajrang");
demo.set("address","ammerpet");
System.out.println(demo.get("no"));
System.out.println(demo.get("name"));
}
}

Вам также может понравиться