0% found this document useful (0 votes)
15 views75 pages

Oopj Digital Note@kkj-1

The document is a comprehensive digital note on Object-Oriented Programming using Java, designed for a course by Mr. Kalyan Kumar Jena. It covers various modules including an introduction to programming, Java basics, classes and objects, inheritance, data abstraction, multithreading, and GUI development with Swing and JavaFX. Additionally, it provides examples of Java programs, data types, operators, control structures, and the features of Object-Oriented Programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views75 pages

Oopj Digital Note@kkj-1

The document is a comprehensive digital note on Object-Oriented Programming using Java, designed for a course by Mr. Kalyan Kumar Jena. It covers various modules including an introduction to programming, Java basics, classes and objects, inheritance, data abstraction, multithreading, and GUI development with Swing and JavaFX. Additionally, it provides examples of Java programs, data types, operators, control structures, and the features of Object-Oriented Programming.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 75

JAVA PROGRAMMING

OBJECT ORIENTED PROGRAMMIMG USING JAVA


DIGITAL NOTE
Designed by:
Mr. Kalyan Kumar Jena
Assistant Professor
Dept. of CSE
PMEC,BERHAMPUR

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

5TH SEMESTER,CSE Page 1


JAVA PROGRAMMING

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.

5TH SEMESTER,CSE Page 2


JAVA PROGRAMMING

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

Simple program in Java


Program to display “hello world” in java using notepad and command prompt:

Open notepad and write the following code:

class First
{
public static void main(String args[ ])
{
System.out.println(“Hello World”);
}
}

Saving a Java program:


The file must be saved with the same name as the class name. So ,the above program must be
save as “First.java”

Compilation and Execution/Run of Java program:

In command Prompt perform the following operations:

Compilation: javac First.java

5TH SEMESTER,CSE Page 3


JAVA PROGRAMMING

Execution/Run: java First

Rules for writing a Java Program:


i. Java is case sensitive
ii. Class name should begin with capital letter
iii. Function name should begin with small letter
iv. If the class name consists of multiple words then the first letter of each word is capital
v. If the method name consists of multiple words then except the first word ,the first letter
of remaining words are capital

JVM (Java Virtual Machine)


Java Program ( a.java) ----- javac(compiler)----Byte Code(a.class)-----Java(Interpreter)---
Machine code

• 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

Data Types in Java:

(Datatype specifies the type of data a variable holds)

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)

5TH SEMESTER,CSE Page 4


JAVA PROGRAMMING

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

NOTE: Why char takes 2 bytes in Java?


• Java uses Unicode system to represent a character.
• Unicode system represents character of many international languages.
• ASCII character takes 1 byte. But Unicode character takes 2 bytes.
• In Unicode system, we can represent characters of different languages like Chinese,
Japanese, French, Dutch etc.

Program to display the addition result of two numbers 10 and 20 :

class Add
{
public static void main(String args[ ])
{
int a=10,b=20;
System.out.println(“The Sum=”+(a+b));
}
}
Compilation: javac Add.java

Execution/Run: java Add

5TH SEMESTER,CSE Page 5


JAVA PROGRAMMING

Program to display the addition result of any two integers :

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

Execution/Run: java Add 10 20

Note: int x=Integer.parseInt(args[0]);

• 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[ ]

Operators used in Java:


• Arithmetic Operators (+, - , * , / , %)
• Relational Operators (< , <= , > , >= , != )
• Logical Operators (&& , || , ! )
• Comparison Operator( = = )
• Assignment Operator( = )
• Increment Operator(++) and Decrement Operator(--)

5TH SEMESTER,CSE Page 6


JAVA PROGRAMMING

• 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

2.Write the Output for the following segment:


class Test
{
public static void main(String args[ ])
{
int a,b,c,d,e,f,g,h=0;
g=h++;
f=g++;
e=f++;
d=e++;
c=d++;
b=c++;
a=b++;
System.out.println(a);
}
}
Output:0

Decisions in Java
If Statements:

• Simple if statement
• if-else statement
• Ladder else-if statement
• Nested if statement

Simple if statement

5TH SEMESTER,CSE Page 7


JAVA PROGRAMMING

• It is one way control statement.

Syntax:
if ( condition)
{
Statement;
}

if-else statement

• It is two way control statement.

Syntax:
if (condition)
{
Statement;
}
else
{
Statement;
}

Ladder else-if statement

• It is multi way control statement.

