Sie sind auf Seite 1von 69

By

Ankur Dumka

Simple
Object-Oriented
Platform independent
Secured
Robust
Architecture neutral
Portable
Dynamic
Interpreted
High Performance
Multithreaded
Distributed

SIMPLE
Java language is simple because:
a) syntax is based on C++
b) removed many confusing and/or rarely-used
features e.g., explicit pointers, operator
overloading etc
c) No need to remove unreferenced objects
because there is Automatic Garbage Collection
in java.
means we organize our software as a
combination of different types of objects that
incorporates both data and behaviour
Basic concept of OOPS are :
a) Object
b) Class
c) Inheritance
d) Polymorphism
e) Abstraction
f) Encapsulation

A platform is the hardware or software environment in
which a program runs. There are two types of
platforms software-based and hardware-based. Java
provides software-based platform.
Java is a software-based platform that runs on top of
other hardware-based platforms. it has two
components:
a) Runtime Environment
b) API(Application Programming Interface)
Java code can be run on multiple platforms
e.g.Windows,Linux,Sun Solaris,Mac/OS etc. Java code
is compiled by the compiler and converted into
bytecode.This bytecode is a platform independent code
because it can be run on multiple platforms i.e. Write
Once and Run Anywhere(WORA).

Java compiler refers to a program which translates
Java language source code into the Java Virtual
Machine (JVM) bytecodes. The
term Java interpreter refers to a program which
implements the JVM specification and actually
executes the bytecodes (and thereby running
your program).
A Java compiler compiles source files (.java) to
bytecode files (.class) with the 'javac' command
A java interpreter is usually referred to as the
Java Virtual Machine (or JVM). It reads and
executes the bytecodes in the .class files. with the
'java' command



Java is secured because:
a) No explicit pointer
b) Programs run inside virtual machine sandbox


Classloader- adds security by separating the package for the classes of the local file
system from those that are imported from network sources.
Bytecode Verifier- checks the code fragments for illegal code that can violate access
right to objects.
Security Manager- determines what resources a class can access such as reading and
writing to the local disk.
Some security can also be provided by application developer through
SSL,JAAS,cryptography etc.

Robust simply means strong. Java uses strong
memory management. There are lack of
pointers that avoids security problem. There is
automatic garbage collection in java. There is
exception handling and type checking
mechanism in java. All these points makes java
robust.
Architecture Neutral
There is no implementation dependent features e.g.
size of primitive types is set.
Portable
java bytecode can be carried to any platform
High- Performance
Java is faster than traditional interpretation since byte
code is "close" to native code still somewhat slower
than a compiled language
Distributed
We can create distributed applications in java. RMI
and EJB are used for creating distributed applications.
We may access files by calling the methods from any
machine on the internet.
A thread is like a separate program, executing
concurrently. We can write Java programs that
deal with many tasks at once by defining
multiple threads. The main advantage of multi-
threading is that it shares the same memory.
Threads are important for multi-media, Web
applications etc.
First install JDK
Set path for the jdk/bin directory
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
This file will have name simple.java with the same
name as that of class
For compile javac simple.java
For run java simple

class keyword is used to declare a class in java.
public keyword is an access modifier which represents
visibility, it means it is visible to all.
static is a keyword, if we declare any method as static,
it is known as static method. The core advantage of
static method is that there is no need to create object to
invoke the static method. The main method is executed
by the JVM, so it doesn't require to create object to
invoke the main method. So it saves memory.
void is the return type of the method, it means it
doesn't return any value.
main represents startup of the program.
String[] args is used for command line argument.
System.out.println() is used print statement.
Public static void main(String args[])
Static public void main( String args[])
Public static void main(String[] args)
At compile time, java file is compiled by Java
Compiler (It does not interact with OS) and
converts the java code into bytecode.

Class loader is the subsystem of JVM that is used
to load class files
Byte code verifier checks the code fragments for
illegal code that can violate access right to objects
Interpretor read bytecode stream then execute the
instructions
If you are saving the java source file inside the
jdk/bin directory, path is not required to be set
because all the tools will be available in the
current directory.
But If you are having your java file outside the
jdk/bin folder, it is necessary to set path of
JDK.There are 2 ways to set java path:

a) Temporary
b) Permanent

