Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
14 views

Java - Meterial For Java (Nagraj)

Uploaded by

cyberdrip1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Java - Meterial For Java (Nagraj)

Uploaded by

cyberdrip1
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

JAVA

 Java is a object Oriented programming language


 Java is a platform independent language that means java programming can be
compiled an any operating system because
 .exe file is created depending upon the operating system different operating system
create different.exe files
 .class file ids read by all individual operating system so java is platform
independent

 Java provide reusability of code because java is a collection of predefined classes


and methods

APPLICATIONS OF JAVA

 We have 3 applications of java They are


 Standalone application (which can be run by itself)
 Enterprise/web application (client ,server communication)
 Mobile application (whatsApp, run on mobile)

JAVA API (APPLICATION PROGRAMMING INTERFACE)

Java API is a document which consist of predefined classes and objects and methods

 To run standalone application java use JSE API


 To run enterprise application java use JEE API
 To run mobie application java use JME API

INSTALLING OF JAVA

I. To run java programming we need to install


1.JDK 2.JRE 3.JVM
II. JDK –JRE Development kit(JDK) is used to develop ,run and execute java application
III. JRE-java Runtime environment is used only for execution of java application .when
we install JDK, JRE also we gets
Q. Why always execution start from main() method?

A. JVM only calls method which consist of String args[] array as input parameter this is the
reason why execution start from main method.

METHODS

 Methods are block of code which are used for better understanding of program to
perform same operation

Syntax of Methods:

public <return type> <method name>

 Return type means any user-defined or pre-defined data type.


 “Void” is a user-defined data type which doesn’t return any value.
 Method name can be anything, but it should starts with small letter followed by next
word first letter as capital letter.

Ex: public void doAdd()

Ex: Public class Sample{


int vOne;
int vTwo;
public int methodOne(){
System.out.println(“Hello ”);
return 20;
}
public long methodTwo(){
System.out.println(“Hi ”);
return 10;
}
}
Sample is a class which consists of two methods
 methodOne() whose return type is int which returns a Integer value.
 methodTwo() whose return type is long which returns a long value.
 We can store Integer value in long because long is a super class to Integer but we
cannot store long value in Integer.

Type of Methods:

Methods are divided into two types. They are

 Static methods
 Non-static methods.

Static methods:

The methods which consist of static keyword in method declaration, they are called
as Static methods.

Static methods are accessed/called by using direct class name or directly with method
name if that method belongs to that same class.

Non-static Methods:

The methods which don’t consist of static keyword are Non-static methods.

Non-static methods are accessed/called by creating object to that class.

Ex:

Public class Sample{


int vOne;

int vTwo;
public int mOne(){
System.out.println(“Hi ”);
return 23;
}
Public static long mTwo(){
System.out.printLn(“Hello ”);
return 23;
}
public static void main(String[] arg){
Sample sm=new Sample();
sm.mOne();
Sample.mTwo();
}
}

Creation of an Object:

Object- objects are instance of class, objects create memory allocation to variables/fields and
methods/blocks of that class.

Syntax to create an object:

<class name> <variable name>=new <constructor>(i.e class name)

Ex;

Sample sm=new Sample();

 By using the reference variable (i.e sm) we can access non-static and static methods
and variables;
Ex:
accessing/calling
sm.mOne();
sm.mTwo();
sm.vOne;
sm.vTwo;
 If methods are static then we can access/call static methods to static method directly
by using method name with class name
Ex:
Sample.mTwo();

Ex:

public class MyClass{

static int vOne;


char c;

public int methodOne(){

int i=10;

System.out.println(“methodOne()”);

return i;

public char methodTwo(){

System.out.println(“methodTwo()”);

return ‘1’;

 In return type we cannot declare datatype


EX. return int X
 Any digit or String inside single quote(‘ ‘) is treated as character
 In String class ,length is a non-static integer method

SYSTEM CLASS

 System class is a pre-defined class which is present in java.lang package.


 System class consist of three static variables
1.in 2.out 3.error
 As these are static variables they can be directly accessed using class name
EX. System.in, System.out, System.err
System.out.println();
CATEGORIES OF METHODS

 Methods Are Divided In 4 Categories


1. Method Which doesn’t return any value (means void return type)
2. Method which return any value.
3. Method which take input parameter.
4. Method which doesn’t take input parameter.
 Type 1,2 and 4 already discussed above
3. Method which take input parameter.
public class Test{
public void methodOne(int a){
System.out.println(a);
}

public void methodTwo(int a,char c){

System.out.println (b);
System.out.println (c);
}
public static void main (String[] args){
Test t =new Test();
t.methodOne(10);
t.methodTwo(10,’1’);

}}

 In this type of method declaration parameters are declared at method declaration


and values are assigned to parameter at the time of method calling
EX-2
public class MyClass{
Sample s;
/* it is a class name which we need in before programs ,but we are using as
userdefined datatype.*/

public Sample methodOne(){


sop("mone");
Sample s =new Sample();
return s;
}
public double methodTwo(){
System.out.println("method TWo()");
float f=10.3f;
return f;
}
}
 If we are using user defined return type then we need to create and return object of
that type and if we are using a pre defined(primitive) retrun type then we need to
return value.

public static void main(String[] args){


MyClass my =new MyClass();
my.methodOne();
my.methodTwo();

}
}

 Return statement bshould be at the last line of the function of method .


 We can directly create the object and return
EX. return s=new Sample();
 We connot create call method inside “sop” uf that method return type”void”.
 We cannot create a method inside a method

PRINT STERAM CLASS

 It is a pre-defined class present in java.io package.


 Print starem class object is consist of println() method
 T access println() metod we need to create print stream Class object
 But we have system class and variable out
i.e System.out which return PrintStrem.
 So, we are not creating object of printstream to access println() instead we are
directly using System.out
We use System.out.println();
 If we want to use PrintStream class we need to import java.io package.
 By default java.lang package is used by java remaining other package need to be
imported
 In this same way System.in return InputStream.
 We have multiple println() methods like println() which doesn’t take any parameter
and printl() method which takes parameters like int ,char Boolean ,float ,object etc

1) DriverManager is a class.
2) registerDriver() is a method with parameter of Driver class which is static method
and void return type.
Ex:
DriverManager.rgisterDriver(Driver driver);