Syntax:
if ( condition)
{
Statement;
}
else if ( condition)
{
Statement;
}
else if ( condition)
{
Statement;
}
….
….
….
….
Nested if-else statement

5TH SEMESTER,CSE Page 8


JAVA PROGRAMMING

• 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;
}

5TH SEMESTER,CSE Page 9


JAVA PROGRAMMING

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;
}

5TH SEMESTER,CSE Page 10


JAVA PROGRAMMING

OBJECT ORIENTED PROGRAMMING IN JAVA


Features of Object Oriented Programming
• Class
• Object
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
• Dynamic Binding
• Delegation
• Message Passing
Class:

• It is the collection of similar objects having common behavior and properties.


• It is a framework/template using which objects are created.

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:

• Polymorphism comes from the word poly(many) and morphous(forms).


• It is the process in which the same entity behaves differently with different situations.

5TH SEMESTER,CSE Page 11


JAVA PROGRAMMING

Dynamic Binding:

• It is the process of connecting one program to another that is to be executed in reply to a


call.

Delegation:

• When the object of one class will act as the data member in another class then it is known
as delegation.

Message Passing:

• The communication between the objects is known as message passing.

Programming using class and object concept:

A class is an user defined data type which is the collection of dissimilar types of data and
functions.

Syntax:

[Access Specifier] [Access Modifier] class classname

Variables;

Methods;

Example:

class Student

int roll;

int age;

int mark;

void display( )

5TH SEMESTER,CSE Page 12


JAVA PROGRAMMING

….

…..

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.

5TH SEMESTER,CSE Page 13


JAVA PROGRAMMING

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:

final int x = 10;

The value of x cannot be changed during program execution.

Syntax to create the object of class:

class-name object-name = new class-name( );

Example:

Student k = new Student( );

Write a program to display “Hello World” using class

class Smpl

void display( )

5TH SEMESTER,CSE Page 14


JAVA PROGRAMMING

System.out.println(“Hello World”);

class Smpl1

public static void main(String args[ ])

Smpl k = new Smpl( );

k.display( );

Compile:javac Smpl1.java

Run: java Smpl1

Write a program to add two numbers using class

class Add

int a,b;

void display(int i,int j )

a=i;

b=j;

System.out.println(“The Sum=”+(a+b));

class Add1

5TH SEMESTER,CSE Page 15


JAVA PROGRAMMING

public static void main(String args[ ])

int m=Integer.parseInt(args[0]);

int n=Integer.parseInt(args[1]);

Add k = new Add( );

k.display( m,n);

Compile:javac Add1.java

Run: java Add1 10 20

Write a program to display employee no=1 and employee age=25 using class

class Emp

int n,a;

void display(int i,int j )

n=i;

a=j;

System.out.println(“The Employee no=”+n);

System.out.println(“The Employee age=”+a);

class Emp1

5TH SEMESTER,CSE Page 16


JAVA PROGRAMMING

public static void main(String args[ ])

Emp k = new Emp( );

k.display( 1,25);

Compile:javac Emp1.java

Run: java Emp1

Write a program to display the student name, roll no and age of a student using class

class Student

String n;

int r,a;

void accept(String i , int j , int k)

n=i;

r=j;

a=k;

void display( )

System.out.println(“The Name=”+n);

System.out.println(“The Roll no=”+r);

System.out.println(“The Age=”+a);

5TH SEMESTER,CSE Page 17


JAVA PROGRAMMING

class Student1

public static void main(String args[ ])

String z=args[0];

int m=Integer.parseInt(args[1]);

int n=Integer.parseInt(args[2]);

Student k = new Student( );

k.accept(z,m,n);

k.display( );

Compile:javac Student1.java

Run: java Student1 Ram 1 19

Static Members
Static members can be

• static data member


• static method
• static block

Static data member

• 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.

5TH SEMESTER,CSE Page 18


JAVA PROGRAMMING

• 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();

5TH SEMESTER,CSE Page 19


JAVA PROGRAMMING

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.

5TH SEMESTER,CSE Page 20


JAVA PROGRAMMING

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

When a constructor accepts some argument/parameter then it is known as 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:

Java does not support destructor.

Example of Constructor (Default,Parameterized,Copy)

class Use

5TH SEMESTER,CSE Page 21


JAVA PROGRAMMING

int a,b;

Use( ) ---------------Default Constructor

a=4;

b=9;

System.out.println(a+ “ “ +b);

Use(int i , int j) ------------------- Parameterized Constructor

a=i;

b=j;

System.out.println(a+ “ “+ b);

Use(Use k) ------------Copy Constructor

