Java - Meterial For Java (Nagraj)
Java - Meterial For Java (Nagraj)
APPLICATIONS OF JAVA
Java API is a document which consist of predefined classes and objects and methods
INSTALLING OF JAVA
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:
Type of Methods:
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.
Ex:
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.
Ex;
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:
int i=10;
System.out.println(“methodOne()”);
return i;
System.out.println(“methodTwo()”);
return ‘1’;
SYSTEM CLASS
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’);
}}
}
}
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);
Variables:
int 0
char 0
long 0.0
double 0.0
Boolean false
Global variables can accessed by anywhere in that class
boolean g;
If user defined data type is used like sample as instance then its default is taken as null scope
CONSTRUCTORS
Constructor are the special type of functionality that are to be executed at the time of
object creation.
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
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.
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.
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.
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
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-
T1.mthree();
T1.mfour();
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
String
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
S1.equals(s2);
As String class is a sub class to object class we can directlt access class method using String
class object
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(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.
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
2.multilevel inheritance-one class extends other class & that class extends some other classes
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
Arrays-arrays are objects in java i.e arrays are similar type of objects
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
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.*
ia[0]=i;
ia[1]=ii;
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”);
}
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 cannot change method name in implementation class one interface class can hold many
implementation objects
*By using extends keyword we can provide relation b/w two interfaes.
Sop(“methodIntTwo”)
System.out.println(“methodIntTwo(foat)”);
Return f;
System.out.println(“methodIntOne(int)”);
Return 25;
(or)
Ts.methodIntOne();
System.out.println(l);
Ts.methodIntTwo();
Double d=ts.methodIntTwo(10.3f);
System.out.println(d);
Int hc =ts.hashcode();
System.out.print(hc);
** 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
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
Int I;
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.
Final class cannot be inherited or extended buut can be extending from others
EX..
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;
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
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>>>>>>>>>>>>>>>>>>>>>>>>
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
Exceptions occurs at runtime i.e execution exceptions is subclass to throwable class and
throwable class is subclass to object class
Object 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.
int i=101;
System.out.println("Started");
try{
System.out.println("1");
System.out.println("2");
System.out.println(j);
System.out.println("3");
System.out.println("4");
}catch(ArithmeticException ae){
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 .
int i=101;
System.out.println("Started");
try{
System.out.println("1");
System.out.println("2");
System.out.println(j);
System.out.println("3");
System.out.println("4");
}catch(ArithmeticException ae){
System.out.println("Ended");
}
Finally Block: finally block always execute even exception may occur or may not occur.
int i=101;
System.out.println("Started");
try{
}catch(ArithmeticException ae){
}finally{
System.out.println("Ended");
}
public class Test{
int i=101;
System.out.println("Started");
try{
}catch(ArithmeticException ae){
}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.
System.out.println("Started");
try{
int i=101;
}catch(ArithmeticException ae){
}catch(RuntimeException ae){
}catch(Exception ae){
}catch(Throwable ae){
}finally{
System.out.println("Ended");
}
}
System.out.println("Started");
try{
int i=101;
}catch(Throwable ae){
}catch(Exception ae){
}catch(RuntimeException ae){
}catch(ArithmeticExcepti
}catch(ArithmeticException ae){
}finally{
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.
Unchecked exceptions are the execeptions which are not checked by the compiler and
which are sub classess to RuntimeException.
Ex:ArithmaticException,NullPointerException
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
>>>>>>>>>>>>>>>>>>>>>>>THREADS>>>>>>>>>>>>>>>>>>>>>>>>>
Basically there are two types of execution is there in the programming they are
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 class which is available in java.lang package and it contains the following
methods
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.
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.
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
MAP
JDBC API(or)
JDBC Software
EX:-DriverManager.registerDriver(new.com.mysql.jdbc. driver());
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:-c.close();
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.
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
PACKAGES OF SERVLET
Project
WEB-INF
Classes
lib
Web.xml
<%
Class.forName(“com.mysql.jdbc.Driver()”);
DriverManager.getConnection(“jdbc:mysql://localhost:3066/dvr”,”root”,”root”
);
%>
JSP Declaration
<%!
int i;
public void methodOne();
{ sop(“methodOne()”) }
%>
JSP Expressions
<% = i %> Print value of ‘i’ i.e. variable data & method return type.