Open command prompt
copy the path of jdk/bin directory
write in command prompt: set
path=copied_path
Example : set path= C:\Program
files\Java\jdk1.6.0_23\bin
Javac simple.java
Java simple

Go to MyComputer properties -> advanced tab
-> environment variables -> new tab of user
variable -> write path in variable name -> write
path of bin folder in variable value -> ok -> ok -
> ok
Setting the path in Linux OS is same as setting
the path in the Windows OS. But here we use
export tool rather than set.
export PATH=$PATH:/home/jdk1.6.01/bin/
It is a specification where working of Java Virtual
Machine is specified. Its implementation is known as
JRE (Java Runtime Environment)
Whenever you write java command on the command
prompt to run the java class, and instance of JVM is
created.
JVM, JRE and JDK are platform dependent because
configuration of each OS differs. But, Java is platform
independent.
The JVM performs following main tasks:Loads code
a) Verifies code
b) executes code
c) Provides runtime environment

It is used to provide runtime environment
It is the implementation of JVM
It physically exists.It contains set of libraries +
other files that JVM uses at runtime

It physically exists.It contains JRE +
development tools.

There are three types of variables in java
a) local variable
b) instance variable
c) static variable

Local Variable
A variable that is declared inside the method is called
local variable
Instance Variable
A variable that is declared inside the class but outside
the method is called instance variable . It is not
declared as static. A variable that is created inside the
class but outside the method, is known as instance
variable.Instance variable doesn't get memory at
compile time.It gets memory at runtime when
object(instance) is created.That is why, it is known as
instance variable.
Static Variable
A variable that is declared as static is called static
variable. It cannot be local.

class A
{ int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
};

When a class member is preceded by public, then that member
may be accessed by code outside the class in which it is declared.
In this case, main ( ) must be declared as public.
Main method is static because object is not required to call static
method if it were non-static method, jvm create object first then
call main() method that will lead the problem of extra memory
allocation. The keyword static allows main ( ) to be called without
having to instantiate a particular instance of the class.This is
necessary since main ( ) is called by the Java interpreter before any
objects are made.
void simply tells the compiler that main ( ) does not return a
value.
Main ( ) is the method
String args [ ] declares a parameter named args, which is an array
of instances of the class String. args receives any command-line
arguments present when the program is executed.

System is a predefined class that provides access to the
system which is introduced inside java
lang.package. System class is a default class.
Out is the static attribute which is calling print method. Out
is a static attribute inside a system class. Out is a data type
of print stream class that is connected to the console. Out is a
static attribute. Method System.out.println displays its
argument in the command window followed by
a new-line character to position the output cursor to the
beginning of the next line.
Println ( ) displays the string which is passed to it
System.out.printf method (f means "formatted") displays
formatted data inside a print stream class there is
Println method & printf method is available
In java, there are two types of data types
a) primitive data types
b) non-primitive data types


Data Type Default Value Default size
boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Char uses 2 bytes because java uses unicode system rather than ASCII code system.
\u0000 is the lowest range of unicode system. (universal international standard character
encoding) and \uFFFF is the highest range
Simula is considered as the first object-oriented
programming language.
The programming language where everything
is represented as an object, is known as truly
object-oriented programming language.
Smalltalk is considered as the first truly object-
oriented programming language.
Object
Class (Collection of objects)
Inheritance (one object acquires all the properties and behaviours
of parent object)
Polymorphism(one task is performed by different ways)
Abstraction (Hiding internal details and showing functionality)
Encapsulation (Hiding internal details and showing
functionality)

OOPs makes development and maintenance
easier where as in Procedure-oriented
programming language it is not easy to
manage if code grows as project size grows.
OOPs provides data hiding

Object based programming language follows
all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object
based programming languages.
There are many ways to create an object in java.
They are:
a) By new keyword
b) By newInstance() method
c) By clone() method
d) By factory method etc.

Anonymous simply means nameless
An object that have no reference is known as
anonymous object
It is used when you have to use an object only
once

class Calculation
{
void fact(int n)
{
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[])
{
new Calculation().fact(5);//calling method with annonymous object
}
}


For class oil and gas creating 2 objects
Oilandgas o1=new oilandgas() , o2=new
oilandgas();
The static can be:
a) variable (also known as class variable)
b) method (also known as class method)
c) Block
d) nested class