a=k.a;

b=k.b;

System.out.println(a+ “ “+ b);

class Use1

public static void main( String args[])

Use k = new Use();

Use m = new Use(5,7);

Use z=new Use (m);

5TH SEMESTER,CSE Page 22


JAVA PROGRAMMING

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;

void display( int i)

a=i;

System.out.println(a);

void display(int i , int j)

a=i;

b=j;

System.out.println(a+ “ “+ b);

class Use1

public static void main(String args[] )

5TH SEMESTER,CSE Page 23


JAVA PROGRAMMING

Use k = new Use();

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.

5TH SEMESTER,CSE Page 24


JAVA PROGRAMMING

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( );
}
}

5TH SEMESTER,CSE Page 25


JAVA PROGRAMMING

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( );
}
}

5TH SEMESTER,CSE Page 26


JAVA PROGRAMMING

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.

5TH SEMESTER,CSE Page 27


JAVA PROGRAMMING

Example:
class A
{
int x,y;
A( int i , int j)
{
x=i;
y=j;
}
}
class B extends A
{
int z;

B(int i,int j,int k )

{
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( );
}
}

5TH SEMESTER,CSE Page 28


JAVA PROGRAMMING

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);

void dept(String d);

void age(int a);

public class B implements A

void name(String n)

System.out.println(n);

void dept(String d)

System.out.println(d);

void age(int a)

5TH SEMESTER,CSE Page 29


JAVA PROGRAMMING

System.out.println(a);

public static void main(String args[ ])

B k=new B( );

k.name(“Ram”);

k.dept(“finance”);

k.age(30);

Difference between Abstract class and Interface:

Abstract Class:

• It contains abstract as well as non abstract methods.


• To use abstract class,extends keywords is used.
• It can have constructors.
• Variables declared may not be final and static.

Interface:

• It contains only abstract methods.


• To use interface, implements keywords is used.
• It does not have any constructor.
• Variables declared have to be final and static.

5TH SEMESTER,CSE Page 30


JAVA PROGRAMMING

Package :

• Package is a container where classes and interfaces are stored.


• We can have classes with same name in two different packages.
• Java supports predefined as well as user defined packages.
Pre-defined 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

Creating user defined package:

Suppose package name is Color.

File-1

package Color;

public class Red

public void disp1( )

System.out.println(“Red”);

File-2

package Color;

5TH SEMESTER,CSE Page 31


JAVA PROGRAMMING

public class Green

public void disp2( )

System.out.println(“Green”);

File-3

package Color;

public class Blue

public void disp3( )

System.out.println(“Blue”);

Implementation File

import Color.*;

class Pack

Public static void main(String args[ ])

Red r=new Red( );

Green g=new Green( );

5TH SEMESTER,CSE Page 32


JAVA PROGRAMMING

Blue b=new Blue( );

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:

• Declaring the array


• Creating memory allocation

Declaring the array:

Syntax:

datatype array-name[ ];

Example:

int a[ ];

Creating memory allocation:

Syntax:

array-name=new datatype [size];

Example:

5TH SEMESTER,CSE Page 33


JAVA PROGRAMMING

a=new int[3];

Note:

int a[ ];

a=new int[3];

is similar to

int a[ ]=new int[3];

Initialization of 1-D array

Syntax:

datatype arrayname[ ]={list of items};

Example:

int a[ ]={1,2,3,4,5};

Multi-Dimensional Array (2-D,3-D,…):

2-D Array:

Create an Array:

• Declaring the array


• Creating memory allocation

Declaring the array:

Syntax:

datatype array-name[ ][ ];

Example:

int a[ ][ ];

Creating memory allocation:

Syntax:

array-name=new datatype [size][size];

5TH SEMESTER,CSE Page 34


JAVA PROGRAMMING

Example:

a=new int[3][3];

Note:

int a[ ][ ];

a=new int[3][3];

is similar to

int a[ ][ ]=new int[3][3];

Program for matrix multiplication:


import java.util.Scanner;