Here we need to create Driver class object


3) getConnection() is a method with parameter of String class which is a static
method and void return type.
Ex:
DriverManager.getConnection(String s);
Here we need to create String class object.

Variables:

 variables are two types in JAVA, they are


i) Instance/Global variables.
ii) Local variables.
i) Instance/Global variables:
The variables which are inside the class outside the methods/blocks are called as
Instance/Global variables.
 For instance variables JVM provides default value if we don’t assign any value.
Datatype default value

int 0
char 0
long 0.0
double 0.0
Boolean false
 Global variables can accessed by anywhere in that class

ii) Local Variables:


The variables which are declared inside the class and insde the methods/blocks are
called as Local variables.
o Local variables can be accessed only within that method/block.
o Local variables must be initialize before using, but instance/global variables
dont’t need to initialize because JVM allocates memory by default.
o Highest priority is always given to local variables that is why local variables
get executed first.
Ex:
public class Test{
int a;
char b;
long c;
Sample s;
double d;

boolean g;

public static void main(String[] sd){


int e;
char f;
boolean h;
System.out.println(“Variable”+ e);
System.out.println(“Variable”+ f);
Test t=new Test();
System.out.println(“Variable”+ t.a);
System.out.println(“Variable”+ t.b);
System.out.println(“Variable”+ t.c);
}

If user defined data type is used like sample as instance then its default is taken as null scope

Scope of instance variable is it can be accessed throughout the class

Scope of local variable is it can be accessed only in particular block or method

CONSTRUCTORS

Constructor are the special type of functionality that are to be executed at the time of
object creation.

Constructor must be class name

Constructors doesn’t have any return type ,even void also

JVM execute constructors at the time of object creation

By using ne operator we are initializing & calling a constructor

Methods are executed when we are calling method constructors are executed while object
creation

Every java class contain a default constructor i.e. which doesn’t take any parameter or either
default or parameterised

Types of constructor

Two types of constructor

i) Constructor with parameter.


ii) Constructor without parameter
public class Test {
public Test(){
System.out.println(“Default constructot”);
}
Public Test(int a){
System.out.println(“parameterised constructot”);
}
public static void main(String[] args){
Test t=new Test(); // calling Default Constructor
Test t1=new Test(12);//calling Parameterized Constructor
}
}

We can write multiple constructors in a single program

We cannot write one class constructor in another class

When we don’t supply constructor then only JVM will supply constructor .but if we supply,
JVM won’t supply any constructor and use our supplied constructor.

 We need to create object based on Constructor.


Ex:
Public class Sample{
Public Sample(){
}
}
Public class MyClass(){
public MyClass(Sample s){
System.out.println(“MyClass Object is Created..”)
}
}

public class Test{


public static void main(String[] args){
MyClass me;me=new MyClass(new Sample());
}
}

Scanner class:

 The main use of Scanner class is to read or take the input from the keyboard.
 Scanner class is available in java.util package to access Scanner class
 Scanner class consists of non-static methods, they are next(), nextInt(),nextLong(),
nextBoolean().
 next() is a non-static method which is used to write string variable in Scanner class.
 To create object in Scanner class we need to InputStream as parameter in constructor
i.e Scanner(InputStream).
Syntax:
Scanner sc=new Scanner(InputStream or System.in)
Ex:
Import java.util.*;
Public class Read{
Public static void main(String[] ar){
Input Stream is=System.in;
Scanner sc=new Scanner(is);
String name=sc.next();
System.out.println(“name”);
long num=sc.nextInt();
System.out.println(“Integer”);
}
}
 InputStream is a class present in java.io package.
 Based on constructor we are going to create objects.
 Before object creation we need to verify constructor
BufferReader class:

 BufferReader class is same as Scanner class, both are used to accept input from the
keyboard.
 It is present in java.io package.
 BufferReader class consists of two constructors, they are
i)BufferReader(Reader reader)
ii)BufferReader(Reader r, Integer i)
 ‘Reader’ parameter is another class which is present in java.io package and it has two