If you declare any variable as static, it is known
static variable.
a) The static variable can be used to refer the
common property of all objects (that is not
unique for each object)
b) The static variable gets memory only once in
class area at the time of class loading
c) Advantage is It makes your program memory
efficient (i.e it saves memory)
If you apply static keyword with any method, it is
known as static method
A static method belongs to the class rather than
object of a class.
A static method can be invoked without the need
for creating an instance of a class.
static method can access static data member and
can change the value of it.
two main restrictions for the static method :
a) The static method can not use non static data
member or call non-static method directly.
b) this and super cannot be used in static context.


Is used to initialize the static data member.
It is executed before main method at the time of classloading.
class A{
Static
{System.out.println("static block is invoked");}
public static void main(String args[])
{
System.out.println("Hello main");
}
}
Output:static block is invoked Hello main
We can execute main function without main() method by using static
block
class A{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}


this keyword is a reference variable that refers to the
current object.
this keyword can be used to refer current class instance
variable.
this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method
(implicitly)
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this keyword can also be used to return the current class
instance
The this() constructor call should be used to reuse the
constructor in the constructor. It maintains the chain
between the constructors i.e. it is used for constructor
chaining.

making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is
called a superclass. The new class is called a subclass.
there can be three types of inheritance: single,
multilevel and hierarchical.
Multiple and Hybrid is supported through interface
only


Aggregation represents HAS-A relationship. If
a class have an entity reference, it is known as
Aggregation.
We use aggregation for code reusability
Inheritance should be used only if the
relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise,
aggregation is the best choice.

class Operation{
int square(int n){
return n*n;
}
}

class Circle{
Operation op;//aggregation
double pi=3.14;

double area(int radius){
op=new Operation();
int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).
return pi*rsquare;
}



public static void main(String args[]){
Circle c=new Circle();
double result=c.area(5);
System.out.println(result);
}
}

If subclass (child class) has the same method as
declared in the parent class, it is known as method
overriding.
Advantages:
a) Method Overriding is used to provide specific
implementation of a method that is already provided
by its super class.
b) Method Overriding is used for Runtime Polymorphism
For overriding methods should have:
Same name and arguments as that of parent class and
should possess is-a relationship (inheritance)
Constraints with overriding methods:
static method cannot be overridden (include main method)



class Bank{
int getRateOfInterest(){return 0;}
}

class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}

class Test{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
SBI Rate of Interest: 8 ICICI Rate of Interest: 7 AXIS Rate of Interest: 9

The super is a reference variable that is used to
refer immediate parent class object. Whenever you
create the instance of subclass, an instance of
parent class is created implicitly i.e. referred by
super reference variable.
super is used to refer immediate parent class
instance variable and method. super() is used to
invoke immediate parent class constructor.
we use super keyword to distinguish between
parent class instance variable and current class
instance variable
super() is added in each class constructor
automatically by compiler.


class Person{
void message(){System.out.println("welcome");}
}

class Student extends Person{
void message(){System.out.println("welcome to java");}

void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}

public static void main(String args[]){
Student s=new Student();
s.display();
}
}
output: welcome to java
welcome
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}

class Bike extends Vehicle{
Bike(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike b=new Bike();

}
}
Output: vehicle is created
Bike is created
class Vehicle{
int speed=50;
}

class Bike extends Vehicle{
int speed=100;

void display(){
System.out.println(super.speed);//will print speed of Vehicle now
}
public static void main(String args[]){
Bike b=new Bike();
b.display();

}
}
Output :50
In case there is no method in subclass as parent, there is no need to use
super
class Person{
void message(){System.out.println("welcome");}
}

class Student extends Person{

void display(){
message();//will invoke parent class message() method
}

public static void main(String args[]){
Student s=new Student();
s.display();
}
}
Output :Welcome

The final keyword in java is used to restrict the
user. The final keyword can be used in many
context.
a) Variable
b) Method
c) class
Final variable value cannot be changed. They are
constants. Try to change value of final variable will
give compile time error. Final variable that cannot
be initialized during declaration is known as blank
final variable. Blank final variable can be initialize
in constructor only.
Final method cannot be overriden. Doing so will
give compile time error. But they can be inherited
Final class cannot be extended or cannot be
inherited.
Constructor can never be final as constructor is
never inherited
A class that is declared with abstract keyword, is
known as abstract class.
Abstraction is a process of hiding the
implementation details and showing only
functionality to the user
Abstraction lets you focus on what the object does
instead of how it does it.
There are two ways to achieve abstraction in java
Abstract class
Interface