class MatrixMultiplication
{
public static void main(String args[])
{
int m, n, p, q, sum = 0, c, d, k;

Scanner in = new Scanner(System.in);


System.out.println("Enter the number of rows and columns of first
matrix");
m = in.nextInt();
n = in.nextInt();

int first[][] = new int[m][n];

System.out.println("Enter the elements of first matrix");

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
first[c][d] = in.nextInt();

System.out.println("Enter the number of rows and columns of second


matrix");
p = in.nextInt();
q = in.nextInt();

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];

System.out.println("Enter the elements of second matrix");

for ( c = 0 ; c < p ; c++ )

5TH SEMESTER,CSE Page 35


JAVA PROGRAMMING
for ( d = 0 ; d < q ; d++ )
second[c][d] = in.nextInt();

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < q ; d++ )
{
for ( k = 0 ; k < p ; k++ )
{
sum = sum + first[c][k]*second[k][d];
}

multiply[c][d] = sum;
sum = 0;
}
}

System.out.println("Product of entered matrices:-");

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < q ; d++ )
System.out.print(multiply[c][d]+"\t");

System.out.print("\n");
}
}
}
}

Program for matrix addition:


import java.util.Scanner;

class AddTwoMatrix
{
public static void main(String args[])
{
int m, n, c, d;
Scanner in = new Scanner(System.in);

System.out.println("Enter the number of rows and columns of matrix");


m = in.nextInt();
n = in.nextInt();

int first[][] = new int[m][n];


int second[][] = new int[m][n];
int sum[][] = new int[m][n];

System.out.println("Enter the elements of first matrix");

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
first[c][d] = in.nextInt();

5TH SEMESTER,CSE Page 36


JAVA PROGRAMMING

System.out.println("Enter the elements of second matrix");

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
second[c][d] = in.nextInt();

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
sum[c][d] = first[c][d] + second[c][d]; //replace '+' with '-'
to subtract matrices

System.out.println("Sum of entered matrices:-");

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < n ; d++ )
System.out.print(sum[c][d]+"\t");

System.out.println();
}
}
}

Program for matrix Transpose:


import java.util.Scanner;

class TransposeAMatrix
{
public static void main(String args[])
{
int m, n, c, d;

Scanner in = new Scanner(System.in);


System.out.println("Enter the number of rows and columns of matrix");
m = in.nextInt();
n = in.nextInt();

int matrix[][] = new int[m][n];

System.out.println("Enter the elements of matrix");

for ( c = 0 ; c < m ; c++ )


for ( d = 0 ; d < n ; d++ )
matrix[c][d] = in.nextInt();

int transpose[][] = new int[n][m];

for ( c = 0 ; c < m ; c++ )


{
for ( d = 0 ; d < n ; d++ )
transpose[d][c] = matrix[c][d];
}

5TH SEMESTER,CSE Page 37


JAVA PROGRAMMING

System.out.println("Transpose of entered matrix:-");

for ( c = 0 ; c < n ; c++ )


{
for ( d = 0 ; d < m ; d++ )
System.out.print(transpose[c][d]+"\t");

System.out.print("\n");
}
}
}

5TH SEMESTER,CSE Page 38


JAVA PROGRAMMING

String
• String class is available in java.lang package.
• This class provides methods to handle strings and characters.

Constructors supported by String class :

String( )

It is used to create empty string object.

Example:

String s=new String( );

String(“String” )

It is used to create a string object with specified string.

Example:

String s=new String(“hello” );

String(char a[ ] )

It is used to create a string object from array of characters.

Example:

Char a[ ]={‘a’ , ‘b’ , ‘c’ , ‘d’};

String s=new String(a);

String(char a[ ], starting position,no. of characters)

It is used to create a string object by taking the characters from the start index with specified no.
of characters.

Example:

Char a[ ]={‘a’ , ‘b’ , ‘c’ , ‘d’};

String s=new String(a,1,2);

Functions/Methods of String class:

5TH SEMESTER,CSE Page 39


JAVA PROGRAMMING

length( ):

It returns the no. of characters stored in a string object.

indexOf( ):

It returns the position of first occurrence of a character in a string.

lastIndexOf( ):

It returns the position of last occurrence of a character in a string.

concat( ):

It creates a new string by concatenating two strings.

toLowerCase( ):

It converts a string into lower case.

toUpperCase( ):

It converts a string into upper case.

substring( ):

It extracts a sub string from a given string.

replace( ):

It replaces a string with specified string.

charAt( ):

It returns the character specified by position no.

Example:

class Str

public static void main(String args[ ])

String s1=new String(“Hello World”);

System.out.println(s1.indexOf(‘l’));

5TH SEMESTER,CSE Page 40


JAVA PROGRAMMING

System.out.println(s1.lastIndexOf(‘l’));

System.out.println(s1.subString(4));

String s2=s1.toUpperCase( );

String s3=s1.toLowerCase( );

System.out.println(s1+ “ “ +s2+ “ “+s3);

5TH SEMESTER,CSE Page 41


