Ashish Mishra
Inheritance
Data Abstraction
Encapsulation
Polymorphism
E
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.
2. Features Of java
Following are the features of java.
1)
2)
3)
4)
5)
6)
7)
8)
9)
Simple
Robust
Secure
Distributed
Multi Threaded
Portable
Architecture neutral
Object Oriented
Interpreted
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.
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.
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 Objectbased 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:
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.
Static Block
Member Declaration
Method Definitions
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.
3.
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:
extends
Implements
<classname>
{
<Access modifier> {static} <data type> <variable names.>
Static {
----------------}
<constructor>{
----------------}
<Access modifier> {static} <return type> <methodname>(<argument list>){
----------------}
public
protected
..
..
}
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();
}
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:
6. Interface
Actual structures of Class, Abstract Class and Interface
Abstract class
Class
Member variables
Member variables
Static block
Static block
Constructor
Constructor
Methods
Methods
(static & non-static)
Abstract methods
Defining an interface:
interface keyword is used to define an interface.
E.g.,
Interface
interface InterfaceDemo {
Member variables
(by default final static)
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
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
We can get the reference of an interface by using the object of the class which
--- 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);
}
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
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:
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 ()
Class c = Class.forName (Employee);
Employee obj = c.newInstance ();
Using Clone()
Creating exact copy of an object.
Employee e2 = e1.clone ();
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.
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.
5.
6.
7.
}
}
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.
8. Method Overriding
1.
2.
3.
4.
The parameters of the method should be same, along with their ordering.
5.
6.
7.
8.
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 subclass 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.
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.
b.
Add private keyword with the method. By doing so, the method will not be
visible outside the class.
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.
2.
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.
Note: If we have multiple classes and interfaces only one can be public,and it must have
the same name as source file.
2.
//throws an error
// is not allowed.
//
is not allowed.
4.
5.
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;
demo.get();
// is not allowed.
Eg:
// is not valid.
super
---------- object
super () ---------- constructor
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
super Object
super() Constructor
Static block
We cant use
We cant use
Static Variable
We cant use
refer
Nonstatic variable
We can use
We cant use
Constructor
We can use
We can use
We can use
We cant use
Static methods
We cant use
We cant use
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();
}
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
Not valid
Static methods
Not valid
Not valid
Eg:-
valid
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() {
return DefaultStatic.this;
}
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.
They can be called using the class name outside the class.
Static Block :
Gets executed only once when the class is loaded into the memory.
Static block can be defined in class , abstract class but not in interface.
Overriding:
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.
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));
}
}
We cannot have
We cant use static methods in interface because all the methods of interface are
abstract.
Transient and static when used together , the transient is ignored and the object can be
saved or serialized.
Overview:
Class:
Does Applies
Class
NO
YES
YES
static block
YES
Constructor
NO
Static Methods
YES
Non-static Methods
YES
Abstract Class:
Does Applies
Class
NO
YES
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?
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.
What is Multithreading?
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.
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.
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..
}
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");
}
.
synchronized block can also be written inside the methods(static as well as not
static methods).
9 synchronized block is handy when dealing with classes which are not threadsafe 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");
}
}
interface SyncDemoInf{
public void set();
}
Class:
Synchronized
Keyword
Synchronize()
Statement
Class
X
X
X
X
Static Methods
X
X
Non-static Methods
Abstract Class:
Synchronized
Keyword
Synchronize()
Statement
Class
X
X
X
X
X
Interface
Does Applied
Interface
Member variables
X
X
Method Declarations
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.
2. ObjectInputStream
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.
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
try {
} catch (ExceptionType name) {
}
2)
try {
} finally {
}
3)
try{
}catch(ExceptionType name){
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
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"));
}
}