A class that is declared as abstract is known
as abstract class. It needs to be extended and
its method implemented. It cannot be
instantiated.
Syntax - abstract class <class_name>{}
A method that is declared as abstract and does
not have implementation is known as abstract
method.
Syntax-
abstract return_type <method_name>();//no bra
ces{}
abstract class Bike{
abstract void run();
}

class Honda extends Bike{
void run(){System.out.println("running safely..");}

public static void main(String args[]){
Bike obj = new Honda();
obj.run();
}
}

Any classes that derive from the Base class
basically has 2 options:
1. The derived class must provide a
definition for the Abstract method
OR
2. The derived class must be declared abstract
itself.
any non abstract class is called a concrete class.
It can only be used as a superclass for other
classes
Abstract classes cannot be instantiated, but they can be
subclassed.
An abstract method is a method that is declared without an
implementation
If a class includes abstract methods, then the class itself must be
declared abstract
When an abstract class is subclassed, the subclass usually provides
implementations for all of the abstract methods in its parent class
Methods in an interface that are not declared as default or static
are implicitly abstract, so the abstract modifier is not used with
interface methods. (It can be used, but it is unnecessary.) .With
interfaces, all fields are automatically public, static, and final, and
all methods that you declare or define (as default methods) are
public.
you can extend only one class, whether or not it is abstract,
whereas you can implement any number of interfaces.
An interface is a blueprint of a class. It has
static constants and abstract methods.
The interface is a mechanism to achieve fully
abstraction in java. There can be only abstract
methods in the interface. It is used to achieve
fully abstraction and multiple inheritance in
Java.
Interface also represents IS-A relationship.
It cannot be instantiated just like abstract class
to achieve fully abstraction.
support the functionality of multiple
inheritance.
achieve loose coupling.
Interface fields are public, static and final
bydefault, and methods are public and
abstract.












interface printable{
void print();
}

class A implements printable{
public void print(){System.out.println("Hello");}

public static void main(String args[]){
A obj = new A();
obj.print();
}
}











interface Printable{
void print();
}

interface Showable{
void show();
}

class A implements Printable,Showable{

public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){
A obj = new A();
obj.print();
obj.show();
}
}

An interface that have no member is known as
marker or tagged interface. For example:
Serializable, Cloneable, Remote etc. They are
used to provide some essential information to
the JVM so that JVM may perform some useful
operation.
public interface Serializable{
}

An interface differs from an abstract class because
an interface is not a class
An interface is essentially a type that can be
satisfied by any class that implements the
interface.
Any class that implements an interface must
satisfy 2 conditions:
It must have the phrase
"implements Interface_Name" at the beginning of
the class definiton.
It must implement all of the method headings
listed in the interface definition.
a Java class can inherit from only one abstract class, but can
implement multiple interfaces.
Variables declared in a Java interface is by default final. An
abstract class may contain non-final variables.
Members of a Java interface are public by default. A Java
abstract class can have the usual flavors of class members
like private, protected, etc..
Java interface should be implemented using keyword
implements; A Java abstract class should be extended
using keyword extends.
An interface can extend another Java interface only, an
abstract class can extend another Java class and implement
multiple Java interfaces.
A Java class can implement multiple interfaces but it can
extend only one abstract class.

An abstract class may provide some methods with
definitions so an abstract class can have non-
abstract methods with actual implementation
details. An abstract class can also have
constructors and instance variables as well. An
interface, however, can not provide any method
definitions it can only provide method headings.
Any class that implements the interface is
responsible for providing the method
definition/implementation.
In Java, a class can only derive from one class,
whether its abstract or not. However, a class can
implement multiple interfaces
An abstract class is good if you think you will plan on using
inheritance since it provides a common base class
implementation to derived classes.
An abstract class is also good if you want to be able to
declare non-public members. In an interface, all methods
must be public.
If you think you will need to add methods in the future,
then an abstract class is a better choice. Because if you add
new method headings to an interface, then all of the classes
that already implement that interface will have to be
changed to implement the new methods. That can be quite a
hassle.
Interfaces are a good choice when you think that the API
will not change for a while
Interfaces are also good when you want to have something
similar to multiple inheritance, since you can implement
multiple interfaces.

Das könnte Ihnen auch gefallen