JAVA PROGRAMMING

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.

Program for execution of a thread

class Use extends Thread

public void run( )

System.out.println(“Thread”);

class Use1

public static void main(String args[ ])

Use k=new Use( );

k.start( );

5TH SEMESTER,CSE Page 42


JAVA PROGRAMMING

Program for execution of multiple thread

class Use1 extends Thread

public void run( )

System.out.println(“Thread1”);

class Use2 extends Thread

public void run( )

System.out.println(“Thread2”);

class Use

public static void main(String args[ ])

Use1 t1=new Use1( );

t1.start( );

Use2 t2=new Use2( );

t2.start( );

5TH SEMESTER,CSE Page 43


JAVA PROGRAMMING

NOTE:

• start( ) and run( ) are the methods of Thread class.


• In a java program, there is at least one thread known as main thread. The child thread can
be created using Thread class.
• The program execution always starts from main thread. The main thread sends signal to
the child thread to execute the child thread using start( ).
• The start( ) automatically invokes the run( ).

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:

class Use1 extends Thread

public void run( )

System.out.println(“Thread1”);

class Use2 extends Thread

public void run( )


5TH SEMESTER,CSE Page 44
JAVA PROGRAMMING

System.out.println(“Thread2”);

class Use3 extends Thread

public void run( )

System.out.println(“Thread3”);

class Use

public static void main(String args[ ])

Use1 t1=new Use1( );

Use2 t2=new Use2( );

Use3 t3=new Use3( );

t1.setPriority(Thread.MAX_PRIORITY);

t2.setPriority(6);

t3.setPriority(t2.getPriority( )+1);

t1.start( );

t2.start( );

5TH SEMESTER,CSE Page 45


JAVA PROGRAMMING

t3.start( );

Creating a thread using Runnable Interface

Steps:

I. Create a class by implementing the Runnable interface.


II. Create an object of the class which has implemented the Runnable interface.
III. Create an object of Thread class and pass the object created in step-II as an
argument to the thread class constructor.
IV. Invoke the start( ) using Thread class object.

Example:

class Use implements Runnable

public void run( )

System.out.println(“Thread”);

class Use1

public static void main(String args[ ])

Use k=new Use( );

Thread t=new Thread(k);

5TH SEMESTER,CSE Page 46


JAVA PROGRAMMING

t.start( );

Life Cycle of Thread

The thread life cycle has following states:


• Newborn state
• Runnable state
• Suspended state
• Dead state

Newborn state:

• When a thread is created it is in the newborn state.


• In this state the thread doesnot have any resources.

Runnable state

• When a process is in runnable state, it has two states-ready and run.


• In ready state, the thread has all resources except the processor.
• In run state, the thread has processor along with all resources.

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

• A thread is in dead state when it is completely executed.

NOTE:

yield( ):

• It is used to relinquish the control voluntarily to other thread.

5TH SEMESTER,CSE Page 47


JAVA PROGRAMMING

stop( ):

• It is used to kill a thread.

sleep( ):

• It is used to de-active a thread for specific millisecond.

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:

I.Import java.applet package


II.Import java.awt package
III.Create a class by inheriting from Applet class.
IV. Provide the paint( ) in order to draw string, shapes, graphically user components etc.
in the applet
V. Create an HTML file and provide the applet tag.
VI. Execute the applet using appletviewer or any web browser.

Example:

import java.awt.*;

import java.applet.*;

public class Ause extends Applet

public void paint(Graphics g)

g.drawString(“hello world”,10,100);

5TH SEMESTER,CSE Page 48


JAVA PROGRAMMING

HTML File:

<html>

<body>

<applet code=”Ause.class” width=300 height=300>

</applet>

</body>

</html>

Applet Life Cycle


The applet life cycle consists of following methods:
• public void init( )
• public void start( )
• public void paint(Graphics g)
• public void stop( )
• public void destroy( )

public void init( )

• It is used to initialize an applet.


• Applet is created using this method.
• init( ) automatically invokes start( ).

public void start( )

• It is used to start the execution of an applet.


• start( ) is similar to main( ) in a standalone application.
• As main( ) is used to begin the execution of a java program, similarly start( ) is
used to begin the execution of an applet.
• In applet life cycle, the init( ) is called only once, whereas start( ) is called many
times.
• start( ) is automatically called when refresh button is clicked. It is also called
when we click maximize button.

public void paint(Graphics g)

• It is used to draw GUI components such as buttons, labels etc.


• It is used to draw 2-D shapes like oval, rectangle, circle, polygon etc.