constructors but protected and consists of sub-classes like InputStreamReader.
 We can store super type in sub-type but cannot store sub-type in super type.
 As Reader is also a class we need to create object for Reader class but as Reader class
constructors are protected, we cannot create for Reader class.
 But we can use InputStreamReader for creation of object as it is sub-class of Reader
class.
Ex:
import java.io.*;
import java.util.*;
public class Read{
public static void main(String[] ar){
InputStream out=System.in;
InputStreamReader read=new InputStreamReader(out);
BufferReader br=new BufferReader(read);
int num=br.read();
System.out.println(num);
}
}
 Read is method present in BufferReader class and it is non-static method, so we
called by creating BufferReader class object and it returns integer value.
 JAVA follows “Uniq code” values but not “ASCII” values.
Object Oriented Programming Structure (OOPS) concept:

OOP’s concept are written is such a way that it supports Abstraction, Inheritance,
Polymorphism, Encapsulation.

Object class it is the super /root class to all the java classes &present in java.lang package.

 Boolean equals is a method of object class

INHERITANCE

Inheritance is a process of creating chain of objects by using sub class objects we can able to
access sub class method as well as its super class methods.

It is a relationship among classes when there are dependencies of classes.


In this example we have created
ated 3 classes One, Two, and Three each class contains two
methods all are non static and there is no any relation among these classes so that we need to
create the object to each and every class and call the methods.

Inheritance accessed by two classes using “extends” keyword

Ex Two extends One

TWO sub class to ONE


Compilation of inherited program

When Test.java is compiled one class Two class both gets compiled because Test.java file
depends (or) takes values of one class & two class file

So three “class” files are generated


erated by compilation Test.java file

By using inheritance we don’t need to create multiple object directly using sub class object s
we can access super class methods also.

Execution starts from main method ,then search for object .if object is three ,name of the
class is searched when class is found ,”extends” keyword is searched .if keyword is there
then takes the class name (super class)and search for that class when class is found ,again
search for “extends” keyword ,if keyword is present take the class name & same process if
no”extends” keyword then an obje
object
ct is created of object class then object created for one
class
Type casting –converting one class type (super class)format to another
type(sub cast) format is called type casting

EX-

One t=new Two();

Two t1=new (Two)t; Type casting

T1.mthree();

T1.mfour();

“this” operator /keyword this k object keyword/operator indicates the


current(i.e the object which is called for calling methods & variable of that
class)

Using this operator we can assign local variable values to global variable values
when both the variable name is same

EX-
Public class MyClass{
int vo;
public mOne(){
int vo;
vo=101;
this.vo=vo;
}
Public void mTwo(){
System.out.println(Two);
}
public static void main(String[] args){
MyClass my=new MyClass();
my.mOne();
} }
When both global & local variables are same name then assigning local variable is done by
using ”this keyword”

this.vo=vo;

this keyword search for vo variable in the object which is by default zero then by using
assignment operator the value of vo which is 101 in mOne is overrided from zero to 101
global variable

STRINGS IN JAVA
Majorly we have 3 predefine classes to deal with string related tasks in java. They are

i) String
ii) StringBuffer
iii) StringBuilder

All these 3 classes are belongs to same package called as java.lang package

NOTE: Strings are nothing but objects in java.

String

String is immutable object, immutable means once we create an object we cannot


change i.e the value of String class object cannot be modify.

Basically there 2 ways to create the String Object

By using new operator [String s=new String ();]

By using String literal [String s=”java”;]

If you create String class object by using new operator every time it will create a new object.
In the above example two String class objects are created sone and stwo these objects are
created by using new operator so that it has created two different objects.

But if you same String class object by using String literal (“ ”) it will not create new
object every time first it will check is there any object is available in StringPool with
represent same characters if not available then only it will create new object otherwise it will
assign same address to new reference variable.

In the above diagram we have created two string objects by using string literal this
time it has not created two different objects it created only single object with same character
so that it has assign same object to new reference variable.

equals() is a method present in both object& string class whose return type is Boolean

By using equals operator we can compare two objects


EX

S1.equals(s2);

As String class is a sub class to object class we can directlt access class method using String
class object

Equals() method check content available in object

== operator check address of reference variable

By using new operator for String ,it will create each and every time new object

String objects are immutable objects because we cannot change value once object is created.

Sop(“dvr”+10+20+30) here it is concatenation operator o/p-dvr102030

Sop(10+20+30) here it is addition operator o/p-60

Sop(10+20+30+dvr) o/p-60dvr

Method overriding defining same method name & sub class method name & parameter in
super class & sub class is called method overriding.

public class BaseClass{


int i;
public void mOne(BaseClass cb){
System.out.println("baseclass");
}
}
public class DeliveredClass extends BaseClass{
int i;
public void mTwo(BaseClass cb){
super mOne(this)
System.out.println(mTwo(101));
}
public void mOne(BaseClass cb){
System.out.println("baseclass of delivered");
}
}
Public class Test{
public static void main(String[] args){
DeliveredClass cd=new DeliveredClass();
cd.mTwo(10);
cd.mOne(new DeliveredClass);
}
}
We can override main method but cannot override in same class but we can in super class &
sub class

