Oopj Digital Note@kkj-1
Oopj Digital Note@kkj-1
Module1:-
Chapter 1-: An introduction to programming.
Different types of programming languages, Description of Compiler and Interpreter,
Advantage of Object Oriented Programming, Object Oriented Programming, Features of
Object Oriented Programming.
Chapter 2-: Introduction to Java.
What is Java?, Why Java?, History behind Java, Different versions of Java, Difference between
C/C++ and Java, Features of Java, First Java Program, Prerequisites Before start writing a
java program, Writing the program, Compiling the program, How Java program compiles?,
Executing the program, How Java program executes?, What is JVM and its significance in
executing a program?, Architecture of JVM.
Chapter 3-: Understanding First Program and a step forward, Understanding every term of
the program, Java Tokens, Datatypes, Operators, What are Operators?, Different types of
Operators, Typecasting, Control Structures and Arrays, Different types of control structures,
Conditional Statements, Loops/ Iterators, Jumping Statements, Java Arrays,
Multidimensional Arrays, Taking Input from keyboard, Command Line Arguments, Using
Scanner Class, Using Buffered Reader class.
Module 2: -
Chapter 1-: Introduction to Classes and Objects.
Classes, Methods, Objects, Description of data hiding and data encapsulation, Constructors,
Use of static Keyword in Java, Use of this Keyword in Java, Array of Objects, Concept of
Access Modifiers (Public, Private, Protected, Default).
Chapter 2-: Inheritance
Understanding Inheritance, Types of Inheritance and Java supported Inheritance,
Significance of Inheritance, Constructor call in Inheritance, Use of super keyword in Java,
Polymorphism, Understanding Polymorphism, Types of polymorphism, Significance of
Polymorphism in Java, Method Overloading, Constructor Overloading, Method Overriding,
Dynamic Method Dispatching.
Chapter 3-: String Manipulations.
Introduction to different classes, String class, String Buffer, String Builder, String Tokenizer,
Concept of Wrapper Classes, Introduction to wrapper classes, Different predefined wrapper
classes, Predefined Constructors for the wrapper classes. Conversion of types from one type
(Object) to another type (Primitive) and Vice versa, Concept of Auto boxing and unboxing.
Chapter 4:- Data Abstraction
Basics of Data Abstraction, Understanding Abstract classes, Understanding Interfaces,
Multiple Inheritance Using Interfaces, Packages, Introduction to Packages, Java API
Packages, User-Defined Packages, Accessing Packages, Error and Exception Handling,
Introduction to error and exception, Types of exceptions and difference between the types,
Runtime Stack Mechanism, Hierarchy of Exception classes, Default exception handling in
Java, User defined/Customized Exception Handling, Understanding different keywords (try,
catch, finally, throw, throws), User defined exception classes, Commonly used Exceptions
and their details.
Chapter 5:- Multithreading
Introduction of Multithreading/Multitasking, Ways to define a Thread in Java, Thread
naming and Priorities, Thread execution prevention methods. (yield(), join(), sleep()),
Concept of Synchronisation, Inter Thread Communication, Basics of Deadlock, Demon
Thread, Improvement in Multithreading, Inner Classes, Introduction, Member inner class,
Static inner class, Local inner class, Anonymous inner class.
Module 3: -
Chapter 1:- IO Streams (java.io package)
Introduction, Byte Stream and Character Stream, Files and Random Access Files,
Serialization, Collection Frame Work (java.util), Introduction, Util Package interfaces, List,
Set, Map etc, List interfaces and its classes, Setter interfaces and its classes.
Chapter 2:-Applet
Introduction, Life Cycle of an Applet, GUI with an Applet, Abstract Window Toolkit (AWT),
Introduction to GUI, Description of Components and Containers, Component/Container
hierarchy, Understanding different Components/Container classes and their constructors,
Event Handling, Different mechanisms of Event Handling, Listener Interfaces, Adapter
classes.
Module 4: -
Chapter 1:- Swing (JFC)
Introduction Diff b/w awt and swing, Components Hierarchy, Panes, Individual Swings
Components JLabel, JButton, JTextField, JTextArea.
Chapter 2:- JavaFX
Getting started with JavaFX, Graphics, User Interface Components, Effects, Animation, and
Media, Application Logic, Interoperability, JavaFX Scene Builder 2, Getting Started with
scene Builder.
Working with scene Builder.
Text Book:-
1. Programming in Java. Second Edition. OXFORD HIGHER EDUCATION. (SACHIN
MALHOTRA/SAURAV CHOUDHARY)
2. CORE JAVA For Beginners. (Rashmi Kanta Das), Vikas Publication
Reference Book:-
1. JAVA Complete Reference (9th Edition) Herbalt Schelidt.
Definition of Java:
Java is a general purpose, high level and objected oriented programming language. It was
developed by Sun Microsystem and James Gasling is popularly known as father of java.
Features of Java:
i. Java is compiled as well as interpreted language.
ii. Java supports Object Oriented Programming.
iii. It is used to develop internet based application.
iv. It is used to create dynamic web pages.
v. It provides facilities to program electronic consumable device such as mobile, laptop,
palmtop using J2ME.
vi. It supports multi threading
class First
{
public static void main(String args[ ])
{
System.out.println(“Hello World”);
}
}
• Javac is the compiler used to convert the .java file into .class file or byte code
• The .class file is platform independent
• JVM interprets the .class file to generate machine code
• JVM contains the interpreter known as Java
• Now-a-days, JVM is embedded with OS and web browser like Internet Explorer, Mozilla Firefox
etc.
• JVM takes nano space
int(4 bytes)
float(4bytes)
char(2bytes)
double(8 bytes)
short int(2 bytes)
unsigned int(4 bytes)
long int(8bytes)
byte(1byte)
boolean(1bit)
Wrapper Class
• Wrapper classes are used to convert one data type into another data type.
• Wrapper class contains different methods for such conversion.
• In order to make Java more object oriented programming language, wrapper classes are used.
Example:
Integer, Float, Double, Boolean, Byte
class Add
{
public static void main(String args[ ])
{
int a=10,b=20;
System.out.println(“The Sum=”+(a+b));
}
}
Compilation: javac Add.java
class Add
{
public static void main(String args[ ])
{
int x = Integer.parseInt(args[0]);
int y = Integer.parseInt(args[1]);
int z=x+y;
System.out.println(“The Sum=”+z);
}
}
Compilation: javac Add.java
• parseInt is a method of Integer class .This method is used to convert a string datatype into
integer type.
• The above statement converts the contents of args[0] into integer type and stores it in an
integer variable x.
• While executing a java program if we provide values through command prompt then it is
known as command line argument. These command line arguments are stored in the
array args[ ]
• Conditional Operator(?:)
• Bitwise Operators ( & , | , ^ , >> , >>> , << , ~ )
NOTE:
1.Write the Output for the following segment:
int a = 10,b=20;
System.out.println(“Hello”+a+b); Output-Hello1020
System.out.println(+a+b+“Hello”); Output-30Hello
System.out.println(+“Hello”+a); Output-Error
System.out.println(a+b+“Hello”); Output-30Hello
Decisions in Java
If Statements:
• Simple if statement
• if-else statement
• Ladder else-if statement
• Nested if statement
Simple if statement
Syntax:
if ( condition)
{
Statement;
}
if-else statement
Syntax:
if (condition)
{
Statement;
}
else
{
Statement;
}
Syntax:
if ( condition)
{
Statement;
}
else if ( condition)
{
Statement;
}
else if ( condition)
{
Statement;
}
….
….
….
….
Nested if-else statement
• When one if statement is present inside another if statement then it is known as nested
if statement.
Syntax:
if (condition)
{
if(condition)
{
Statement;
}
else
{
Statement;
}
}
else
{
Statement;
}
Switch case :
• It is used to execute certain tasks among a number of tasks.
Syntax:
switch(exp.)
{
case value1:
statement;
break;
case value2:
statement;
break;
.
.
.
case value n:
statement;
break;
default:
statement;
}
Loops in Java
• Loops are used to execute the same statements again and again.
• Different loops used in Java are:
➢ while loop
➢ do while loop
➢ for loop
while loop
syntax:
while(condition)
{
statement;
increment/decrement;
}
do while loop
syntax:
do
{
Statememt;
increment/decrement;
}while(condition);
for loop
syntax:
for(initialization;condition;increment/decrement)
{
Statement;
}
Object:
• It is an instance of class.
Encapsulation:
• It is the process of combining the data member and member function into a single unit.
Abstraction:
• It is the process of dealing with essential features without including the unnecessary
details/background details.
Inheritance:
• It is the process of creating a new class by inheriting the properties and behavior of one
or more existing classes.
• The existing class is known as base class / parent class / super class and the newly created
class is known as derived class / child class / sub class.
Polymorphism:
Dynamic Binding:
Delegation:
• When the object of one class will act as the data member in another class then it is known
as delegation.
Message Passing:
A class is an user defined data type which is the collection of dissimilar types of data and
functions.
Syntax:
Variables;
Methods;
Example:
class Student
int roll;
int age;
int mark;
void display( )
….
…..
Access Specifier:
It specifies the visibility mode of class members. Java supports following types of access
specifier.
• private
• public
• protected
• default
private:
when the data member(variable) and member function(function) are declared under private
access specifier then they can be accessed inside the class only. But they cannot be accessed
outside of the class as well as in the derived class.
public:
when the data member(variable) and member function(function) are declared under public access
specifier then they can be accessed inside the class ,outside of the class as well as in the derived
class.
Protected:
when the data member(variable) and member function(function) are declared under protected
access specifier then they can be accessed inside the class and in the derived class. But they
cannot be accessed outside of the class .
default:
when the data member(variable) and member function(function) are declared under default
access specifier then they can be accessed within the package. Package is a collection of classes
and interfaces.
Note:
• When no access specifier is mentioned, then the default access specifier is public.
• Semi colon (;) is optional to terminate a class.
Access Modifier:
Access Modifiers are used to modify the accessibility of class members. Java uses the following
access modifiers:
• final
• static
• abstract
• volatile
• synchronize
• transient
• native
Note:
final:
This keyword is used to declare a variable whose value is fixed throughout the program
execution. It is used to declare constants in Java.
Example:
Example:
class Smpl
void display( )
System.out.println(“Hello World”);
class Smpl1
k.display( );
Compile:javac Smpl1.java
class Add
int a,b;
a=i;
b=j;
System.out.println(“The Sum=”+(a+b));
class Add1
int m=Integer.parseInt(args[0]);
int n=Integer.parseInt(args[1]);
k.display( m,n);
Compile:javac Add1.java
Write a program to display employee no=1 and employee age=25 using class
class Emp
int n,a;
n=i;
a=j;
class Emp1
k.display( 1,25);
Compile:javac Emp1.java
Write a program to display the student name, roll no and age of a student using class
class Student
String n;
int r,a;
n=i;
r=j;
a=k;
void display( )
System.out.println(“The Name=”+n);
System.out.println(“The Age=”+a);
class Student1
String z=args[0];
int m=Integer.parseInt(args[1]);
int n=Integer.parseInt(args[2]);
k.accept(z,m,n);
k.display( );
Compile:javac Student1.java
Static Members
Static members can be
• When a variable is declared with “static” keyword then it becomes a static data
member(static variables)
• Static variables are known as class variables and non static variables are known as
instance variables.
• Static variable is available as per class basis where as non-static variable is available as
per object basis.
• A static variable has one copy for the entire class and all the objects of the class shares a
single copy of static variable,where as a non-static variable has separate copy for each
object of the class.
Static method
• When a method is preceded with “static” keyword then it is known as static method(static
member function)
• A static method can directly access static variables.
• But a static method cannot access a non static variable directly. In order to do so, the
object of the class is created within the static method.
• A non static method can access static as well as non static variable directly.
• Static members can be directly accessed by the help of object and they can also be
accessed by the help of class name.
Example:
class Use
{
int a;
static int b;
Use(int i,int j)
{
a=i;
b=j;
}
void show()
{
System.out.println(a);
}
static void display()
{
System.out.println(b);
}
}
class Use1
{
public static void main(String args[])
{
Use k=new Use(5,7);
k.show();
k.display();
}
}
Static Block
• When a block is declared with “static” keyword without any name then it is known as static
block.
• In a program, the static block is executed first by the JVM.
• If a class contains static block and main( ) then the static block is executed first followed by
main()
• In Java, we can write program without main ( ).
Example:
class Use
{
static int x;
static
{
x=10;
System.out.println(x);
}
public static void main(String args[])
{
System.out.println(“hello”);
}
}
Note:
Why main( ) is static?
• We know that a static method can be accessed without creating object. As main( ) is a
member function of a class , in order to access it we need object of the class.
• When we first time execute a java program object is not created.
• If we make main( ) as static then JVM can directly invoke the main( ) using the class
name.
• If at all, main( ) is a non static method then it can never be invoked by JVM because no
object is created.
Constructor
• Constructor is a special member function whose name is same as class name.
• Constructor is automatically called when the object is created.
• It does not have any return type.
• It is used to construct the object by allocating memory to the object.
Types of Constructor
• Default Constructor
• Parameterized Constructor
• Copy Constructor
Default Constructor
When a constructor does not accept any argument/parameter then it is known as Default
Constructor.
Parameterized Constructor
Copy Constructor
When a constructor takes class type as its argument/parameter then it is known as Copy
Constructor.
Constructor Overloading
When more than one constructor is available in a program then it is known as Constructor
Overloading.
Note:
class Use
int a,b;
a=4;
b=9;
System.out.println(a+ “ “ +b);
a=i;
b=j;
System.out.println(a+ “ “+ b);
a=k.a;
b=k.b;
System.out.println(a+ “ “+ b);
class Use1
Method Overloading
• When more than one method with same name having either different no. of arguments or
different data type of arguments or different ordering of arguments then it is known as
method overloading.
• In method overloading, the method name is same but each method has to vary either by
no. of arguments or data type of arguments or ordering of arguments.
Example:
class Use
int a,b;
a=i;
System.out.println(a);
a=i;
b=j;
System.out.println(a+ “ “+ b);
class Use1
k.display(6);
k.display(5,9);
Inheritance
• It is the process of creating a new class by inheriting the properties and behavior of one
or more existing classes.
• The existing class is known as base class / parent class / super class and the newly created
class is known as derived class / child class / sub class.
Types of Inheritance
• Single Inheritance
• Multiple Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Single Inheritance
• When a new class is created by inheriting the properties and behavior of one existing
class then it is known as single inheritance mechanism.
Multiple Inheritance
• When a new class is created by inheriting the properties and behavior of two or more
existing classes then it is known as multiple inheritance mechanism.
Multilevel Inheritance
• When a new class is created or derived from another derived class then it is known as
multilevel inheritance mechanism.
Hierarchical Inheritance
• When the classes are created or derived like tree structure then it is known as hierarchical
inheritance mechanism.
Hybrid Inheritance
• When a new class is created by applying more than one inheritance mechanism then it is
known as hybrid inheritance.
NOTE:
• Java does not support multiple inheritance directly. But it can be used in java using
Interface mechanism.
• Hybrid inheritance can be used in java if it contains multiple inheritance mechanism.
• To inherit a class, “extends” keyword is used.
Example of Inheritance
class A
{
void show( )
{
System.out.println(“hello”);
}
}
class B extends A
{
void disp( )
{
System.out.println(“world”);
}
}
class C
{
public static void main(String args[ ])
{
B k=new B( );
k.show( );
k.disp( );
}
}
Method Overriding
• When more than one method with same signature (same prototype) is available in class
then it is known as Method Overriding.
• Here, the same method can be defined differently in the parent and child class.
• For Method Overriding, Inheritance mechanism is required.
Example
class A
{
void show( )
{
System.out.println(“hello”);
}
}
class B extends A
{
void show( )
{
System.out.println(“world”);
}
}
class C
{
public static void main(String args[ ])
{
B k=new B( );
A t=new A( );
k.show( );
t.show( );
}
}
Abstract Class
• If a class contains at least one abstract method then it becomes an abstract class.
• Method declared without any definition is known as abstract method.
• “abstract” keyword is used to declare abstract class.
• We cannot create the object of abstract class.
Example:
abstract class A
{
void show( );
}
class B extends A
{
void show( )
{
System.out.println(“world”);
}
}
class C
{
public static void main(String args[ ])
{
B k=new B( );
k.show( );
}
}
super:
• This keyword is used to invoke parent class constructor from the child class.
• It is used to pass arguments from the child class to the parent class.
• super( ) must be the first executable statement in the child class constructor.
Example:
class A
{
int x,y;
A( int i , int j)
{
x=i;
y=j;
}
}
class B extends A
{
int z;
{
super(i,j);
z=k;
}
void disp( )
{
System.out.println(x+y+z);
}
}
class C
{
public static void main(String args[ ])
{
B k=new B(10,20,30 );
k.disp( );
}
}
Interface
• It is a blue print of a class. It is similar to class.
• It is a specification which is completely implemented by a class.
• It contains only abstract methods and static constants.
• Here, the variables declared are “static” and “final”
• We cannot create the object of Interface.
Example:
public interface A
void name(String n)
System.out.println(n);
void dept(String d)
System.out.println(d);
void age(int a)
System.out.println(a);
B k=new B( );
k.name(“Ram”);
k.dept(“finance”);
k.age(30);
Abstract Class:
Interface:
Package :
Java provides large no. of packages but the following are commonly used:
• java.lang
• java.io
• java.awt
• java.applet
• java.net
• java.sql
• java.util
File-1
package Color;
System.out.println(“Red”);
File-2
package Color;
System.out.println(“Green”);
File-3
package Color;
System.out.println(“Blue”);
Implementation File
import Color.*;
class Pack
r.disp1( );
g.disp2( );
b.disp3( );
Array:
An array is the collection of similar types of data in continuous memory locations.
Types of Array:
• 1-D Array
• Multi-Dimensional Array (2-D,3-D,…)
1-D Array:
Create an Array:
Syntax:
datatype array-name[ ];
Example:
int a[ ];
Syntax:
Example:
a=new int[3];
Note:
int a[ ];
a=new int[3];
is similar to
Syntax:
Example:
int a[ ]={1,2,3,4,5};
2-D Array:
Create an Array:
Syntax:
datatype array-name[ ][ ];
Example:
int a[ ][ ];
Syntax:
Example:
a=new int[3][3];
Note:
int a[ ][ ];
a=new int[3][3];
is similar to
class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;
if ( n != p )
System.out.println("Matrices with entered orders can't be multiplied
with each other.");
else
{
int second[][] = new int[p][q];
int multiply[][] = new int[m][q];
multiply[c][d] = sum;
sum = 0;
}
}
System.out.print("\n");
}
}
}
}
class AddTwoMatrix
{
public static void main(String args[])
{
int m, n, c, d;
Scanner in = new Scanner(System.in);
System.out.println();
}
}
}
class TransposeAMatrix
{
public static void main(String args[])
{
int m, n, c, d;
System.out.print("\n");
}
}
}
String
• String class is available in java.lang package.
• This class provides methods to handle strings and characters.
String( )
Example:
String(“String” )
Example:
String(char a[ ] )
Example:
It is used to create a string object by taking the characters from the start index with specified no.
of characters.
Example:
length( ):
indexOf( ):
lastIndexOf( ):
concat( ):
toLowerCase( ):
toUpperCase( ):
substring( ):
replace( ):
charAt( ):
Example:
class Str
System.out.println(s1.indexOf(‘l’));
System.out.println(s1.lastIndexOf(‘l’));
System.out.println(s1.subString(4));
String s2=s1.toUpperCase( );
String s3=s1.toLowerCase( );
Multiple Threading
• A thread is a single sequential flow of control within a program. It is an independent path
of execution with in a program.
• Thread is basically a light weight sub-process,a smallest unit of processing.
• In multi threading, simultaneously multiple threads work and multiple programs can also
be executed at a time.
• Due to multi threading, we will be able to control the execution of threads using
Synchronization.
• To create multiple threads, java provides “Thread” class and “Runnable” interface.
System.out.println(“Thread”);
class Use1
k.start( );
System.out.println(“Thread1”);
System.out.println(“Thread2”);
class Use
t1.start( );
t2.start( );
NOTE:
Thread Priority
• Thread class provides methods and constants to set the priority of threads.
• It provides two methods getPriority( ) and setPriority( ) to know the priority of a
thread and to set the priority of thread.
• Thread class contains three constants to set the priority of thread which are given as
follows:
MAX_PRIORITY(value is 10)
MIN_PRIORITY(value is 1)
NORM_PRIORITY(value is 5)
Example:
System.out.println(“Thread1”);
System.out.println(“Thread2”);
System.out.println(“Thread3”);
class Use
t1.setPriority(Thread.MAX_PRIORITY);
t2.setPriority(6);
t3.setPriority(t2.getPriority( )+1);
t1.start( );
t2.start( );
t3.start( );
Steps:
Example:
System.out.println(“Thread”);
class Use1
t.start( );
Newborn state:
Runnable state
Suspended state
• When a thread is temporarily suspended due to input/output event or interrupts then the
thread goes to suspended state.
• After the condition of suspension is removed, the thread goes to ready state.
• If the condition of suspension is not removed then the thread goes to dead state.
Dead state
NOTE:
yield( ):
stop( ):
sleep( ):
Applet
• Java supports two types of application-stand alone based application and internet based
application
• Stand alone applications are also known as console based application.
• Internet based application is known as applet
Steps to create an applet:
Example:
import java.awt.*;
import java.applet.*;
g.drawString(“hello world”,10,100);
HTML File:
<html>
<body>
</applet>
</body>
</html>
• It uses Graphics class available in java.awt package and this class provides no. of
methods to draw 2-D shapes.
Example:
import java.awt.*;
import java.applet.*;
System.out.println(“initialized”);
System.out.println(“started”);
System.out.println(“painting”);
g.drawString(“My Applet”,10,100);
System.out.println(“stopping”);
System.out.println(“destroying”);
HTML File:
<html>
<body>
</applet>
</body>
</html>
Applet:
Application Program:
• It has main( ).
• To execute it, HTML tag may not be required.
Graphics class
It is used to draw geometrical shapes on the applet. It provides following methods:
drawRect( )
• This method is used to draw rectangle on the applet.
• It takes 4 parameters.
• The first 2 parameters indicate the coordinate of top left corner point.
• The last 2 parameters specifies length and width of rectangle.
• Example: g.drawRect(10,10,20,30);
drawRoundRect( )
• This method is used to draw rounded rectangle .
• It takes 6 parameters.
• The first 4 parameters are similar to the arguments of rectangle.
• The last 2 parameters specify the angle of corner of rectangle.
drawLine( )
• This method is used to draw a straight line.
• It takes 4 parameters.
• The first 2 parameters indicate coordinate of first point and last 2 parameters
indicate the coordinate of last point.
• Example: g.drawLine(10,10,70,70);
drawOval( )
• This method is used to draw an oval.
• When the last two parameters of this method are same ,it becomes a circle.
drawPolygon( )
• This method is used to draw a polygon.
• Java also provides a class known as Polygon to draw the polygon.
Example:
import java.awt.*;
import java.applet.*;
g.drawLine(20,20,90,90);
g.drawRect(20,70,90,90);
g.drawOval(20,20,200,120);
g.setColor(Color.Green);
g.fillOval(70,30,100,100);
g.drawRoundRect(10,100,80,50,10,10);
g.fillRoundRect(20,110,60,30,5,5);
Layout Manager
Layout manager specifies how components are organized in applet or frame. There are following
types of layout manager:
• Flow Layout
• Grid Layout
• Border Layout
• Grid bag Layout
• Card Layout
• Manual Layout
Flow Layout
Example:
import java.awt.*;
import java.applet.*;
setFont(new Font(“SansSerif”,Font.BOLD,32));
add(b1);
add(b2);
add(b3);
add(b4);
add(t1);
Component
Container
Panel
Applet
Window
• Java does not restrict to create a GUI application for console based java program as Panel
is the super class of internet based application.
• Similarly Window is the super class of console based java application.
Frame
• A Frame has border , title bar but without any menu bar.
Button
Label
TextField
TextArea
Example:
import java.awt.*;
import java.applet.*;
setFont(new Font(“SansSerif”,Font.BOLD,32));
add(“East”,b1);
add(“West”,b2);
add(“North”,b3);
add(“South”,b4);
add(“Center”,t1);
Exception
• It is a run time anomaly, upon occurrence the system shows abnormal behavior.
• It occurs due to execution of illegal instruction during run time.
• When exception occurs the program is aborted abnormally and the control returns to the
OS.
• Exceptions are broadly classified into:
▪ Checked Exception
▪ Unchecked Exception
Checked Exception:
• These are the exceptions which are checked by the compiler and program will
not execute unless this exceptions are handled.
• All exception except run time exception are checked exceptions.
Unchecked Exception:
• These are the exceptions which are not checked during compilation.
• Run time exceptions are unchecked exceptions.
NOTE:
Object:
Throwable:
• throws
• finally
try:
• The codes which are likely to generate exception are kept within try block.
• This block is used to detect exception.
• In java, when exception occurs an exception object is created.
catch:
• This block is used to handle the exception thrown by the try block.
• It provides the solution for the exception object received.
• For a try block, there must be a catch block.
• For a single try block, there can be any no. of catch block.
throw:
• This keyword is used to throw an exception object from a try block to catch block or from one
catch block to another catch block.
• When an exception is thrown from one catch block to another catch block, then it is known as
rethrowing an exception.
throws:
Example
class Exc
try
int x=10,y=0;
System.out.println(“result=”+(x/y));
class Exc
try
int x=Integer.parseInt(args[0]);
int y=Integer.parseInt(args[1]);
int z=x/y;
System.out.println(“result=”+z);
catch (NumberFormatException n)
catch (ArrayIndexOutOfBound a)
System.out.println(“give arguments”);
Example(Rethrowing an Exception):
class Thrw
try
int z=x/y;
System.out.println(“result=”+z);
throw a;
try
test(50,10);
test(50,0);
System.out.println(“Exception is caught”);
class Thrw
int z=x/y;
System.out.println(“result=”+z);
try
test(50,10);
test(50,0);
System.out.println(“Exception is caught”);
throw:
throws:
• For JDBC , the package “java.sql” provides the following classes and interfaces:
Connection:
• It is an interface used to establish connection with DBMS.
DriverManager:
• This class defines object which can connect java application to a JDBC driver.
PreparedStatement:
ResultSet
Steps:
Step-I:
• Load the class available for driver into the JRE by using forName() of java.lang
Step-II:
• Establish the connection with DBMS by using DNS, user-id, password of DBMS into
getConnection() of java.sql.DriverManager class.
• The getConnection() returns a reference of java.sql.Connection.
Step-III:
Example:
import java.sql.*;
import java.io.*;
class Conn
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
Connection con=DriverManager.getConnection(“jdbc:odbc:DSN”,”scott”,”tiger”);
Statement st=con.createStatement( );
While(rs.next( ))
System.out.println(rs.getInt(“empno”)+”:”+rs.getString(“ename”));
Con.close();
SWING:
• It is a set of packages built on top of AWT that provides you a number of prebuilt classes.
• Its package contents around 250 classes and 40 UI components.
• The swing components are part of JFC.
• The swing components are present in javax.swing package.
• Swing components are derived from JComponent class.
• JComponent inherits the AWT classes Container and Component.
• All component class start with letter J.
Swing Features
• Borders
• Easy mouseless operation
• Easy scrolling
• Pluggable look and feel
• Swing components are light weight
Example of Swing:
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
3) AWT doesn't support pluggable look and feel. Swing supports pluggable look and feel.
4) AWT provides less components than Swing. Swing provides more powerful
componentssuch as tables, lists,
scrollpanes, colorchooser, tabbedpane
etc.
• Model - Model represents an object or JAVA POJO carrying data. It can also have logic
to update controller if its data changes.
• View - View represents the visualization of the data that model contains.
• Controller - Controller acts on both model and view.
• It allows a java object that executes on one machine to invoke a method of a java object that
executes on another machine.
• The RMI system consists of three layers : The stub/skeleton layer, The remote reference layer, the
transport layer.
Packages of RMI
• java.rmi
• java.rmi.registry
• java.rmi.server
• java.rmi.activation
EXAMPLE:
1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }
In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder{
AdderRemote()throws RemoteException{
super();
}
public int add(int x,int y){return x+y;}
}
3) create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes the RMI compiler
and creates stub and skeleton objects.
rmic AdderRemote
rmiregistry 5000
In this example, we are binding the remote object by the name sonoo.
import java.rmi.*;
import java.rmi.registry.*;
public class MyServer{
public static void main(String args[]){
try{
Adder stub=new AdderRemote();
Naming.rebind("rmi://localhost:5000/sonoo",stub);
}catch(Exception e){System.out.println(e);}
}
}
import java.rmi.*;
public class MyClient{
public static void main(String args[]){
try{
Adder stub=(Adder)Naming.lookup("rmi://localhost:5000/sonoo");
System.out.println(stub.add(34,4));
}catch(Exception e){}
}
}
JAVA NETWORKING:
• Java Networking is a concept of connecting two or more computing devices together so that we
can share resources. Java socket programming provides facility to share data between different
computing devices.
• The java.net package provides support for the two common network protocols − TCP − TCP
stands for Transmission Control Protocol, which allows for reliable communication between two
applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
• The term network programming refers to writing programs that execute across multiple
devices (computers), in which the devices are all connected to each other using a network.
The java.net package provides support for the two common network protocols −
• TCP − TCP stands for Transmission Control Protocol, which allows for reliable communication
between two applications. TCP is typically used over the Internet Protocol, which is referred to as
TCP/IP.
• UDP − UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of
data to be transmitted between applications.
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
6. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range
from 0 to 255.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication endpoint between
applications.
The port number is associated with the IP address for communication between two applications.
4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network Interface Controller). A network node
can have multiple NIC but each with unique MAC.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but fast. The
example of connection-less protocol is UDP.
6) Socket
A socket is an endpoint between two way communication.
• Java Socket programming is used for communication between the applications running on different JRE.
• Java Socket programming can be connection-oriented or connection-less.
• Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
• Sockets provide the communication mechanism between two computers using TCP. A client
program creates a socket on its end of the communication and attempts to connect that socket to a
server. When the connection is made, the server creates a socket object on its end of the
communication.
1. IP Address of Server
2. Port number.
Socket class
A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a
socket.
ServerSocket class
The ServerSocket class can be used to create a server socket. This object is used to establish communication with
the clients.
java socket programming in which client sends a text and server receives it:
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
In this example, client will write first to the server then server will receive and print the text. Then server will write
to the client and client will receive and print the text. The step goes on.
File: MyServer.java
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}}
File: MyClient.java
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}
dout.close();
s.close();
}}
JavaFX:
• JavaFX is a software platform for creating and delivering desktop applications, as well as
rich internet applications (RIAs) that can run across a wide variety of devices.
• JavaFX is intended to replace Swing as the standard GUI library for Java SE, but both
will be included for the foreseeable future.
• JavaFX is a set of graphics and media packages that enables developers to design, create,
test, debug, and deploy rich client applications that operate consistently across diverse
platforms.