5TH SEMESTER,CSE Page 49


JAVA PROGRAMMING

• It uses Graphics class available in java.awt package and this class provides no. of
methods to draw 2-D shapes.

public void stop( )

• It is used to stop execution of an applet.


• It is automatically invoked when minimize button is clicked.

public void destroy( )

• It is called to unload the applet from the memory.


• It is also called only once within life cycle of an applet.

Example:

import java.awt.*;

import java.applet.*;

public class Alife extends Applet

public void init( )

System.out.println(“initialized”);

public void start( )

System.out.println(“started”);

public void paint(Graphics g)

System.out.println(“painting”);

g.drawString(“My Applet”,10,100);

5TH SEMESTER,CSE Page 50


JAVA PROGRAMMING

public void stop( )

System.out.println(“stopping”);

public void destroy( )

System.out.println(“destroying”);

HTML File:

<html>

<body>

<applet code=”Alife.class” width=300 height=300>

</applet>

</body>

</html>

Difference between Applet and Application Program:

Applet:

• It does not have main( ).


• To execute applet, HTML tag is required.
• It cannot access the file system of a machine.
• It does not have access to native library.
• It is an internet based application.

Application Program:

• It has main( ).
• To execute it, HTML tag may not be required.

5TH SEMESTER,CSE Page 51


JAVA PROGRAMMING

• It can interact with the file system.


• It can access native library.
• It is a standalone program.

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.*;

public class Use extends Applet

5TH SEMESTER,CSE Page 52


JAVA PROGRAMMING

public void paint(Graphics g)

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

• It is the default layout for applet.


• Here the GUI components are arranged from top left corner to the right bottom corner.
• To create Flow Layout the following syntax is used:
FlowLayout f=new FlowLayout( );
f.setLayout( );
or
setLayout(new FlowLatout( ));

5TH SEMESTER,CSE Page 53


JAVA PROGRAMMING

Example:

import java.awt.*;

import java.applet.*;

public class Flow extends Applet

public void init( )

setLayout(new FlowLayout( ));

setFont(new Font(“SansSerif”,Font.BOLD,32));

Button b1=new Button (“ok”);

Button b2=new Button (“cancel”);

Button b3=new Button (“abort”);

Button b4=new Button (“retry”);

TextArea t1=new TextArea(5,5);

add(b1);

add(b2);

add(b3);

add(b4);

add(t1);

5TH SEMESTER,CSE Page 54


JAVA PROGRAMMING

Abstract Window Toolkit (AWT)


• Java provides a package known as java.awt which is used to draw GUI components on
an applet

Some classes of AWT :

Component

• It is an abstract class which encapsulates all functionality of a visual component


• The other components are derived from this class.

Container

• It is an abstract class which provides a rectangular area.


• It can contain other component or other container in it. But a component cannot contain a
container.

Panel

• It is a concrete sub class of container.


• When an applet is visible on the browser , actually first the Panel is drawn on the browser
and above it the applet is drawn.
• A Panel does not have title bar, menu bar or border.

Applet

• It is direct sub class of Panel.


• It is used as a container for the internet based java application.
• An applet does not have any menu bar or title bar. It uses the menu bar and title bar of the
browser.

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

• For console based java application, Frame is the super class.


• It provides a container for standalone application.

5TH SEMESTER,CSE Page 55


JAVA PROGRAMMING

• A Frame has border , title bar but without any menu bar.

Button

• It is a component which can be clicked by mouse.


• To create button, Button class is used
• Example: Button b=new Button(“OK”);

Label

• It is used to create a button with specified label.


• Example: Lable b=new Lable(“enter pin”);

TextField

• It is used to create textbox which are used to accept input.


• Example: TextField t1=new TextField(20); TextField t2=new TextField(“hello”);

TextArea

• It is used to create multiline text fields.


• It accepts multiple lines of text and it is also by default provided with scroll bars.
• Example: TextArea t=new TextArea(“hello”,5,10);

Example:

import java.awt.*;

import java.applet.*;

public class Brder extends Applet

public void init( )

setLayout(new BorderLayout( ));

setFont(new Font(“SansSerif”,Font.BOLD,32));

5TH SEMESTER,CSE Page 56


JAVA PROGRAMMING

Button b1=new Button (“ok”);

Button b2=new Button (“cancel”);

Button b3=new Button (“abort”);

Button b4=new Button (“retry”);

TextArea t1=new TextArea(5,5);

add(“East”,b1);

add(“West”,b2);