SUPER KEYWORD used to access super class methods & variables .if we want to accees
override method from subclass we use super keyword

Method overloading- defining multiple functionality with same method & different
parameter within same class

TYPES OF INHERITANCE

1.single inheritance –one class extends other class

2.multilevel inheritance-one class extends other class & that class extends some other classes

Multipleinheritance-java doesn’t support multiple inheritance becoz its meaning is ne class


extends mre than one class

Java don’t support multiple inheritance because duplicate objects are created

Objects should be unique but in multiple inheritance more than two objects are created so
jvm undergo ambiguity situation doesn’t know which object to execute hence java doesn’t
support multiple inheritance

From one non-static method we can call another non-static method


We cannot access super & this keyword using ststic context as they are non static

Arrays-arrays are objects in java i.e arrays are similar type of objects

Array size is and start with index as zero

Syntax Datatype arrayname[] =new same datatype[size];

EX-

import java.util.*
Public class Test{
public static void main(String[] args){
int a[]=new int[];
Scanner sc=new Scanner(System.in);
for(int i=0;i<=4;i++){
System.out.println("enter integer values");
a[i]=s,nextInt();
}
}
We create arrays in java using any datatype user defined also
import java.util.*
Public class Test{
public static void main(String[] args){
BaseClass a[]=new BaseClass[];
a[0]=new BaseClass();
a[1]=new BaseClass();
System.out.println(a[0]);
}
}
If we are using datatype array we need to store values

If w use class name array then we need to supply objects


Length keyword is used to find out size of array where as length method is used to find out
length of strings

Wrapper class- wrapper class is a class .by using this class we can represent primitive
datatype as classes.the wrapper classes are class Integer, class float,class long ,class character

import java.lang.*

Public class Test{

public static void main(String[] args){

Integer[] ia=new Integer[2];

long[] i=new long[2];

Integer i =new Integer(10);

Integer ii =new Integer(20);

ia[0]=i;

ia[1]=ii;

Integer class is not a sub class to long class

In integer primitive datatype we can store integer values in long but in wrapper class we
cannot store integer class in long class

INTERFACE

interface provides services .it is a user defined data type which contains two variables
i.e static & final and a abstract method

Interface is like a class but not a class it is defined by using “interface keyword”

……………………………………………………………………………………………

System.out.println(“method”);
}

Public static void main(String args[]){

MyInterfaceImp imp=new MyInterfaceImp():

Imp.mOne();

Imp.i or MyInterface.i ;

* we cannot create object to interface &we cannot call abstract method as it doesn’t have
body

* we can create object to implement class and call interface

MyInterface i=new MyInterface.mone();

*for one interface class we can write multiple implementation classes.

*we cannot change method name in implementation class one interface class can hold many
implementation objects

*JDBC are interface class like connection servlet ae interface

EX. connection c =DriverManager.getConnection();

*interface also contatins static method with body

Public static void main(String args[]){

 But non static methods by default treated as abstract method


 If we don’t write abstract keyword ,static &final keyword in interface,by defaulit java
treated them as abstract method static final variables
 We can call one method inside a method
 If a statis method present in nterface the we need to use mandotary interface name
 The no.of methods declaraed in interface should be implemented in implementation
class All methods should be implemented
 We can execute interface using static main method
 Interface also contatin static method with body but non static methods don’t have
body &treated as abstract method
 We cannot declare one method onside a methodbit we can call one method inside
amethod
 If input parameter is taken as interface in any method then we need to provide object
of implementation class.
 Interface variable can hold implementation class
EX..public class SampleInt
{
Public void setSample (Sample Int);
}
Public Class One implent SampleInt
{
Publis static void main(Sring args[]){
One o=new One();
System.out.println(o);
}
}

Polymorphism - Single object which represents multiple behaviours at different time.

Ex.piblic interface IntOne{

Public long lv=101;

Public void method IntOne();

Public long method IntOne(Int i);

*By using extends keyword we can provide relation b/w two interfaes.

Public interface IntTwo extends IntOne{


Public double dv=202;

Public void method IntTwo(float f);

*now we can provide implementation class to both the interfaces.

Public class IntTwoImpl implements IntTwo{

Public void method IntTwo(){

Sop(“methodIntTwo”)

Public double methodIntTwo(float f){

System.out.println(“methodIntTwo(foat)”);

Return f;

Public void method IntOne(){

System.out.printl(“method int one1’);

Pubic long methodIntOne(int i){

System.out.println(“methodIntOne(int)”);

Return 25;

Using IntTwoImpl clas we are providing implementation to both interface methods

Public class Test{


Public static void main(String args[]){

IntTwoImpl ts=new IntTwoImpl();

(or)

IntTwo ts=new IntTwoImpl();

IntOne ts =new IntTwoImpl(); ***

Public clas Test{

Public static void main(String args[]){

Ts.methodIntOne();

Long l =ts.method IntOne(10);

System.out.println(l);

Ts.methodIntTwo();

Double d=ts.methodIntTwo(10.3f);

System.out.println(d);

Int hc =ts.hashcode();

System.out.print(hc);

Object class methods-hashcode(),equals(),wait(),nptify(),notifyAll().

NULL iit is a default value to all refferenece variables

** if we use normal class for execution of interfaces compiler doesn’t allow to compile the
class without all interface methods so we are going to abstract class concept

Abstract-it is used in two ways


 If abstract is used as keyword then it is use for class and methods
 Abstract class –it is a mixture of implementated and non-implemented nethod of
interface

These classes allow the compile to compile if that class doesn’t contain all interface methods
also

We cannot create object to abstract classes,so we need to extends another class so that we can
create object to abstract class and call methods

EX.public interface MyInterface{

Int I;

Public void methodOne();

Public void methoTwo();

Public abstract class MyIntImpl implements myInterface


{
public void methodOne(){
System.out.println(“methodone”);
}
}
Public class Test extends MyInterImpl{

public void methodTwo(){


System.out.println(“methodtwo”);
}
public static void main(String args[]){
Test t=new Test();
t.methodOne();
}
We cannot create object to abstract class bot we can Assign object calling to abstract class
*we can also write as

Public class Test extends MyIntImpl implements MyInterface always we need to write as
extends followed by implements

Extends------------implementation

Implementation ---------------extends

Abstraction –it hides the internal service and provide the external services i.e usefull
information to developers.

EX.every predefined methods

Final keyword-final is keywot=rs used for variable ,methods and classes

*final variable value cant be changed and it must be initialized.

Final method cannot be overrided

Final class cannot be inherited or extended buut can be extending from others

EX..

----public Final First

----public class second extend First(wrong)

--- public class First extend Sample

Final class can be extendinfg from others i.e can be a sub class

PACKAGE___

 Package is a keyword used to separate out the classes package consist of classes.
 Using package we can create same class in different packages.
 Package name can be anything and are created by using package keyword but must
contain two folders or two words
 EX>>

Package org.java.cse;

Package should be always in forst line of the program

***package in the first keyword in java

 While compiling these kind of program we need to compile as


 Javac –d Test.java
 To execute these file we need to separating fully package name as
Java org jva.cse Test-class name

Public Class Test{


Public Test(){
System.out.println(“4”);
Public static void main(Sttring args[]){
System.out.println(“1”);
//Test t=new Test();
//Sample s=new Sample();
}
} System.out.println(“4”);
System.out.println(“4”);----it is instance method i.e a method without any name treated as
instance method
Static {
System.out.println(“3”);
}
}

 First static block is executed then main method then instance method then constructor
(at the time of object creation)
 As sample object is a other class object ,then we can execute instance method after
main method
 If Test class object i.e same class object is creates then we can execute instance
method after main method

Public class Test{


Public static void main(String args[]){
System.out.println(“1”);
main(“ ”);
}
Public static void main(String args[]){
System.out.println(“2”);
main(“ ”);
}
}

 Jvm execute only main method which takes String[] array as its i/p parameters
 To execute other main method which doesn’t take i/p parameter as string [] array rhen
we need to call those method if it is static directly by name & if non static then by
creating object
 Access specifiers & access modifiers
 Public ,private protected and default are treated as access specifiers & access
modifiers
 Public –variable , methods, classes and constructors are treated as public we can
access within all the locations i.e any were we can access
 Private-variables, methods ,can be accessible within same class cannot access outside
class
 Protected-variable ,methods and classes we can access within super class sub class of
same package or different pavkage
 Default we can access with the diff pavkage default is not a keyword but when we
don’t write public,private and protected then that is treated as defaul
Public class Test{
Public sample s;
Public void setSample(Sample
ample(Sample s){
this .s=s;
}
Public class temp{
Public static void main(String args[]){
Test t=new Test();
t.setSample(new Sample);
}
}

Encapsulation

Binding
inding (accessing the data) the data to only related functionalities is called
encapsulation and also unbinding the data to unrelated functionalities

>>>>>>>>>>>>>>>>>>>>>>>>>> >>>>>>>>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>EXCEPTIONS>>>>>>>>>>>>>>>>>>>>>>>>

Public class Temp{

Int i=10;

Int j=10/0;
System.out.println(J);

Exceptions ---Exceptions are object which contains total information about the failure
statement

Exceptions are also pre defined classes we can say this because we can create object only to
classes once an exception is raised by jvm ,programmatically terminated &remaining
statement are not executed

As a programmer we should avoid abnormal termination of program

To avoid abnormal termination we need to handle exception by using exceotion handles

Exception handling---the process of handling the exception is called exception handling

In order to handle exception we have #blocks

1)try 2)catch 3)finally

Exceptions occurs at runtime i.e execution exceptions is subclass to throwable class and
throwable class is subclass to object class

Object class

Object classthrowable classexception

Errors are occurred with problem of hardware at compiletime

While exceptions occur with problem of software

Sub class of exception are Arthimatic exception,ClassNotFoundException-


ArrayIndexOutOfBoxException-RunTimeException

To all exception class &errors class Throwable is super class

Try block: try block used to identify the Exception after identification it is going to transfer
the same Exception to catch block.
I) In the try block we can write the statements which cause exceptions.
II) We should not write single try block if we write single try block it is going give
error message saying that “try without catch ,finally or resource declaration”.
III) We should write try with catch or finally block.
IV) We can write multiple catch blocks to the single try
V) We can write try with finally ,we can write try with catch and finally also but
finally block should be last block of try.

Catch Block: Catch block is capable of storing or handling the Exceptions.

i) Catch block is executed if and only if the exception is occurred


ii) If no exception catch block will not get execute.

Example 1: if there is an execption

public class Test{

public static void main(String[] argd){

int i=101;

System.out.println("Started");

try{

System.out.println("1");

System.out.println("2");

int j=i/0; //somethig by 0

System.out.println(j);

System.out.println("3");

System.out.println("4");

}catch(ArithmeticException ae){

System.out.println("catch block is executed..");

System.out.println("Ended");

}
If there is an exception in the program it will not execute all the statements in the try block it
will execute the statements before exception statement (i.e with in this example “int j=i/0 “)
directly it will enter into catch block .

Example 2: if there is an no exception :

public class Test{

public static void main(String[] argd){

int i=101;

System.out.println("Started");

try{

System.out.println("1");

System.out.println("2");

int j=i/100; //somethig by something

System.out.println(j);

System.out.println("3");

System.out.println("4");

}catch(ArithmeticException ae){

System.out.println("catch block is exe


executed..");

System.out.println("Ended");

}
Finally Block: finally block always execute even exception may occur or may not occur.

public class Test{

public static void main(String[] argd){

int i=101;

System.out.println("Started");

try{

int j=i/100; //somethig by something

}catch(ArithmeticException ae){

System.out.println("catch block is executed..");

}finally{

System.out.println("Finally Block is executed..."); }

System.out.println("Ended");

}
public class Test{

public static void main(String[] argd){

int i=101;

System.out.println("Started");

try{

int j=i/0; //somethig by zero

}catch(ArithmeticException ae){

System.out.println("catch block is executed..");

}finally{

System.out.println("Fina
System.out.println("Finally Block is executed...");

System.out.println("Ended");

Hierarchy in Exceptions
Object is the super class to All the java classes. Throwable is the super class to all the
Exception and Error classes.Exception is the super class to all the exception classes like
ArithmaticException,ClassNotFoundException..etc.And to all the error classes Error is the
super class.

As per inheritance we can store sub class object in super class so ArithmaticException is a
sub class to RuntimeException,Exception and Throwable that is the reason why we can store
ArithmaticException object in RuntimeException,Exception,Throwable.

To the single try block we can declare multiple catch blocks but we need to follow the order
like from sub class to super class but not super class to sub class.

public class Test{

public static void main(String[] argd){

System.out.println("Started");

try{

int i=101;

int j=i/0; //ArithmeticException

}catch(ArithmeticException ae){

System.out.println("ArithmeticException catch block");

}catch(RuntimeException ae){

System.out.println("RuntimeException catch block");

}catch(Exception ae){

System.out.println("Exception catch block");

}catch(Throwable ae){

System.out.println("Throwable catch block");

}finally{

System.out.println("Finally Block is executed..");

System.out.println("Ended");

}
}

public class Test{

public static void main(String[] argd){

System.out.println("Started");

try{

int i=101;

int j=i/0; //ArithmeticException

}catch(Throwable ae){

System.out.println("Throwable catch block");

}catch(Exception ae){

System.out.println("Exception catch block");

}catch(RuntimeException ae){

System.out.println("RuntimeException catch block");

}catch(ArithmeticExcepti
}catch(ArithmeticException ae){

System.out.println("ArithmeticException catch block");

}finally{

System.out.println("Finally Block is executed..");

System.out.println("Ended");

}
Exceptions are of 2 types they are

I) Checked Exceptions
II) Unchecked Exceptions

NOTE: Exceptions are occurred only runtime there no Exception at compile time

i) Checked Exceptions :

Checked exceptions are exceptions which are checked by the compiler and which are not sub
classes to RuntimeException.

Ex: ClassNotFoundException,SQLException.

ii) Unchecked Exceptions :

Unchecked exceptions are the execeptions which are not checked by the compiler and
which are sub classess to RuntimeException.

Ex:ArithmaticException,NullPointerException

finalize() Method : finalize()


nalize() is a non static method available inside Object class which is
used to call the garbage collector it will remove unused objects .
What is final ,finally and finalize ?

final is keyword that is applicable to the variables,methods,and classes.If a variable


declared as final that variable cannot be change,if a method as declared as final that method
cannot be override in subclasses,if a class is declared as final that class cannot be
inherit(extend) by other classes but final class can extends any ot
other class.

finally() is a block which is used to handle the exception.

throws : If any checked exception is available in the program the compiler will not allow you
to compile the class without writing the try and catch blocks. Instead of writing try and catch
to handle the checked exceptions we can use “throws” keyword.

By using throws keyword we are explicitly mentioning to the compiler to allow the program
to compile

throw : By using “throw” keyword we can rise a new exception object


The above exception called as “StudentNameNotValidExcpetion” is called user defined
exception and it is going to occur at the time of user has supplied invalid username.In order to
create and throw that execption we use “throw” keyword

>>>>>>>>>>>>>>>>>>>>>>>THREADS>>>>>>>>>>>>>>>>>>>>>>>>>

Basically there are two types of execution is there in the programming they are

i) Process Based Execution


ii) Thread based Execution

Java doesn’t support process based execution because one process is depends on another
process. So that there is a chance of idle state in order to avoid that java people has
invented threads concept in java.

Thread is a part of process and thread is light-weight component.


Threads can be create in two ways they are

i) By Implementing Runnable Interface


ii) By extending Thread class

Process of create and execute the threads

1) Define a class by implementing Runnable interface/extending the tThred class


2) Override a method called as run() method
3) Create the object to Thread Class / Subclass to Thread
4) And call the method called as start() method from Thread class

By implementing Runnable Interface

Runnable is an interface available in java.lang package and it contains only single


method i.e run() which returns void and it is non static method.
By Extending Thread Class

Thread is class which is available in java.lang package and it contains the following
methods

public void start()

public
public static void sleep(long ms)

By using start() method we can execute the threads and by using sleep method we can make
threads into waiting state until specified time is expires. Once the time which we have
supplied int the sleep(long ms) expires the threads which are waiting in the waiting
waiti state
automatically invoked .
By using wait() method of Object class also we can make the thread into enter waiting state.

If you call sleep(int ms)from Thread class threads will enter into the waiting state and
automatically invoked from waiting state to running state once the specified time is expires.

But if you call wait() method from Object class threads will enter into waiting state and
threads will wait for invoke from notify() or notifyAll() methods until and unless we call
notify() or notifyAll()
ifyAll() methods from Object class threads will wait in waiting state only.

Multi-Threading:

The process of defining and executing the more than one thread is called as milti-
milti
threading. Java supports only multi-threading.
multi

yield() : indicates that the thread is not doing anything particularly important and if any other
threads or processes need to be run, they can. Otherwise, the current thread will continue to
run.

join(): The join() method of a Thread instance is used to join the start of a thread’s
execution to end of other thread’s execution such that a thread does not start running until
another thread ends. If join() is called on a Thread instance, the currently running thread will
block until the Thread instance has finished executing.
The join() method waits at most this much milliseconds for this thread to die. A timeout of 0
means to wait forever.

Daemon Thread :

Daemon threads are the threads which always run in background process. gc() is a
garbage collector which always runs in background to clean up un used objects

Thread Deadlock:

If two or more threads are enter into waiting state and waiting for each other for
invoke from the waiting state is called as Deadlock situation in Threads.

Thread Life Cycle:

All these threads can be execute and handle by a Thread Scheduler this is used to assign the
priorities to threads and give the specific time to all the threads. We can also assign some
priorities to particular threads by using MAX_PRIORITY, MIN_PRIORITY,
NORM_PRIORITY constants variable from Thread class.

The default priority for all threads is 5.

Synchronization:
Multi-threaded programs may often come to a situation where multiple threads try to access
the same resources and finally produce erroneous and unforeseen results.
So it needs to be made sure by some synchronization method that only one thread can access
the resource at a given point of time.

Java provides a way of creating threads and synchronizing their task by using synchronized
blocks. Synchronized blocks in Java are marked with the synchronized keyword. A
synchronized block in Java is synchronized on some object. All synchronized blocks
synchronized on the same object can only have one thread executing inside them at a time.
All other threads attempting to enter the synchronized block are blocked until the thread
inside the synchronized block exits the block.

>>>>>>>>>>>>>>>>>>>>>COLLECTIONS>>>>>>>>>>>>>>>>>>>>>

Collections are the objects by using these collections we can make different type of objects
into single unit they are majorly 3 types of collection objects we have they are

i) LIST
ii) SET
iii) MAP

 List is an Interface
 Set is also an Interface
 Map is a plain interface
 By using collection we can give group of objects in to single object/unit.
 In collection we use only objects but not values abstract list and is can add
methods.
Ex. import java.util.*
Public class Array list
{
Psvm (---)
List l=new Array list ();
l. add(101);
l. add(s101);
l. add(10.3);
 iterator i=l.iterator();
 By using array list we can store different data types
 Iterator is a interface with methods, hashnext () Boolean & next of E.
If (i.hash Next ()); \\ how many times we call this method
Sop i.next()); that many values can be printed
If (i.hashNext());
Sop (i.next());
(or)
While(i.hashNext()) \\ one if we call in while bop all
{ sop(i.next()); } values can be printed.
Hashset hs=new Hashed();
Set.add(101);
Set.add(102);
Set.add(102);
Set.add(102);
Set.add(1);
Iterator si=set.Iterator();
While (si.hashNext ());
{ sop (si.next()); }
}
 List allows duplicators but set doesn’t allow duplicates
 List displays as per insertion order but set doesn’t follow insertion order rather it
follows the 1st priority is character the string then int.

SET

 Set will not allow duplicates

MAP

 Map will store key and object pair

>>>>>>>>>>> JDBC (JAVA DATABASE CONNECTIVITY) >>>>>>>>>>>>>>>>>.

 Java applications cannot take data from database directly.


 So we use JDBC to communicate java with DB.
java

JDBC API(or)

JDBC Software

 Steps to write JDBC:


 Step 1: Register the Driver(By passing Driver class object as a parameter to
registerDriver() method)

EX:-DriverManager.registerDriver(new.com.mysql.jdbc. driver());

 Step 2: Get the connection from database server


(By supplying URL,username,password as parameter to
getConnection()method).

Ex:-connection c=DriverManager.getConnection(jdbc:mysql://
localhst:3306/13-560”,”root”,”dvrcet);
 Step 3:-Create statement object(which is used to send sql query to the database
server).

Ex:-statement s=c.createStatement();
 Step 4:-Execute sql query(By supplying sql query at the parameter through
executeQuery()method).

Ex:-Resultset rs=s.executeQuery(“select sid,sname,age from student”);

 Step 5:-Close Connection.

EX:-c.close();

 Connection,Driver,Statement,PrepareStatement, Resultset are interfaces of JDBC


and DriverManager is class.

JAVASCRIPT

 Java script is a scripting language which is mainly used for validations of forms.
 We need to avoid irrelevant data i.e. given by customer or User at client side.
 Validations are of two types
 Server side validations
 Client side validations

If in html if we use work < script> then it’s called internal java script.

CSS (CODE STYLE SHEETS)

 Internal style sheets – written inside program.


 External style sheets- separate tag as css file include in program html with
relational attribute.
 With in line ex<h4- styles =color=red.>

>>>>>>>>>>>>>>>>>>>>>>>>>>>> SERVLETS >>>>>>>>>>>>>>>>>>>>>>>


 Servlets can be developed in following ways
 Implementing Servlet Interface
 Extending GenericServlet
 Extending HttpSerlet
 Servlets are present in javax.servlet package.
 Another way of developing servlets is javax.servlets
 Servlet interface methods

i) void init(ServletConfig)
ii) void service(ServletRequest request,ServletResponse response)
iii) void destroy()
iv) String getServletInfo()
v) ServletConfig getServletConfig()

ARCHITECTURE

dddd
Web Browser http request Tomcat/JEE Server

hfhhfigrfifje http response

PACKAGES OF SERVLET

 Servlets are developed under two package


 Javax.servlet
 Javax.servlet.http.
 If you develop servlet class using “javax.servlet” package then they are executed
in any protocol i.e independent of protocol.
 If you develop servlet class “javax.servlet.http” package then they are execute
with in the http protocol only i.e. protocol dependent
 HttpServlet is subclass to GenericServlet and GenericServlet is implementation
class to Servlet interface.
 How to execute one Servlet from another Servlet?
ANS:-We have request dispatcher.
Executionof servlet:
 Servlet is stored as .java file,so we get .class file after compilation of program.
 Servlets are executed by server.
 We need to follow the below process for storing of servlet programs.

Project

WEB-INF

Classes

lib

Web.xml

 Generated .class file of servlet is stored in classes folder.


 An .xml file is generated to show the server about the location of program
&execution,it is stored in web.xml folder.
XML program:
<web_app>
<servlet>
<servlet_name>one</servlet_name>
<servlet_class>.class filename</servlet-class>
</servlet>
<servlet-name>one</servlet_name>
<url-pattern>/one</url-pattern>
<web_app>

>>>>>>>>>>>>>>>>>>>>>>>> JSP >>>>>>>>>>>>>>>>>>>>>>>>>>>

 JSP is a technology that helps software developers create dynamically


generated web pages based on HTML,XML,java or other document type.
 Jsp is similar to PHP,ASP but it uses the java programming language.
 JSP and HTML are placed inside project but outside WEB_INF folder.
 Printwrite object we can give program to client & execute.
 In JSP we donot need to write class, printwriter objects. Everything is
executed directly.
 We should not write java code directly in JSP.
 We have multiple elements to write java code.
 If we write java code without any tag that data is treated as normal text &
printed as same what we write.
 For html we write tags & for java we need to write with java syntax.
 Template text-the text written without following any syntax or signature
out.write().
EX:-hi welcome jsp template text.
<form>
Username -<input type=”text”/> html text
</form>
 For writing java code we use “scriptlets” in JSP Scriptlets syntax.

<%
Class.forName(“com.mysql.jdbc.Driver()”);

DriverManager.getConnection(“jdbc:mysql://localhost:3066/dvr”,”root”,”root”
);
%>

 The code which is written inside scriplet(<%-----------%>) is placed inside


service method. i.e., jsp service ().
We should not write import package in scriptlets a the code inside scriplet is
stored inside service method and packages are written on top of the
program.
 Within a single jsp we can write multiple scriplet.

Page Attribute –To import package.


<%@page import =”java.sql.*”%>

Attribute Package name


 The above syntax is converted into servlet as package and print above
program.
 Servlet declare methods & instance variables inside scriptlets as we
cannot declare one method inside another method.
 To declare instance variables we need to declare as

JSP Declaration
<%!
int i;
public void methodOne();
{ sop(“methodOne()”) }

%>

JSP Expressions

Syntax - <% =Instance variable %>

<% = i %> Print value of ‘i’ i.e. variable data & method return type.

You might also like