add(“North”,b3);

add(“South”,b4);

add(“Center”,t1);

5TH SEMESTER,CSE Page 57


JAVA PROGRAMMING

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:

• This is the super class of all classes.


• If a class is not inherited from any class then its super class is Object.

Throwable:

• This is the super class of all exception classes.


• Under Throwable, we have error and exception class.
• Java does not provide any mechanism to handle error.
• But exceptions are handled in java.

Handling the Exceptions:


Java provides the following keywords for exception handling:
• try
• catch
• throw

5TH SEMESTER,CSE Page 58


JAVA PROGRAMMING

• 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:

• This keyword is used to handle the exception without try-catch block.

Example

class Exc

public static void main(String args[ ])

try

int x=10,y=0;

System.out.println(“result=”+(x/y));

5TH SEMESTER,CSE Page 59


JAVA PROGRAMMING

catch (ArithmeticException ac)

System.out.println(“Denominator must be non-zero”);

Handling Multiple Exceptions:

• For a single try block we can provide multiple catch blocks.

class Exc

public static void main(String args[ ])

try

int x=Integer.parseInt(args[0]);

int y=Integer.parseInt(args[1]);

int z=x/y;

System.out.println(“result=”+z);

catch (ArithmeticException ac)

System.out.println(“Denominator must be non-zero”);

catch (NumberFormatException n)

5TH SEMESTER,CSE Page 60


JAVA PROGRAMMING

System.out.println(“provide integer data”);

catch (ArrayIndexOutOfBound a)

System.out.println(“give arguments”);

Example(Rethrowing an Exception):

class Thrw

public static void test(int x, int y)

try

int z=x/y;

System.out.println(“result=”+z);

catch (ArithmeticException ac)

System.out.println(“Denominator must be non-zero”);

throw a;

public static void main(String args[])

5TH SEMESTER,CSE Page 61


JAVA PROGRAMMING

try

test(50,10);

test(50,0);

catch (ArithmeticException ac)

System.out.println(“Exception is caught”);

Example (use of throws)

class Thrw

public static void test(int x, int y) throws ArithmeticException,NumberFormatException

int z=x/y;

System.out.println(“result=”+z);

public static void main(String args[])

try

test(50,10);

test(50,0);

5TH SEMESTER,CSE Page 62


JAVA PROGRAMMING

catch (ArithmeticException ac)

System.out.println(“Exception is caught”);

Difference between throw and throws:

throw:

• It is used to propagate the exception after handling it.


• It requires try and catch block to handle the exception.
• For each and every exception we get a separate catch block i. e. to handle multiple
exception that no. of catch block is required.

throws:

• It is used to propagate the exception to the caller without handling it.


• It does not require try and catch block to handle the exception.
• More than one exceptions can be specified without try and catch block.

5TH SEMESTER,CSE Page 63


JAVA PROGRAMMING

Java Database Connectivity (JDBC)

• For a JDBC application ,java provides a package known as java.sql


• For connecting a java program to a database, a middle layer is used known as drivers.
• Drivers establish the communication/connection from a java program to the DBMS.
• There are generally following types of driver:

➢ Type-I Driver (JDBC-ODBC Bridge Driver)


➢ Type-II Driver (Native-API Driver)
➢ Type-III Driver (Network-Protocol Driver)
➢ Type-IV Driver (Thin Driver)

• 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:

• This interface provides facility to execute sql by accepting parameters.


CallableStatement
• This interface provides facility to execute procedures/functions of DBMS.

ResultSet

• This interface is used to contain the data retrieved from DBMS.

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.

5TH SEMESTER,CSE Page 64


JAVA PROGRAMMING

Step-III:

• Create an object of java.sql.Statement to execute required sql through it.


• Object of statement can be created by using createStatement() of Connection.

Example:

import java.sql.*;

import java.io.*;

class Conn

public static void main(String args[])

Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

Connection con=DriverManager.getConnection(“jdbc:odbc:DSN”,”scott”,”tiger”);

Statement st=con.createStatement( );

Resultset rs=st.executeQuery(“select * from Emp”);

While(rs.next( ))

System.out.println(rs.getInt(“empno”)+”:”+rs.getString(“ename”));

Con.close();

5TH SEMESTER,CSE Page 65


JAVA PROGRAMMING

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

JButton b=new JButton("click");//creating instance of JButton


b.setBounds(130,100,100, 40);//x axis, y axis, width, height

f.add(b);//adding button in JFrame

f.setSize(400,500);//400 width and 500 height


f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
}

5TH SEMESTER,CSE Page 66


JAVA PROGRAMMING

Difference between JAVA AWT AND JAVA SWING:

No. Java AWT Java Swing

1) AWT components are platform-dependent. Java swing components are platform-


independent.

2) AWT components are heavyweight. Swing components are lightweight.

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.

5) AWT doesn't follows MVC(Model View Controller) Swing follows MVC.


where model represents data, view represents presentation
and controller acts as an interface between model and
view.

MVC (MODEL VIEW CONTROLLER) Architecture:

• It is the heart of swing UI Components.


• The model of a component is where the component’s data is stored.

• 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.

RMI(REMOTE METHOD INVOCATION):

• 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.

5TH SEMESTER,CSE Page 67


JAVA PROGRAMMING

Packages of RMI

• java.rmi
• java.rmi.registry
• java.rmi.server
• java.rmi.activation

Steps involved in creating and registering a remote object:

1. Create remote interface.


2. Create a class that implements the remote interface.
3. Create the stub and skeleton classes.
4. Copy the remote interface and stub file to the client.
5. Create and register the remote object.

EXAMPLE:

1) create the remote interface


For creating the remote interface, extend the Remote interface and declare the
RemoteException with all the methods of the remote interface. Here, we are creating a
remote interface that extends the Remote interface. There is only one method named add()
and it declares RemoteException.

1. import java.rmi.*;
2. public interface Adder extends Remote{
3. public int add(int x,int y)throws RemoteException;
4. }

2) Provide the implementation of the remote interface


Now provide the implementation of the remote interface. For providing the implementation of the Remote
interface, we need to

Either extend the UnicastRemoteObject class,

or use the exportObject() method of the UnicastRemoteObject class

In case, you extend the UnicastRemoteObject class, you must define a constructor that declares
RemoteException.

5TH SEMESTER,CSE Page 68


JAVA PROGRAMMING

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

4) Start the registry service by the rmiregistry tool


Now start the registry service by using the rmiregistry tool. If you don't specify the port number, it uses a
default port number. In this example, we are using the port number 5000.

rmiregistry 5000

5) Create and run the server application


Now rmi services need to be hosted in a server process. The Naming class provides methods to get and store the
remote object. The Naming class provides 5 methods.

public static java.rmi.Remote lookup(java.lang.String) throws java.rmi.NotBoundException,


java.net.MalformedURLException, java.rmi.RemoteException; it returns the reference of the remote object.

public static void bind(java.lang.String, java.rmi.Remote) throws java.rmi.AlreadyBoundException,


java.net.MalformedURLException, java.rmi.RemoteException; it binds the remote object with the given name.

public static void unbind(java.lang.String) throws java.rmi.RemoteException, java.rmi.NotBoundException,


java.net.MalformedURLException; it destroys the remote object which is bound with the given name.

public static void rebind(java.lang.String, java.rmi.Remote) throws java.rmi.RemoteException,


java.net.MalformedURLException; it binds the remote object to the new name.

5TH SEMESTER,CSE Page 69


JAVA PROGRAMMING

public static java.lang.String[] list(java.lang.String) throws java.rmi.RemoteException,


java.net.MalformedURLException; it returns an array of the names of the remote objects bound in the registry.

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);}
}
}

6) Create and run the client application


At the client we are getting the stub object by the lookup() method of the Naming class and invoking the
method on this object. In this example, we are running the server and client applications, in the same machine
so we are using localhost. If you want to access the remote object from another machine, change the localhost to
the host name (or IP address) where the remote object is located.

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){}
}
}

5TH SEMESTER,CSE Page 70


JAVA PROGRAMMING

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.

• The widely used java networking terminologies are given below:

1. IP Address

2. Protocol

3. Port Number

4. MAC Address

5. Connection-oriented and connection-less protocol

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.

It is a logical address that can be changed.

2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:

5TH SEMESTER,CSE Page 71


JAVA PROGRAMMING

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.

5) Connection-oriented and connection-less protocol


In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The example of
connection-oriented protocol is TCP.

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:

• 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.

5TH SEMESTER,CSE Page 72


JAVA PROGRAMMING
The client in socket programming must know two information:

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) {

5TH SEMESTER,CSE Page 73


JAVA PROGRAMMING

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);}
}
}

Example of Java Socket Programming (Read-Write both side)

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();

5TH SEMESTER,CSE Page 74


JAVA PROGRAMMING

}}

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.

5TH SEMESTER,CSE Page 75

You might also like