0% found this document useful (0 votes)
25 views175 pages

b.sc(m)-V Sem Java Notes

The document provides an overview of Java as a pure object-oriented programming language, detailing its core concepts such as classes, objects, inheritance, and polymorphism. It also covers Java's features, types of applications, the Java Virtual Machine (JVM), and the development tools required for programming in Java. Additionally, it includes information on data types, syntax rules, and a simple example of a Java program.

Uploaded by

rajeshmsd481
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
25 views175 pages

b.sc(m)-V Sem Java Notes

The document provides an overview of Java as a pure object-oriented programming language, detailing its core concepts such as classes, objects, inheritance, and polymorphism. It also covers Java's features, types of applications, the Java Virtual Machine (JVM), and the development tools required for programming in Java. Additionally, it includes information on data types, syntax rules, and a simple example of a Java program.

Uploaded by

rajeshmsd481
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 175

JAVA

UNIT-I
Introduction:
JAVA - Java is a pure Object Oriented Programming Language.
OOPs Concepts:
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Data Abstraction & Encapsulation
6. Message communication
7. Dynamic binding
Objects & Classes:
Objects:
Objects are the basic runtime entities in object oriented system. They may
represent a place, person or any item that the program may handle.
- An entity that has state and behavior is known as an object
E.g. chair, bike, marker, pen, table, car etc.
An object has three characteristics:
• State: represents data (value) of an object.
• Behavior: represents the behavior (functionality) of an object
• Identity: Object identity is typically implemented via a unique ID.
Class:
Collection of Objects of same type is known as class
ex: mango, apple and orange are the members of the class fruit
Data Abstraction:
Hiding the implementation details of a particular object is known as Data
abstraction
Data Encapsulation:
Combining all the functions together is known as Data Encapsulation.
- The wrapping of data and methods into a single unit is called encapsulation
which is one of the important features of class. The data is not accessible to the
outside world and only those methods which are wrapped in the class can access it
which is known as data hiding.
Polymorphism:
Means the ability to take more than one form.
Inheritance:
It is the process by which the objects of one class acquire the properties of objects
of another class.
- Extending the parent class properties to child class is the concept of Inheritance.
-It provides the idea of reusability which means that we can additional features to
an existing class without modifying it which is possible by deriving a new class
from the existing one where the new class will have the combined features of both
the classes.
Dynamic binding:
Means that the code associated with given procedure call is not known until the
time of the call at runtime. It is associated with polymorphism and inheritance.
Message Communication
Objects communicate with each other by sending and receiving information as
people.
It involves specifying the name of the object, method name and information to be
sent.
example:
employee.salary(ename);
Depending on the above principles, they support,
- object based programming language

Object based programming language support


- data encapsulation
- data hiding & access mechanisms
- automatic initialization & clear up of objects
- operator overloading
Ex: SMALLTALK
Object oriented programming language
object base programming language + dynamic binding+inheritance
Ex: c++,java
History of JAVA:
JAVA is a general-purpose, object-oriented programming language developed by
Sun Microsystems of USA in 1991.
Originally called Oak by James Gosling.
Java was invented for the development of software for consumer electronic devices
like TVs, toasters
Oak was renamed to java in 1995.

What is Java:
->Java is a pure object oriented programming language.
->Java is a programming language and a platform independent.
->Java is a high level, robust, secured and object-oriented programming language.
Platform: Any hardware or software environment in which a program runs is
known as a platform. Since Java has its own runtime environment (JRE) and API,
it is called platform.

JAVA features:
- Compiled and Interpreted
- Platform independent & portable
- Object Oriented
- Robust & secure
- distributed
- Familiar, simple & small
- Multithreaded & interactive
- High performance
- Dynamic & Extensible

Compiled & interpreted:


Java combines both the features of compiler and interpreter. First, java
compiler translates source code into byte code instructions which are not machine
instructions at the second stage, java interpreter generates machine codes that can
be directly executed by the machine that is running the java program.
Platform independent & portable:
Java programs can be easily moved from one system to other anywhere and
anytime i.e. changes and upgrades in o/s, processors and system resources will not
force any changes in java programs.

Object oriented:
Java is a true OOPL where all program code and data reside within objects &
classes.

Robust & secure:


Java is a robust language which provides many safeguards to ensure reliable code.
It utilizes strong memory management.
There is an absence of pointers that bypasses security.
There is automatic garbage collection in Java.

Distributed:
It is a distributed language for creating applications on networks which has the
ability to share both data & programs.

Simple, small & familiar:


Java is a small and simple language. It does not use pointers, preprocessor header
files, go to statement, operator overloading, and multiple inheritance

Multithreaded and Interactive:


Multithreaded means handling multiple tasks at same time which means that we
need not wait for the application to finish one task before finishing other.

High performance:
Incorporation of multithreading enhances the overall execution speed of java
program.

Dynamic & Extensible:


It is a dynamic lang. which is capable of dynamically linking in new class libraries,
methods and objects by using packages.
Types of Java Applications:
There are mainly 4 type of applications that can be created using java
programming:

1) Standalone Application: It is also known as desktop application or window-


based application. An application that we need to install on every machine such as
media player, antivirus, acrobat reader etc.
AWT and Swing are used in java for creating standalone applications.

2) Web Application: An application that runs on the server side and creates
dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc.
technologies are used for creating web applications in java.
ex:as irctc.co.in, gmail.com,snapdeal.com,amazon.in,bookmyshow.com

3) Enterprise Application: An application that is distributed in nature, such as


banking applications, Insurance Application etc. It has the advantage of high level
security, load balancing and clustering.
In java, EJB is used for creating enterprise applications.
ex: Banking & Insurance Applications

4) Mobile Applications: An application that is created for mobile devices.


Currently Android and Java ME are used for creating mobile applications.
Ex: Embedded Systems
Smart Card
Robotics
Games etc.

JVM:
JVM (Java Virtual Machine) is an abstract machine.
It is a specification that provides runtime environment in which java byte code can
be executed.
Java virtual machine:
Java is a 2 stage system which supports both compiler & interpreter based.
At first stage, java compiler translates source code into intermediate code known as
byte code(virtual code) for a machine that does not exist. This machine is called
JVM and exists only inside computer memory. It is a simulated computer within
the computer and does all major functions of real computer.
At second stage, byte code is converted to machine code.

Process of compilation:

Java Compiler
Java Program code Virtual machine

Source Code Byte Code

Process of converting byte code into machine code (Interpretation):


Byte code Machine code
Java Interpreter
Virtual machine real machine

The JVM performs following main tasks:


Loads code
Verifies code
Executes code
Provides runtime environment

JRE(Java Runtime Environment)


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

Tools for developing a java program


- Application development tools - JDK -> contains development tools to create &
develop java program
- Java class library(JSL) or application program interface(API) - contains set of
classes with methods in the form of packages
Java Development kit (JDK) – The JDK comes with a set of tools that are used
for developing and running Java program.
It includes:
1. Appletviewer( It is used for viewing the applet)
2. Javac(It is a Java Compiler)
3. Java(It is a java interpreter)
4. Javap(Java diassembler,which convert byte code into program description)
5. Javah(It is for java C header files)
6. Javadoc(It is for creating HTML document)
7. Jdb(It is Java debugger)

java class library(JSL) or application program interface(API)


Provides set of classes with methods in the form of packages
types of predefined packages:
- >language package
ex: import java.lang.*;
-> awt package
import java.awt.*;
-> utility package
Import java.util.*;
->input and output package
import java.io.*;
->applet package
import java.applet.*;
->networking package
import java.net.*;

How to set Permanent Path of JDK in Windows


1: open mycomputer folder->"c" drive->program files(x86)->java->jdk1.5.0_13-
>bin
2. copy the address from address bar(ctrl+c)

For setting the permanent path of JDK, you need to follow these steps:
Go to MyComputer ->right click->properties ->
change settings->advanced tab -> environment variables -> new tab of user
variable -> write “path” in variable name -> write path of bin folder (C:\jdk1.3\bin
ie paste by using ctrl+v)in variable value -> ok -> ok -> ok
- set the same path with system variable also

For typing java programs and executing


- chose start->cmd->ok displays DOS prompt
- at the prompt, type D: which display "D" drive ie d:\>
- create a subdirectory on your name using md/mkdir command
-d:\>md chinnu
d:\> change to "chinnu" subdirectory from "D" drive using cd/chdir command
d:\>cd chinnu
Popular Java Editors
To write your Java programs, you need a text editor.
Edit - on dos platform

Notepad − On Windows machine, you can use any simple text editor
like Notepad , TextPad.

Netbeans − A Java IDE that is open-source and free which can be downloaded
from https://www.netbeans.org/index.html.

Eclipse − A Java IDE developed by the eclipse open-source community and can be
downloaded from https://www.eclipse.org/.

implementing java program


- creating program
- compiling the program
- running the program
steps for writing java program
- open notepad editor by choosing start->notepad->ok
- type java program(source code using high level language)
- save the program as filename.java in your directory by choosing file->save
- minimize notepad editor by choosing minimize button
- compile the program from dos prompt(start->cmd)
by typing javac filename.java which creates .class file which converts source code
to byte code
- run the java program by typing at the dos prompt, as java filename which
executes and converts byte code to machine code

Example
class FirstJavaProgram
{
public static void main(String []args)
{

System.out.println("Welcome to Java Programming");


}
}

Structure of java program


It is collection of different sections.

documentation section - suggested


package statements - optional
import statements - optional
interface statements -optional
class definition - essential
main class method definition - essential

declaration of class
//syntax
imort packagename.classname;
class classname
{
public static void main(String args[])
{
function body;
}
}
First Java Program
Let us look at a simple code that will print the "Welcome to Java Programming"
Example:
class FirstJavaProgram
{
public static void main(String []args)
{
System.out.println("Welcome to Java Programming");
}
}
class declaration
class FirstJavaProgram declares a class which is Objet Oriented construct. As
java is true Object Oriented language, so everything must be placed inside a class.

Opening & Closing Braces


Every class definition in java begin with { and ends with } brace

main line
public static void main(String args[]) defines a method named main() similar
to main() of c & C++. Every java program must include main() method which is
the starting point for the interpreter to begin the execution of program.

A java application. can have number of classes but only one of them must include
main method to initiate the execution.

This line contains the keywords public, static, void

public - it is an access specifier that declares the main method as unprotected and
therefore making it accessible to all other classes.

static - it declares main method as one that belongs to the entire class and not a
part of any objects of the class.
Note: Static is used to access the methods without invoking on object using dot
operator.
Why do we use static in "public static void main (String args[]) in Java?

Because, in Java a function or variable in class is un accessible until an Object is


created from the class, but the 'main' function is supposed to run at startup(without
Object initiation) by JVM. So the 'main' is declared public as well as static so that
it can be accessed outside class & without even an Object is created.

void - it states that the main method does not return any value(returns nothing)

The output line


System.out.println("Welcome to Java Programming");
prints Welcome to Java Programming as output on screen

-It is the only the executable statement which is similar to printf() or cout<<

Steps to save the file, compile, and run the program:


- Open notepad (start->notepad) and write the code as above.
- Save the file as: FirstJavaProgram.java by choosing file->save
- Open a command prompt window (start->cmd) and go to the directory where you
saved the file
-Type javac FirstJavaProgram.java at prompt and press enter to compile your
code. which creates .class file
- Now, at prompt, type java MyFirstJavaProgram to run your program.

You will see Welcome to Java Programming printed on the window.

Data types in Java:


java language has a rich implementation of data types which specify size and the
type of values that can be stored in an identifier.

Types
- primitive data types/intrinsic
- non primitive/derived data types
primitive data types (8 types)
char boolean byte short int long float double
These 8 primitive types can be put into 4 categories.
1. Integer type
this group includes byte,short,int,long
byte - it is 8 bit integer data type. Value ranges from -128 to 127. Default value is
zero 0.
ex: byte b=10;
short - it is 16 bit integer data type. Value ranges from -32768 to 32767. default
value is 0.
ex:
short p=11;
int - it is 32 bit integer data type. Value ranges from -2147483648 to 2147483647.
default value is 0.
ex:
int x=10;
long- it is 64 bit integer data type. value ranges from -9.223372036854775808 to
9223372036854775807. Default value is 0.
ex:
long l=100023;

2. floating type
this group includes float, double
float - it is 32 bit float data type. Default value is 0.02F
ex:float f=10.2f;
double - it is 64 bit float data type
default value is 0.0d.
ex:
double db=11.23d;

3. character type
this group represent char which represents symbols in a character set like letters
and numbers.
char - it is 16 bit unsigned Unicode character. Range is from 0 to 65535.
ex:char c='a';
4. boolean
this group represents boolean which is a special type for representing true/false
values.
ex:
boolean ms=true;

5.String - accepts set of characters


syntax:
String variable;
ex:String name;
strores more than one character for name

non-primitive /derived data types


a reference data type is used to refer an object for which a reference variable is
declared.
ex: class, functions, interfaces, arrays

Basic Syntax
About Java programs, it is important to keep in mind the following points.

Case Sensitivity − Java is case sensitive, which means identifier Hello and hello
would have different meaning in Java.
ASCII(American Standard Code for Information Interchange)
- Characters
A to Z - 65 to 90 difference (+- 32)
a to z - 97 to 122
0 to 9 - 48 to 56

Class Names − For all class names the first letter should be in Upper Case.
Example: class MyFirstJavaClass
Method Names − All method names should start with a Lower Case letter.
Example: public void myMethodName()
Program File Name − Name of the program file should exactly match the class
name.
When saving the file, you should save it using the class name (Remember Java is
case sensitive) and append '.java' to the end of the name (if the file name and the
class name do not match, your program will not compile).
Example: Assume 'FirstJavaProgram' is the class name. Then the file should be
saved as 'FirstJavaProgram.java'

public static void main(String args[]) − Java program processing starts from the
main() method which is a mandatory part of every Java program.

Java Identifiers & keywords/reserved words(60)


All Java components require names. Names used for classes, variables, and
methods are called identifiers.

In Java, there are several points to remember about identifiers. They are as follows

1.All identifiers should begin with a letter (A to Z or a to z), currency character ($)
or an underscore (_).
ex: stud_name
2.After the first character, identifiers can have any combination of characters.
ex: stud_name1
3. A key word cannot be used as an identifier.
4.Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.

Java Modifiers:
Like other languages, it is possible to modify classes, methods, etc., by using
modifiers. There are two categories of modifiers −
1.Access Modifiers − default, public , protected, private
2. Non-access Modifiers − final, abstract, static
Note: Static is used to access the methods without invoking object
Variable is a data name that holds a value which changes during program
execution.
declaration of variables:
datatype variable1,variable2,...;
ex:
byte x;
int a,b,c;

giving values to variables


1) using assignment statement
2)using read statement

1) using assignment statement : value can be assigned to a variable using


assignment operator(=)
syntax:
datatype variablename=value/expression;
ex: int a=5;
or
int a;
a=5;

2) read statement - readLine() method is used to read values interactively using


keyboard which always read value of type string which are then converted to
corresponding data types using wrapper classes.

Java Variables or scope of variables


Following are the types of variables in Java −
1.Local Variables
2.Class Variables (Static Variables)
3.Instance Variables (Non-static Variables)

- Instance & Class variables are declared inside a class

- Instance variables are created when the objects are instantiated and therefore
associated with the objects

- class variables are global to a class and belong to the entire set of objects that
class creates.
-Local variables - variables declared and used inside methods are called local
variables. They are so called because they are not available for outside method
definition.
- These are visible to the program only from beginning till end of programming
block

Java Keywords (60)


The following list shows the reserved words in Java. These reserved words may
not be used as constant or variable or any other identifier names.

abstract boolean break byte byvalue


case cast catch char class
const continue default do double
else extends false final finally
float for future generic goto
if implements import inner instanceof
int interface long native new
null operator outer package private
protected public rest return short
static super switch synchronized this
threadsafe throw throws transient true
try var void volatile while

Comments in Java
are non executable statements which are used for user identification.

Java supports single-line(//) and multi-line(/* ==== */) comments very similar to
C and C++.
Note : characters available inside any comment are ignored by Java compiler.

type casting - process of converting from one form(dat type) to other form
1- implicit type casting/type conversion
2- explicit type casting/casting a value
1- implicit type casting/type conversion -
process of converting from low range data types to high range data type values.
uses:
- it is possible to assign one type of values to another data type without caste
where java compiler does this conversion automatically and so it is also called as
automatic conversion.

ex: byte b=75;


int a=b;
possible type conversions:

byte short,int,long,float,double
char int,long,float,double
short int,long,float,double
int long,float,double
long float,double
float double

2- explicit type casting/ casting -


Process of converting from one data type to another data type explicitly by user
when they need is called casting a value.
- using casting, we can convert high range data type to low range and vice versa

syntax:
datatype <variablename>=(datatype)<variablename>
ex:
int i=135;
byte b=(byte)i;
- casting high range values to low range value leads to loss of data
- casting float->int causes truncation of decimal part
ex:23.5 ->23
- casting double->float causes rounding off digits
ex:1.23456789234
1.234568
-> casting long-int causes dropping the excess high order bits
uses of casting
1) x=(int)7.5 converted into integer by truncating fractional part
X=7
2) y=(int) 21.3/(int)4.5 both numerator and dinominator are converted into int
and result is 5
3) int n=2;
int sum=3;
b=(double)sum/n; performs floating point mode division
4) y=(int)a+b performs additions and caste the result to int
5)p=cos((double)x) firstly caste the value "x" to double and it is
passed to cos() function as parameter

reading values from keyboard


there are various ways to read values from the keyboard interactively like using
data input stream &buffered reader(readLine()),command line arguments, Scanner
class .....
Scanner Class:
Scanner is a class in java.util package used for obtaining the input of the primitive
types like int, double etc. and strings. ... To create an object of Scanner class, we
usually pass the predefined object System.in, which represents the standard input
stream.

to input numerical values,


for int use nextInt(),
short use nextShort(),
float use nextFloat(),
double use nextDouble(),
long use nextLong()
for character use next() - for single word
for line of text , use nextLine()
for boolean, use nextBoolean()
java.util Package. It contains the collections framework, legacy collection classes,
event model, date and time facilities, internationalization, and miscellaneous utility
classes (a string tokenizer, a random-number generator, and a bit array).
System.in is an InputStream which is typically connected to keyboard input of
console programs. System.in is not used as often since data is commonly passed to
a command line Java application via command line arguments, or configuration
files.

//Scanner12.java
//reading values from key board
import java.util.Scanner;
class Scanner12
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter ur rollnumber");
int rollno=sc.nextInt();
System.out.println("enter ur name");
String name=sc.next();
System.out.println("enter ur fee");
double fee=sc.nextDouble();
System.out.println("roll number ="+rollno);
System.out.println("name ="+name);
System.out.println("fee ="+fee);
sc.close();
}
}

//reading values from kb


//sum of 2 numbers
//Sumtwonums.java
import java.io.*;
class Sumtwonums
{
public static void main(String args[]) throws IOException
{
DataInputStream di=new DataInputStream(System.in);
System.out.println("Enter first Number");
int m=Integer.parseInt(di.readLine());
System.out.println("Enter second Number");
int n=Integer.parseInt(di.readLine());
int sum=m+n;
System.out.println("Sum of 2 numbers is :"+sum);
}
}

//reading values from kb


import java.lang.DataInputStream;
class InputKB
{
public static void main(String args[])
{
DataInputStream in=new DataInputStream(System.in);
int num1=0;
float num2=0.0f;
try
{
System.out.println("Enter any integer");
num1=Integer.parseInt(in.readLine());
System.out.println("Enter any floating value");
num2=Float.valueOf(in.readLine()).floatValue();
}
catch(Exception e)
{
}
System.out.println("Integer number ="+num1);
System.out.println("Floating value ="+num2);
}
}
note : readline() method is invoked using an object of the class DataInputStream
which reads i/p from kb as a string which is then converted to correct data type
using data type wrapper classes.

//reading values from kb


//factorial value
//Fact11.java
import java.io.*;
import java.lang.*;
class Fact11
{
public static void main(String args[]) throws IOException
{
int n,f=1;
DataInputStream dis=new DataInputStream(System.in);
System.out.println("enter any number");
n=Integer.parseInt(dis.readLine());

for(int i=1;i<=n;i++)
{
f=f*i;
}
System.out.println("factorial value is"+f);
}
}

Control structures -controls the flow of data:


- Sequential control structures
- Selection control structures
- Iterative control structures

- Sequential control structures


these are by default, where the programming statements are executed in a sequence
starting from the beginning till the end of the program.
-Selection control structures - these are the statements which are executed basing
on a certain condition.
ex: decision making statements (if construct) and switch construct

-Iterative control structures (looping) - execution of statements repeated number


of times as long as condition is true or until condition becomes false is known as
loop.
ex: do, for loop, while loop

if construct
- simple if
- if else construct
- if else if ladder
- nested if

simple if
if (condition)
statement(s);
// program to demonstrate Simple if
//Simpleif.java
import java.lang.*;
class Simpleif
{
public static void main(String args[])
{
int age=12;
if ( age>=18)
System.out.println("candidate is major");
if ( age<18)
System.out.println("candidate is minor");
}
}
if else construct:
if (condition)
statement(s);
else
statement(s);

// program to check whether candidate is major or minor


// program to demonstrate if else construct
//Ifelse.java
import java.lang.*;
class Ifelse
{
public static void main(String args[])
{
int age=20;
if ( age>=18)
System.out.println("candidate is major");
else
System.out.println("candidate is minor");
}
}
//wap to find biggest of 2 numbers
//wap to check whether given number is even or odd
if else if ladder
if (condition)
statement(s);
else
if (condition)
statement(s);
[ else
if (condition)
statement(s);]
else
statement(s);
// program to find biggest of 2 numbers including equality
// program to demonstrate if else if construct
//Ifelseif.java
import java.lang.*;
class Ifelseif
{
public static void main(String args[])
{
int a=10; //assignment statement
int b=10;
if ( a>b)
System.out.println("a is greater than b");
else
if (b>a)
System.out.println("b is greater than a");
else
System.out.println("Both a and b are equal");
}
}

* wap to calculate grade basing on total and print marks memo consisting of
rno,name and any 3 subject marks

nested if - if within a if
if(condition)
{
if(condition)
statement(s);
else
statement(s);
}
else
{
if(condition)
statement(s);
else
statement(s);
}

// program to find biggest of 3 numbers


// program to demonstrate nested if
//Nestedif.java
import java.lang.*;
class Nestedif
{
public static void main(String args[])
{
int a=80,b=44,c=15,big;
if ( a>b)
{
if(a>c)
{
big=a;
}
else
{
big=c;
}
}
else
{
if(b>c)
{
big=b;
}
else
{
big=c;
}
}
System.out.println("biggest number of "+a+","+b+" and "+c+" is:"+big);
}
}

switch construct
is a multi way construct which is used as an alternate to if else if construct.
syntax:
switch(expression)
{
case value 1:
statements;
break;
case value 2:
statements;
break;
case value 3:
statements;
break;
=====
====
case value N:
statements;
break;
default:
statements;
break;
}

Q: program to accept day number and print appropriate day of the week
//SwitchChoice.java

import java.util.Scanner;
class SwitchChoice
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("enter day number from 1 to 7");
int dayno=sc.nextInt();
switch(dayno)
{
case 1:
System.out.println("it is monday");
break;
case 2:
System.out.println("it is tuesday");
break;
case 3:
System.out.println("it is wednesday");
break;
case 4:
System.out.println("it is thursday");
break;
case 5:
System.out.println("it is friday");
break;
case 6:
System.out.println("it is saturday");
break;
case 7:
System.out.println("it is sunday");
break;
default:
System.out.println("invalid choice ");
}
}
}
iterative statements or looping constructs
loop
execution of statements repeated number of times as long as condition is true or
until condition becomes false is known as loop.
ex: entry contol loop and exit control loop

entry control loop:


here, the condition is checked first and if it is true, enters the loop and executes
the statements accordingly until the condition becomes false.
if the condition is false, simply it exits the loop.
Ex: for loop, while loop
exit control loop:
Here, first enters the loop and executes the statements accordingly ie the
statements are executed at least once unconditionally. At the end, the condition is
checked and if it is true, enters the loop and executes the statements accordingly
until the condition becomes false.
Ex:do loop

while loop:
initialization statement(s);
while(condition)
{
body of loop;
}
statement-x;
//example to demonstrate while loop
//While.java
class While
{
public static void main(String args[])
{
int i=1; //initialisation
while(i<=10)
{
System.out.println(i);
i=i+1;
}
}
}

//reverse of a number
import java.util.Scanner;
class ReverseNum
{
public static void main(String args[])
{
int m,mod,rem,rev=0;
Scanner sc=new Scanner(System.in);
System.out.println("enter any number");
int n=sc.nextInt();
m=n;
while(m>0)
{
rem=m%10;
rev=rev*10+rem;
m=m/10;
}
System.out.println("Reverse of "+n+" is :"+rev);
}
}

for loop:
for(initialization;condition;increment section)
{
body of loop;
}
statement(s);

//example to demonstrate for loop


//For.java
class For
{
public static void main(String args[])
{
for(int i=1;i<=10;i=i+1)
{
System.out.println(i);
}
}
}

//example to demonstrate for loop


//factorial value of a number
//Factorial.java
class Factorial
{
public static void main(String args[])
{
int n=4,f=1;
for(int i=1;i<=n;i=i+1)
{
f=f*i;
}
System.out.println("Factorial value of :"+n+" is :"+f);
}
}
}

do loop:

initialization statement(s);
do
{
body of loop;
}while(condition);
statement-x;

//example to demonstrate do loop


//Do.java
class Do
{
public static void main(String args[])
{
int i=12;
do
{
System.out.println(i);
i=i+1;
}while(i<=10);
}
}

Arrays:
- It is collection of contiguous elements of similar data type(homogenous
collection of elements). Array is container object that hold values of homogenous
types. It is also known as static data structure because size of an array must be
specified at the time of its declaration.
- An array can be either non-primitive or reference type.
- In java, array is an example of derived data type.
- If an array contains "n" elements, the index of array starts from 0 and end
with n-1.
-Each individual element is called subscript of the array.
ex:
int a[]={10,20,30,40,50}; // initialization of array
a[0] is subscript and 0 is the index value

array declaration:
datatype [] identifier;
or
datatype identifier[];
ex:
int []arr;
char []b;
short []cc;
long []dd;
int [][] bb; // two dimensional array

int a[10];
int [10]arr;
note : array can be of any type;

types of arrays:
- one dimensional arrays
- two dimensional arrays

initialization of an array:
new operator is used to initialize an array
ex:
int [] aa=new int[10];
or
int aa[]={22,33,44,55,66};
Accessing an array element:
array index starts from 0. So, to access nth element of an array,
syntax is :
arrayname[n-1];
ex:
to access 5 th element of array
int []aa={11,22,33,44,55};
System.out.println("element in 5th position is"+aa[4]);
o/p
55

//initialisation of 1D array
class ArrayInit
{
public static void main(String args[])
{
int a[]={1,2,3,4,5};
for(int i=0;i<5;i++)
{
System.out.println("elements of array are :"+a[i]);
}
}
}

//sum of elements of array


//Array.java
import java.lang.*;
class Array
{
public static void main(String args[])
{
int arr[]={10,20,30,40,50}; //initialisation of an array
int total=0;
for(int i=0;i<5;i++)
{
total=total+arr[i];
}
System.out.println("total is "+total);
}
}
///sum of any 10 elements in an array
//ArraySum10.java
import java.io.*;
class ArraySum10
{
public static void main(String args[]) throws IOException
{
int a[ ]=new int[10];
int i,sum=0;
DataInputStream di=new DataInputStream(System.in);
System.out.println("Enter any 10 values");
for(i=0;i<10;i++)
{
a[i]=Integer.parseInt(di.readLine());
sum=sum+a[i];
}
System.out.println("sum of 10 elements of array is :"+sum);
}
}

//sorting of elements in an array


//SortScanner.java
import java.util.Scanner;
class SortScanner
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
// int a[ ]={23,45,67,6,2,87,99,12,10,8};
int a[ ]=new int[10];
int i,j,temp;
System.out.println("Enter any 10 elements into an arrays");
for(i=0;i<10;i++)
{
a[i]=sc.nextInt();
}
//sorting
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(a[i] > a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
System.out.println("Elements in sorted are");
for(i=0;i<10;i++)
{
System.out.println(a[i]);
}
sc.close();
}
}
//initilisation of 2d array
//Init2d.java
import java.io.*;
class Init2d
{
public static void main(String args[])
{
int a[][]={{1,2},{3,4},{5,6}},r,c;
System.out.println("Elements of 2d array are");
for(r=0;r<3;r++)
{
for(c=0;c<2;c++)
{
System.out.print(a[r][c]+" " );
}
System.out.println();
}
UNIT-II
Object Oriented Programming
Classes, Objects and Methods
Class in Java
A class is a group of objects of same type that has common properties.
A class in java can contain:
• data member
• method
• constructor
• block
• class and interface

Syntax to declare a class:


class <class_name> [extends superclassname]
{
[variable declaration]
[methods declaration]
}

=>adding variables(data members)


data is encapsulated in a class by placing data fields inside the body of class
definition because they are created whenever an object of the class is instantiated.

class Rectangle
{
int length,breadth; // instance variables
}
length and breadth are instance variables and are also known as member variables
which are only declared and therefore no storage space has been created in the
memory.
=>adding methods(functions)
Methods are declared inside the body of class but immediately after declaration of
instance variables.
syntax:
returntype methodname[(parameterlist)]
{
method-body;
return variable/expression;
}

//function with no arguments and no return value


void getdata( )
{
}
//function with arguments and no return value
void getdata(int x,int y)
{
}
//function with arguments and return value
int getdata(int x,int y)
{
}
//function with no arguments and return value
int getdata()
{
}
ex:
class Rectangle
{
int length,breadth; //instance variables

//method with arguments


void getdata(int x,int y)
{
length=x;
breadth=y;
}
//method without arguments
void getdata()
{
length=12;
breadth=14;
}
}

creating objects:
Creating objects is known as instantiating an object (instantiation)
Objects in java are created using new operator which creates an object of the
specified class and returns reference to that object.
syntax:
classname object(s);

Rectangle rect1; //declare


rect1=new Rectangle(); //instantiate
can be written in single statement as
Rectangle rect1 = new Rectangle();

note:
- first statement declares a variable to hold the object reference
- second statement assigns the object reference to the variable
creation of object references

action statement result

declare Rectangle rect1; null rect1


rect1=new Rectangle(); . rect1
.
Instantiate
|
Rectangle Object
rect1 is a reference to Rectangle object

=>accessing class members


objectname.variablename=value; // giving value to a data member
ex:
rect1.length=10;
rect1.breadth=20;
objectname.variablename; // acessing member
ex:
System.out.println(rect1.length);
System.out.println(rect1.breadth);

objectname.methodname(parameterlist);

here, objectname is the name of the object and variablename is the name of the
instance variable inside the object.
Ex:
Rectangle rect1=new Rectangle();
rect1.length=15; //giving values to members
rect1.breadth=12;
rect1.getdata(); //without argument
rect1.getdata(15,10); //with argument
//Example
//application of classes and objects
//Rectangle1.java
class Rectangle
{
int length,breadth; // declaration of instance variables
void getdata(int x,int y) //method definition
{
length=x;
breadth=y;
}
int rectarea() //definition of other method
{
int area=length*breadth;
return(area);
}
}
class Rectangle1 //class with main method
{
public static void main(String args[ ])
{
int area1,area2;
Rectangle rect1=new Rectangle(); //creating objects
Rectangle rect2=new Rectangle();
rect1.length=15; //giving values
rect1.breadth=10;
area1=rect1.length*rect1.breadth;
System.out.println("Area1="+area1);
rect2.getdata(12,5);
area2=rect2.rectarea();
System.out.println("Area2="+area);
}
}

// Example1
class Student
{
int id;//data member (or instance variable)
String name;//data member(or instance variable)
}
class Student1
{
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
s1.id=1001;
s1.name=”vaagdevi”;
System.out.println(s1.id);
System.out.println(s1.name);
}
}
------------------------------------------------------------------------------------
//Example2
class Student
{
int a;
String b;
void insertRecord(int x, String n) // Method with arguments
{
a=x;
b=n;
}
void displayInformation() //method without argument
{
System.out.println("Id= "+a);
System.out.println(“name=”+b);
}
}
Class Student2
{
public static void main(String args[])
{
Student s1=new Student();
s1.insertRecord(1001,"vaagdevi");
s1.displayInformation();
}
}
------------------------------------------------------------------
//Example3
class Student
{
int id;
String name;
void insertRecord() // Method with no argument
{
id=1001;
name="vaagdevi";
}
void displayInformation() //method
{
System.out.println("Id= "+id);
System.out.println("Name= "+name);
}
}
class Student3
{
public static void main(String args[])
{
Student s1=new Student();
s1.insertRecord();
s1.displayInformation();
}
}
--------------------------------------------
Anonymous object:
=>Anonymous simply means nameless.
=>An object that have no reference is known as anonymous object.
=>If you have to use an object only once, anonymous object is a good approach.

//Calculation.java
//demonstration of anonymous object
class Calculation
{
void fact(int n)
{
int fact=1;
for(int i=n;i>=1;i--)
{
fact=fact*i;
}
System.out.println("factorial value is "+fact);
}
}
class Anonymoustest
{
public static void main(String args[])
{
new Calculation().fact(5); //calling method with anonymous object
}
}
Output:Factorial is 120

Constructors in Java
Constructor in java is a special type of method that is used to initialize the object
when it is created. Java constructor is invoked at the time of object creation.
It constructs the values i.e. provides data for the object that is why it is known as
constructor.

Rules for creating java constructor:


There are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type. This is because they return the
instance of the class itself.
Types of java constructors:
There are two types of constructors:
1. Default constructor (no-argument constructor)
2. Parameterized constructor (with argument constructor)

Default constructor - it is a special member function or method that is invoked


automatically as and when object is created without any argument.
Parameterized constructor - it is a special member function or method that is
invoked automatically as and when object is created with argument.

//Example of Default Constructor


//RectangleArea.java
class Rectangle
{
int length,breadth; // declaration of instance variables
Rectangle() //default constructor method definition
{
length=10; //providing initial values to data members
breadth=5;
}
int rectarea() //definition of other method
{
int area=length*breadth;
return(area);
}
}
class RectangleArea
{
public static void main(String args[ ])
{
Rectangle rect1=new Rectangle(); //calling default constructor
int area1=rect1.rectarea();//explicit function call
System.out.println("Area1="+area1);
}
}

//parameterized constructor
//RectangleArea1.java
class Rectangle
{
int length,breadth; // declaration of instance variables
Rectangle(int x,int y) //defining parameterized constructor
{
length=x;
breadth=y;
}
int rectarea() //definition of other method
{
int area=length*breadth;
return(area);
}
}
class RectangleArea1
{
public static void main(String args[])
{
Rectangle rect1=new Rectangle(15,10); //calling constructor with arguments
int area1=rect1.rectarea();
System.out.println("Area1="+area1);
}
}

//default constructor without method definition


//DefaultCons.java
class DefaultCons
{
int id;
String name;
DefaultCons() //default constructor
{
System.out.println(“id=”+id);
System.out.println("name= "+name);
}
}
class DefaultContest
{
public static void main(String args[])
{
DefaultCons s1=new DefaultCons();
}
}
Explanation: In the above class, as we are not creating any constructor , compiler
provides you with a default constructor where 0 and null values are provided.
Example of parameterized constructor: In this example, we have created the
constructor of Student class that has two parameters. We can have any number of
parameters in the constructor.
class Student4
{
int id;
String name;
Student4(int i,String n) // Parameter Constructor
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
}
class Pconstest
{
public static void main(String args[])
{
Student4 s1 = new Student4(111,"John");
S1.display();
Student4 s2 = new Student4(222,"Thomas");
s2.display();
}
}

--------------------------------------------------------------
Copy Constructor
There is no copy constructor in java. But, we can copy the values of one object to
another object just like copy constructor in C++.
//Example to demonstrate copy constructor
//CopyConStudent.java
class CopyConStudent
{
int id;
String name; //string object
CopyConStudent(int i,String n) // parameterised Constructor
{
id = i;
name = n;
}
CopyConStudent(CopyConStudent s) // Copy Constructor
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}
}
Class Copycontest
{
public static void main(String args[])
{
CopyConStudent s1 = new CopyConStudent(10,"chinnu");
CopyConStudent s2 = new CopyConStudent(s1); //calling method with object
as argument
System.out.println("Object S1 =");
s1.display();
System.out.println("Object S2 =");
s2.display();
}
}
Copying values without using copy constructor:
We can copy the values of one object into another by assigning the objects values
to another object. In this case, there is no need to create the constructor.
//copy constructor
//CopyCons.java
class Student6
{
int id;
String name;
Student6(int i,String n) // parameterized Constructor definition
{
id = i;
name = n;
}
Student6(Student6 s) // Copy Constructor
{
id = s.id;
name =s.name;
}
void display()
{
System.out.println(id+" "+name);
}
}
class CopyCons
{
public static void main(String args[])
{
Student6 s1 = new Student6(111,"Karan"); //parameterized constructor
Student6 s2 = new Student6(s1); // copy constructor
s1.display();
s2.display();
}
}

polymorphism - it has the ability to take more than one form

Types
- compile time polymorphism
- operator overloading (not supported in java but supported in C++)
- method overloading
- runtime polymorphim

Method Overloading in Java:


In Java, it is possible to create methods that have the same name but
different parameter lists & different definitions. It is known as method overloading
which is used when objects are required to perform similar tasks but using different
input parameters.

- Polymorphism : when a method is called, java matches up the method name and
then the number & type of parameters to decide which one of the definitions to
execute. This process is known as polymorphism.
If a class have multiple methods by same name but different parameters and
performing different set of activities, it is known as Method Overloading.
Advantage of method overloading:
Method overloading increases the readability of the program

There are two ways to overload the method in java


1. By changing number of arguments
2. By changing the data type

Constructor overloading (multiple constructors) is a technique in Java in which


a class can have any number of constructors that differ in parameter lists.
class CTest
{
int x,y;
CTest()
{
x=5;
y=10;
}
CTest(int a)
{
x=a;
y=a;
}
CTest|(int a,int b)
{
x=a;
y=b;
}
void display()
{
System.out.println(“x=”,+x);
System.out,println(“y=”,+y);
}
class ConsOvldTest
{
public static void main(String args[ ])
{
CTest c1=new CTest();
c1.display();
CTest c2=new CTest(100);
c2.display();
CTest c3=new CTest(50,90);
c3.display();
}
}

Static Members
-The members that are declared static are called static members. Since these
members are associated with the class itself rather than individual objects, the
static variables and methods are also known as class variables and class methods.
- Static variables are used when we want to have a common variable name to all
instances of a class.
- Like static variables, static methods can be called without using the objects.
•The static variable can be used to refer the common property of all objects (that is
not unique for each object) e.g. company name of employees, college name of
students etc.
•The static variable gets memory only once in class area at the time of class
loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Java static property is shared to all objects.
For example, the Math class of java library defines many static methods to perform
math operations that can be used in any program.
float x=Math.sqrt(25.0);

//Program to demonstrate usage of static variable


//StaticVariable.java
class Student
{
int rollno;
String name;
static String college = "VDC”; //static data member
//parameterised constructor definition
Student(int r,String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}
class StaticVariable
{
public static void main(String args[])
{
Student s1 = new Student(111,"Chinnu"); //paramerterised constructor
s1.display();
}
}
static methods
Method followed by the keyword static is called static method which can
1) Be called directly like "C" language without invoking the same on the object
using . (dot) operator
2) Used to change the value of static data members

//usage of static method


//Staticmethod1.java
class Mathoperation
{
static float multiplyy(float x,float y) //static method
{
return x*y;
}
static float dividee(float x,float y) //static method
{
return x/y;
}
}
class Staticmethod1
{
public static void main(String args[ ])
{
float a=Mathoperation.multiplyy(4.0F,5.0F);
float b=Mathoperation.dividee(4.0F,2.0F);
System.out.println("Multiplication ="+a);
System.out.println("Divide ="+b);
}
}

Nesting of methods (method within a method):


A method can be called by using only its name by another method of the
same class. This is known as nesting of methods.
Note: A method can call any number of methods. It is also possible for a called
method to call another method.

//biggest of 2 numbers including equality


//program to demonstrate nesting of members
//NestingTest.java
class Nesting
{
int m,n;
Nesting(int x,int y) // parameterised constructor definition
{
m=x;
n=y;
}
int largest()
{
if(m>n)
{
return(m);
}
else
{
if(m<n)
{
return(n);
}
else
{
// System.out.println("both are equal");
return 0;
}
}
}
void display()
{
int large=largest(); //calling a method
System.out.println("biggest value="+large);
}
}
class NestingTest
{
public static void main(String args[ ])
{
Nesting nest=new Nesting(50,40); //parameterised constructor
nest.display();
}
}

Inheritance:Extending a class
Inheritance is the concept of extending the features of existing class to a
newly derived class. The Class which is giving properties to a new class is called
as parent class or base class or super class. The class which is inheriting the
properties of parent class is called as child class or sub or derived class.
-The new class will have the combined features of both old and new class.
-Inheritance allows subclasses to inherit all the variables and methods of their
parent classes.

Types of Inheritance
1. Single inheritance (only one super class)
2. Multiple inheritance (a class with several super classes)
3. Hierarcheal inheritance(one super class, many sub classes)
4. Multilevel inheritanace(derived from a derived class(intermediate base class)
5. Hybrid inheritance(combination of multipath forms of inheritances ie multilevel
+ multiple)
6. Multipath Inheritance(creation of class from other super class which are derived
from common super class)

Note : Java does not directly implement multiple inheritance. However, this
concept is implemented using a secondary inheritance path in the form of
interfaces.
Advantages of Inheritance
1. Reusability
2. Elimination of duplication of code
3. Time
4. Size

Syntax:
class subclassname extends superclassname
{
Variables declaration
Methods Declaration
}

The keyword “extends” signifies the properties of superclass name are extended to
subclassname. The sub class will now contain its own variables and methods as
well as those of the superclass.

=>Single level Inheritance:


In this type of inheritance we have two classes that are one parent class and
one child class. Creation of a class from only one super class is known as single
inheritance.

//example of single inheritance


//Singleinh.java Base
class Base
{
int x,y,z;
Derived
void setxy()
{
x=7;
y=5;
}
}

class Derived extends Base


{
void add()
{
z=x+y;
System.out.println("Sum="+z);
}
}
class Singleinhtest
{
public static void main(String args[])
{
Base b1=new Base();
b1.setxy();
Derived d=new Derived();
d.setxy();
d.add();
}
}
=>Multilevel inheritance:
The process of deriving a new class which is already derived from another class.
//Example of multilevel inheritance:
class Base
{
int x,y,z;
void setxy()
Base
{
x=7;
y=5;
} Derived1
}
class Derived1 extends Base
{
void add() Derived2
{
z=x+y;
System.out.println("Sum="+z);
}
}
class Derived2 extends Derived1
{
void mul()
{
z=x*y;
System.out.println("product="+z);
}
}
class Multileveltest
{
public static void main(String args[])
{
Base b1=new Base();
b1.setxy();
Derived1 d1=new Derived1();
d1.setxy();
d1.add();
Derived2 d2=new Derived2();
d2.setxy();
d2.add();
d2.mul();
}
}
=>Hierarchical Inheritance:
The process of deriving more than one subclasses from a common base class
(super class) is called hierarchical inheritance.
//Demonstration on hierarchical inheritance
class Base
{ Base
int x,y,z;
void setxy()
{ Derived1
Derived2
x=7;
y=5;
}
}
class Derived1 extends Base
{
void add()
{
z=x+y;
System.out.println("Sum="+z);
}
}
class Derived2 extends Base
{
void mul()
{
z=x*y;
System.out.println("product="+z);
}
}
class Derived3 extends Base
{
void sub()
{
z=x-y;
System.out.println("subtraction="+z);
}
}
class Hierarhicaltest
{
public static void main(String args[])
{
Derived1 d1=new Derived1();
d1.setxy();
d1.add();
Derived2 d2=new Derived2();
d2.setxy();
d2.mul();
Derived3 d3=new Derived3();
d3.setxy();
d3.sub();
}
}

=>Hybrid Inheritance:
The combination of more than one type of inheritance is called hybrid inheritance
//Demonstration on Hybrid inheritance:
class Base
{ Base

int x,y,z;
void setxy()
{
Derived1 Derived2
x=7;
y=5;
}
} Derived3
class Derived1 extends Base
{
void add()
{
z=x+y;
System.out.println("Sum="+z);
}
}
class Derived2 extends Base
{
void mul()
{
z=x*y;
System.out.println("product="+z);
}
}
class Derived3 extends Derived1
{
void sub()
{
z=x-y;
System.out.println("subtraction="+z);
}
}
class Hybridtest
{
public static void main(String args[])
{
Derived1 d1=new Derived1();
d1.setxy();
d1.add();
Derived2 d2=new Derived2();
d2.setxy();
d2.mul();
Derived3 d3=new Derived3();
d3.setxy();
d3.add();
d3.sub();
}
}

=>Multiple Inheritance:
If a subclass is derived from more than one super class such type of inheritance is
called multiple inheritance.
But classes in java cannot have more than one super class that means a class
cannot extend more than one class.
Java provides an alternative for multiple inheritance using interfaces.
Method Overriding:
A method defined in a super class is inherited by its subclass and is used by
the objects created by the subclass. Method inheritance enables us to use methods
repeatedly in subclasses without having to define the methods again in subclass.
However, there may be a situation when we want an object to respond to the
same method but have different behavior when that method is called. That means,
we should override the method defined in the superclass. This is possible by
defining a method in the subclass that has the same name, same arguments and
same return type as a method in the superclass. Then, when that method is called,
the method defined in the subclass is invoked and executed instead of one in the
superclass. This is known as overriding.
Method Overriding
The process of defining a method in a sub class that has same name, same
number and same type of parameters and same return type with same method in
the super class.
In java, overriding takes place in 2 ways namely
1. replacement
2. refinement

Replacement
It is a type of overriding in which parent class functionality is overridden by
child class i.e. only child class functionality is exhibited.

Ex:
class A
{
void display()
{
System.out.println(“Iam in base class”);
}
}

class B extends A
{
void display()
{
System.out.println(“Iam in child class”);
}
}

class ReplaceTest
{
Public static void main(String args[])
{
B b1=new B();
B1.display();
}
}

Refinement
It is another type of overriding. In this, parent class functionality is extended
by the child class by adding new features. Here we can observe both parent class
functionality and child class functionality

Ex:
class A
{
void display()
{
System.out.println(“Iam in base class”);
}
}

class B extends A
{
void display()
{
super.display();
System.out.println(“Iam in child class”);
}
}

class RefinementTest
{
public static void main(String args[])
{
B b1=new B();
B1.display();
}
}

super keyword
super keyword is a reference variable that is used to refer immediate parent
class object.
Uses of super:
1)super is used to invoke immediate parent class method
Example:
Super.m1(); //invoke parent class method
2)super is used to invoke immediate parent class constructor
Example:
Child()
{
super(); //invoke parent class constructor
}
3)super is used to refer immediate parent class variable.
Example:
Super.i; //invoke parent class variable

// write a program to invoke the parent class variable using super keyword
class Parent
{
int i=10;
}
class child extends Parent
{
int i=20;
void m1()
{
System.out.println("\n value of i in child class="+i);
System.out.println("\n value of i in parent class="+super.i);
}
}
class Supervartest
{
public static void main(String args[])
child c1=new child();
c1.m1();
}
}

// write a program to invoke the parent class constructor using super keyword
class Parent
{
Parent()
{
System.out.println("In parent");
}
}
class Child extends Parent
{
Child()
{
super();// invoke parent class constructor
System.out.println(" In child");
}
}
class Supertest
{
public static void main(String args[])
{
Child c1 = new Child();
}
}

Access specifiers in Inheritance


Specifiers the accessibility of the data members of the class.
private
public
protected
default

The private members of super class are not inherited into sub class where as
default, public, protected members are inherited.
Therefore private members of super class cannot be accessed inside or
outside of sub class where as default, public, protected members of super class can
be accessed inside or outside of sub class but outside the class using object name.
- private members are non inheritable and they can be accessed only within the
class but not outside the class
- public members are globally accessible ie within or outside the class thus
violating the data hiding concept which is one of the important concept of OOPs
- protected members are accessible within the class and the class which is
immediately derived from it.

//example to demonstrate usage of Access Specifiers


//AccessSpecifiers.java
class Access
{
private int x=10;
public int y=20;
protected int z=30;
int p=40; //default access
}
class B extends Access
{
public void show()
{
// System.out.println("private x="+x); //error
System.out.println(" public y="+y);
System.out.println(" protected z="+z);
System.out.println(" default p="+p);
}
}

class AccessSpecifiers
{
public static void main(String args[ ])
{
B obj=new B();
obj.show();
//System.out.println("private obj.x="+obj.x); //error
System.out.println(" public obj.y="+obj.y);
System.out.println(" protected obj.z="+obj.z);
System.out.println(" default obj.p="+obj.p);
}
}

Final keyword:
final is a keyword which is used in several different content with a variable,
method and class.
=>final is a keyword which cannot be changed .
1)final method:
A final method cannot be overriding or overridden in any of its subclass
Example:
class Base
{
final void display()
{
System.out.println("In Base display");
}
}
class Derived extends Base
{
/*void display()
{
System.out.println("In Derived display");
}*/
void print()
{
System.out.println("In Derived print");
}
}
class Finalmethod
{
public static void main(String args[])
{
Derived d1=new Derived();
d1.display();
d1.print();
}
}
2)final class:
A class is declared as final cannot be extends to further subclass
Example:
class Base
{
final void display()
{
System.out.println("In Base display");
}
}
/*class Derived extends Base
{

}*/
class Finalclass
{
public static void main(String args[])
{
Base b1=new Base();
b1.display();
}
}
3)final variable:
Final variable cannot be changed.
Example:
Class Finaltest
{
public static void main(String args[])
{
final int i=10;
// i=i+10;
System.out.println(“i=”+i);
}
}
Abstract classes and methods:
=> We have seen that by making a method final we ensure that the method is
not redefined in a subclass i.e the method never be subclass
=> Java allows us to something that is exactly opposite to this i.e. we can
indicate that a method must always be redefined in a subclass thus making
overriding compulsory this is done by using the keyword abstract in the method
definition.
=> We cannot create object for an abstract class.
=> The abstract class can be used for holding subclass object
=> Any class that has at least one abstract method has to be compulsory
declared as an abstract class
=> abstract class can contain both abstract and non abstract method
=> An abstract method has no body.
=> child class needs to override the definition of all abstract methods.

//Exampe1:
abstract class Parent
{
abstract void m1();
void show()
{
System.out.println("In parent show");
}
}
class Child extends Parent
{
void m1()
{
System.out.println("In child");
}
void display()
{
System.out.println("In child display");
}
}
public class Abstest
{
public static void main(String arg[])
{
Child c1=new Child();
c1.m1();
c1.display();
c1.show();
}
}

//Example2:
abstract class Shape
{
abstract void draw();
void display()
{
System.out.println("In shape display");
}
}
class Circle
extends Shape
{
void draw()
{
System.out.println("In draw");
}
/* void show()
{
System.out.println("In circle show");
}*
}
class Square extends Shape
{
void draw()
{
System.out.println("In square");
}
/*void print()
{
System.out.println("In square print");
}*/
}
public class Abstest1
{
public static void main(String arg[])
{
Shape s1;
s1=new Circle();
s1.display();
s1.draw();
// s1.show();
Shape s2;
s2=new Square();
s2.display();
s2.draw();
//s2.print();
}
}

Interfaces:
- Interface is a kind of class which contains methods and variables with a
difference.
- The difference is that interface defines only abstract methods and final fields.
This means that interfaces do not specify any code to implement these methods and
data fields contain only constants.
=>Therefore, it is the responsibility of the class that implements a interface to
define the code for implementation of these methods.
Syntax:
interface <interfacename>
{
variable declaration;
methods declaration;
}

Declaration of Variables:
final type variablename=value;

Declaration of Methods:
returntype methodname(parameterlist);

Example:
interface product
{
static final int code=999; //final variable
static final String name="xyz:";
void display(void); //abstract method
}

Note :
- Code for the method is not included in the interface and the method declaration
simply ends with ;
- The class that implements this interface must define the code for the method.

Example:
interface Area
{
final static float pi=3.142F; //final variable
//final method which cannot be overidden
final calculate(float a,float b);
void show(void); //abstract method
}

=>Implementing Interface:
A class can implement interfaces by using implements keyword
Syntax:
class classname implements interfacename
{
Body of class
}
// Implementing interface and accessing interface variable(single inheritance)

interface Base
{
int i=20;
public void display();
}
class Derived implements Base
{
public void display()
{
System.out.println(“in Derived display”);
}
public void show()
{
System.out.println(“in Derived show”);
}
}
calss Interfacetest
{
public static void main(String args[])
{
Derived d1=new Derived();
d1.display();
d1.show();
System.out.println(“i=”+Base.i);
}
}

Extending interfaces
Like classes, interfaces can be extended. That is interface can be subinterfaced
from other interfaces.
Syntax:
interface <interfacename2> extends <interfacename1>
{
body of interface2
}

For example, we keep all constants in one interface & the methods in the other.
Example:
interface Itemconstants
{
static final int pcode=999; //final data members
static final string name="TV";
}
interface Item extends Itemconstants
{
void display(void); // declaration of abstract method
}
Note : The interface Item would inherit both the constants code and name into it.

=>We can also combine several interfaces together into a single interfaces.
Example:
interface name1
{

}
interface name2
{

}
interface name3 extends name1,name2
{

}
//Example1 :interface extending other interface(Multilevel inheritance with
interfaces).

interface A A Interface
{
public void display();
} B Interace
interface B extends A
{
public void print();
C class
}
Class C implements B
{
public void display()
{
System.out.println(“In diasplay”);
}
public void print()
{
System.out.println(“In print”);
}
public void show()
{
System.out.println(“In show);
}
}
class Multileveltest
{
public static void main(String args[])
{
C c1=new C();
C1.display();
C1.show();
C1.print();
}
}

//Example2:Two subclasses implementing same super class(Hierarchical


Inheritance)

interface A
{ A => Interface
public void display();
}
class B implements A
{ B => classs C => class
public void display()
{
System.out.println(“In class B display”);
}
public void print()
{
System.out.println(“In class B print”);
}
}
Class C implements A
{
public void display()
{
System.out.println(“In class C display”);
}
public void show()
{
System.out.println(“In class C show”);
}
}
Class Heirarchicaltest
{
public static void main(String args[])
{
B b1=new B();
b1.display();
b1.print();
C c1=new C();
c1.display();
c1.show();
}
}

=>A more general form of implementation as follows:


syntax:
class classname implements <interfacename>
{
body of classname
}
=>general form of implementation may look like this

class classname extends superclass


implements interface1,interface2,....
{
body of classname;
}

This shows that a class can extend another class while implementing interfaces.

//Example1: Multiple Inheritance with extending a class and implementing


interfaces

interface A
{
public void display(); A =>interface B => class

}
class B
{
C =>class
public void show()
{
System.out.println(“In class B show”);
}
Class C extends B implements A
{
public void display()
{
System.out.println(“In class C display”);
}
public void print()
{
System.out.println(“In class C print”);
}
}
Class Mulpleinhtest
{
public static void main(String args[])
{
C c1=new C();
c1.display();
c1.show();
c1.print();
}
}

//Example2: Implementing multiple inheritance by implementing interfaces.


interface A
{ A=>interface B=> interface

public void display();


}
interface B
{ C => class
public void show();
}
Class C implements A.B
{
public void display()
{
System.out.println(“In class C display”);
}
public void show()
{
System.out.println(“In class C show”);
}
public void print()
{
System.out.println(“In class C print”);
}
}
Class Mulpleinhtest1
{
public static void main(String args[])
{
C c1=new C();
c1.display();
c1.show();
c1.print();
}
}

Packages

Packages:Putting classes together(container of classes)

One of the important features of OOP is its ability to reuse the code which
is already created and is achieved by extending classes (inheritance) and
implementing the interfaces but the same is limited to reusing the classes within a
program.
Packages in java are used to reuse classes from other programs without
physically copying them into the program under development which are very much
similar to "class libraries" in other languages.
Packages are way of grouping a variety of classes and/or interfaces
together which is done according to functionality which acts as container of
classes.
Benefits of packages:
1. The classes contained in the packages of other programs can be easily reused
2. In packages, classes can be unique compared with classes in other packages.
That is two classes in two different packages can have same name which may be
referred by their name comprising of package name and class name.
3. Packages provide a way to “hide” classes thus preventing other programs or
packages from accessing classes that are meant for internal use only.
4. Packages also provide a way for separating “design” from “coding” ie first we
design classes and decide their relationships and then we can implement the java
code needed for the methods. It is possible to change the implementation of any
method without affecting the rest of the design.

There is a need to use different set of classes, one for internal representation of
our programs data and the another for external representation ie we have to build
our own classes for handling of our own data and use existing class libraries for
designing user interfaces.

Classification of Java Packages:


Java packages are classified into 2 types namely
1. Java API Packages(Builtin)
2. Defined Packages(User Defined)

Java API Packages(Builtin)


Java API provides number of classes grouped into different packages according
to functionality.

PACKAGE NAME CONTENT

=>java.lang: Language support classes. These are classes that Java compiler
itself uses and therefore they are automatically imported which include classes for
primitive types, strings, math functions, threads and exceptions.
=>java.util: Language utility classes like vectors, hash tables ,random numbers,
date etc
=>java.io: Input/Output support classes. They provide facilities for input
and output of data
=>java.awt : Set of classes for implementing graphical user interfaces(GUI).
They include classes for windows, buttons, lists, menus and so on.
=>java.net : Classes for networking. They include classes for
communicating with local computers as well as internet servers.
=>java.applet : Classes for creating & implementing applets.

Using System Packages


Packages are organized in a hierarchical structure where package named
java contains the package named awt which in turn contains variety of classes used
for implementing GUI.

java
awt -> package containing awt package
Color
Graphics

Font -> Package containing classes


---
---
---
Image -> Classes containing methods

Ways of accessing classes stored in a package


There are two ways of accessing the classes stored in a package.
1. To use fully qualified class name of the class that we want to use is done by
using package name containing the class and then appending the class name to it
using the dot operator.

Example:
To refer the class color in the awt package
java.awt.color

where awt is a package within the package java and the hierarchy is represented
by separating the levels with dots.

2. To use a class in number of places in the program or to be used in many of the


classes contained in a package
syntax:
import packagename.classname;
or
import packagename.*;
The above statements are known as import statements imported using the keyword
import and must appear at the top of the files before any class declarations.

1) The first statement allows specified class in specified package to be imported


example:
import java.awt.color;
imports only the class color
2) The second statement imports every class contained in the package
example:
import java.awt.*;
import all the classes of awt package

Naming Conventions

Packages are named using standard java naming conventions.


1. Generally, names of packages begin with lower case letter, in order to have clear
distinction from class name.

Creating own packages:


user defined Packages can be created using the keyword package followed by
package name which must be the first statement in java source file. followed by
class definition

Syntax:

package <packagename>
public class <classname>
{
------
------
}

example:

package myfirstpackage; // package declaration


public class Firstclass // class definition
{
------
------ (body of class)
}

1. where myfirstpackage is the name of the package and the class Firstclass is a
class which is a part of this package myfirstpackage.
2. The above should be saved as Firstclass.java and should be located in a direcory
named myfirstpackage.
When the source file is compiled, java will create .class file and stored in the
same directory
Note:
The .class files must be located in a directory that has the same name as the
packagename and this directory should be a sub directory of the directory where
classes that will import the package are located.

Steps for creating a package


1. Declare the package at the beginning of java source program using package
keyword as
package <packagename>;
2. Define the class that is to be kept in the package and declare it as public
3. Create a sub directory with name of the package under the directory where main
source files are stored
4. Store the listing as the classname.java in the sub directory created
5. Compile the file. This creates .class file in the sub directory.
(or)
at the prompt , type
d:>javac -d . filename.java
-d automatically creates a subdirectory by name of the package and copies .class
file into it.
. -> refers to current working directory
Accessing a Package
Package can be accessed either using fully qualified class name or using
shortcut approach using import statement.
The import statement can be used to search a list of packages for a particular
class.
syntax:
import package1[.package2][.package3].classname;

where package1 is the name of top level package , package2 is the name of the
package that is inside package1 and so on. Finally, class name is specified and
statement must be ended with ;.

The import statement should appear before any class definitions in a source file.
Multiple import statements are allowed.

example:
import firstPackage.secondPackage.MyClass;

After defining this statement, all the members of the class MyClass can be directly
accessed using the class name or its objects directly without using the package
name.

syntax:
import packagename.*;

Here, packagename may denote a single package or a hierarchy of packages. The


asterisk(*) indicates that the compiler should search this entire package hierarchy
when it encounters a class name which implies that we can access all classes
contained in the above package directly.

//creating a package and executing it from any directory


=>Creating a directory
C:\>md java1
C:\>cd java1
C:\java1>md pack1
C:\java1>cd pack1
C:\java1\pack1>edit Packtest.java
package pack1;
public class Packtest
{
public static void main(String args[])
{
System.out.println(“In packtest”);
}
}
=>Save and exit
=>C:\java1\pack1>set classpath=c:\java1\pack1;.;
=>compile the program
C:\java1\pack1>javac –d c:\java1\pack1 Packtest.java
=>executing the program
C:\java1\pack1>java pack1.Packtest
Output: In packtest
C:\java1\pack1>cd..
C:\java1>java pack1.Packtest
Output: In packtest
C:\java1>cd..
C:\>java pack1.Packtest
Output; In packtest

// accessing a package class from another package


=>Creating a directory
C:\>md java1
C:\>cd java1
C:\java1>md p1
C:\java1>cd p1
C;\java1\p1> edit Testpack.java

package p1;
public class Testpack
{
public void display()
{
System.out.println(“In display)
}
}

=>save and exit

C:\java1\p1>javac Testpack.java
C:\java1\p1>edit Ptest.java

import p1.Testpack;
public class Ptest
{
public static void main(String args[])
{
Testpack tp=new Testpack();
tp.display();
}
}
=>compile the program
C:\java1\p1>javac –d C:\java1\p1 Ptest.java
=>execute the program
C:\java1\p1>java Ptest
Output: In display

//Create a package called “arithmetic’ that congaing methods to deals with


arithmetic operations. Also write a program to use package.

=>create a directory

C:\>md arithmetic

C:\>cd arithmetic

C:\arithmetic>

package arithmetic;
public class Mymath

public int add(int x, int y)

return x+y;

public int sub(int x, int y)

return x-y;

public int mul(int x, int y)

return x*y;

public int div(int x, int y)

return x/y;

public int mod(int x, int y)

return x%y;

}
=>Save and exit

=>compile the program

C:\arithmetic>javac Mymath.java

C:\arithmetic>cd..

import arithmetic.*;

public class Aptest

public static void main(String args[])

Mymath m =new Mymath();

System.out.println(m.add(8,5));

System.out.println(m.sub(8,5));

System.out.println(m.mul(8,5));

System.out.println(m.div(8,5));

System.out.println(m.mod(8,5));

=>Save and exit

C:\<set classpath=C:\;.;

C:\>javac Aptest.java

C:\java Aptest
Strings

Strings represented a sequence of characters, to represent a sequence of characters


in java is by using a character array
Eg:
char charArray[ ]=new char[4];
charAraay[0]=’J’;
charAraay[1]=’a’;
charAraay[2]=’v’;
charAraay[3]=’a’;

In Java, strings are classs objects and implemented using two classes , namely
String and StringBuffer

declaration of string

String <stringname>;
stringname=new String(“string”);

ex:
String str;
Str=new String(“college”);

( or )

String <stringname>=new String(“string”);

ex:
String str=new String(“college”);

String Array
The group of strings in a single array is string array.
Syntax:

String stringname[ ]=new String[size];


Length() – returns the length of the string.
Syn:
Arrayname.length()
Ex: str.length();

String Methods:

1. toUpperCase() – converts string in lower case to uppercase


ex:
String str=new String(“college”);
String str1=str.toUpperCase();

2. toLowerCase() – converts string in upper case to lowercase


ex:
String str=new String(“COLLEGE”);
String str1=str.toLowererCase();

3. concat() – concatenates(clubs) one string string to another at the end


ex:
String str1=new String(“vaagdevi”);
String str2=new String(“college”);
String str3=str1.concat(str2);

4. equals() – compares 2 strings character by character and returns true , if both


are exactly equal otherwise false.(case sensitive)
Ex:
String str1=new String(“vaagdevi”);
String str2=new String(“vaagdevi”);
String str3=str1.equals(str2);

5. equalsIgnoreCase() – compares 2 strings character by character and returns


true , if both are equal(non case sensitive)
Ex:
String str1=new String(“vaagdevi”);
String str2=new String(“VAAGDEVI”);
String str3=str1.equals(str2);

6. replace() – replaces the old character with new character in the string
character by character/
ex:
String str=new String(“vaagdevi”);
str.replace(‘g’,’j’);

7. length() – returns the length of the string


ex:
String str=new String(“vaagdevi degree and pg college”);
str.length();

8. substr() – extracts the part of the string from the main string by extracting
number of characters from the position specified.
ex:
String str=new String(“vaagdevi degree and pg college”);
str.substr(3,4);

9. charAt() – returns the character at the position specified.


ex:
String str=new String(“vaagdevi degree and pg college”);
str.charAt(3);

write a program to implement string methods

import java.io.*;
import java.lang.*;
class stringmethods
{
public static void main(String args[])
{
String str1=new String(“vaagdevi”);
String str2=new String(“VAAGDEVI”);
String str3=new String(“college”);
System.out.println(“string length is :”+str1.length());
System.out.println(“string in uppercase is :”+str1.toUpperCase());
System.out.println(“string in lowercase is :”+str2.toLowerCase());
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
System.out.println(str1.replace(‘g’,’j’));
System.out.println(str1.substr(3));
System.out.println(str1.substr(3,4));
System.out.println(str1.charAt(3));
System.out.println(str1.length());
System.out.println(str1.concat(str3));
}
}
StringBuffer Class:

String creates strings of fixed length, StringBuffer creates strings of flexible length
that can be modified in terms of both length and co ntent.

Commonly used StringBuffer methods:

=>s1.setCharAt(n,’x’)

=>s1.append(s2)

=>s1.insert(n,s2)

=>s1.setLength(n)

Vectors:

Vector class contained in java.util package. This class can be used to create a
generic dynamic array known as vector that can hold objects of any type and any
number.

=>Arrays can be easily implemented as vectors

=>vectors are created like arrays as follows:

Vector intvect=new Vector( ); //declaring without size


Vector list=new Vector(3); //declaring with size

=>Vector possess a number of advantages over arrays:


1. It is in convenient to use vectors to store objects
2. A vector can be used to store a list of objects that may vary in size
3. We can add and delete objects from list as and when required

=>We cannot directly store simple data type in a vector, we can store only objects,
therefore we need to convert simple types to objects. This can be done using the
wrapper classes.

=>Vector methods are:


=>list.addElement(item)
=>list.elementAt(n)
=>list.size()
=>list.removeElement(item)
=>list.removeElementAt(n)
=>list.removeAllElements()
=>list.copyInto(array)
=>list.insertElementAt(item,n)

Wrapper classes:
Vectors cannot handle primitive data types like int, float, long, char, and double.
Primitive data types may be converted into objects by using the wrapper classes
contained in the java.lang package
=>Simple data types and their corresponding wrapper class types
Simple Type Wrapper class
Boolean Boolean
Char Character
Double Double
Float Float
Int Integer
Long Long
=>Converting Primitive numbers to Object number using constructor
methods:
Integer IntVal=new Integer(i); //Primitive integer to Integer object
Float FloatVal=new Float(f); //Primitive float to Float object
Double DoubleVal=new Double(d); //Primitive double to Double object
Long LongVal=new Long(l); //Primitive long to Long object

=>Converting Object numbers to Primitive numbers using typeValue()


method:
int i=IntVal.intValue(); // Object to primitive integer
float f=FloatVal.floatValue(); // Object to primitive float
long l=LongVal.longValue(); // Object to primitive long
double d=DoubleVal.doubleValue(); // Object to primitive double

=>Converting Numbers to Stringsusing toString() Method:


str=Integer.toString(i); //Primitive integer to string
str=Float..toString(f); //Primitive float to string
str=Double.toString(d); //Primitive double to string
str=Long.toString(l); //Primitive long to string

=>Converting String Objects to Numeric Objects using the Static method


ValueOf()
DoubleVal=Double.Valueof(str); //Converts String to Double Object
FloatVal=Float.Valueof(str); //Converts String to Float Object
IntVal=Integer.Valueof(str); //Converts String to Integer Object
LongVal=Long.Valueof(str); //Converts String to Long Object

=>Converting Numeric Strings to Primitive Numbers using Parsing methods:


int i=Integer.parseInt(str); //Converts String to Primitive integer
long l=Long.parseLong(str); //Converts String to Primitive long

Autoboxing and Unboxing


=>The autoboxing and unboxing feature, introduced in J2SE 5.0, the process of
handling primitive data types in collctions.
=>We can use this feature to convert primitive data types to wrapper class types
automatically.
=>The compiler generates a code implicitly to convert primitive type to the
corresponding wrapper class type and vice-versa.

For example:
Double d_object=98.42;
double d_primitive=d_object.doubleValue();

using the autoboxing and unboxing feature, we can rewrite the above code as:
Double d_object=98.42;
double d_primitive=d_object;

UNIT-III

Exception
Managing Errors & Exception Handling:
Error is bugs which make a program go wrong.
Types of Errors
1. Compile-time errors
2. Run-time Errors

Compile-time errors
These are the syntax errors which are detected and displayed by the java
compiler. Whenever compiler displays an error, it will not create the .class file. It
is therefore necessary that we fix all the errors before we can successfully compile
& run the program.

//demonstration of compile time errors


//Compile.java
class Compile
{
public static void main(String args[ ])
{
System.out.println("Have a nice day") // missing ;
}
}
o/p
Compile.java :7: ';' expected
System.out.println("Have a nice day")

Common Compile-time errors


. Mainly because of typing mistakes
. Use of = operator in place of ==
. Bad references to objects
. Missing semicolons
. Missing or mismatch of brackets in class or methods
. Use of undeclared variables
. Missing double quotes in strings
......

Run-time errors (Logical Errors)


These are those errors occurred when a program is successfully compiled
and created .class file but produces wrong result due to wrong logic i.e. produces
the output which is other than expected.

Common run-time errors


. Accessing an element that is out of the bounds of an array
. Trying to store a value into an array of an incompatible class or type
. Dividing an integer by zero
...

//demonstration of runtime errors


//Runtime.java
class Runtime
{
public static void main(String args[ ])
{
int a=20,b=15,c=15;
int p=a/(b-c); // denominator is zero
System.out.println("value of p="+p);
int q=a/(b+c);
System.out.println("value of q="+q);
}
}
o/p
java.lang.ArithemeticException: / by zero
at Runtime.main(Runtime.java:10)

- An exception is a condition caused by a runtime error in the program.


- When java interpreter encounters an error such as dividing integer by zero, it
creates an exception object and throws it.
If the exception object is not caught and handled properly, the interpreter will
display an error message as shown in above example and terminates the program.

Exception Handling:
If we want the program to be continued with the execution for the remaining code,
then we should try to catch the exception object thrown by the error condition and
then display an appropriate message for taking corrective actions. This task is
known as exception handling.
Tasks performed by error handling code
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
Categories of exceptions in java
Checked exceptions - These exceptions are explicitly handled in the code itself
with the help of try & catch blocks. Checked exceptions are extended from the
java.lang.Exception class.
. Unchecked exceptions - These exceptions are not essentially handled in the
program code, instead JVM handles such exceptions. Unchecked exceptions are
extended from the java.lang.Runtime.Exception.

NOTE : Checked & Unchecked exceptions are absolutely similar as far as their
functionality is concerned, but the difference lies only in the way they are handled.

Segments of error handling code


Basically, error handling code consists of 2 segments. One to detect errors and
to throw exceptions and the other to catch exceptions and to take appropriate
actions.
types of exceptions:
- predefined/built in exceptions
- user defined exceptions

Common Java Exceptions (predefined)


Exception type Cause of exception

ArithemeticException caused by math errors such as division


by zero.

ArrayIndexOutOfBoundException =>caused by bad array indexes.

ArrayStoreException caused when a program tries to store


the wrong type of data in an array.

FileNotFoundException =>caused by an attempt to access a


nonexistent file.

IOException caused by general I/O failures like inability


to read from a file.

NullPointerException caused by referencing a null object.

NumberFormatException caused when a conversion between strings


and number fails
OutOfMemoryException caused when there's not enough memory to
allocate a new object.
SecurityException caused when an applet tries to perform an action not
allowed by the browsers security setting.

StackOverFlowException caused when the system runs out of stack space.


StringIndexOutOfBoundException caused when a program attempts to access a
nonexistent character position in a string.
Java uses the keyword "try" to preface a block of code that is likely to cause an
error condition and "throw" an exception. A catch block defined by the keyword
"catch" catches the exception "thrown" by the try block and handles it
appropriately. The catch block is added immediately after the try block.

usage of simple try and catch statements


---------
---------
//try block
try
{
statement; //generates an exception
}
//catch block
catch (Exception-type e)
{
statement; //process the exception
}
----------
----------

- The try block can have one or more statements that could generate an exception.
If anyone statement generates an exception, the remaining statements in the block
are skipped and the execution jumps to the catch block that is placed next to the try
block.
- The catch block can also have one or more statements that are necessary to
process the exception.

NOTE : Every try statement should be followed by at least one catch statement
otherwise compilation error occur.
//demonstration of usage of try and catch block to handle arithemetic exceptio
//ExceptionArith.java
import java.lang.Exception;
class ExceptionArith
{
public static void main(String args[ ])
{
int a=10,b=5,c=5,x,y;
try
{
x=a/(b-c); //exception here
System.out.println("value of x="+x);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero ");
}
y=a/(b+c);
System.out.println("value of y="+y);
}
}

o/p
Division by Zero
y=1

//demonstration of nested try statements


//NestedTry.java
class NestedTry
{
public static void main(String args[ ])
{
try
{
int a=2,b=4,c=2,x=7,z;
int p[]={2,3,4}; //array initialization
p[3]=33;//array out of bound
try
{
z=x/((b*b)-(4*a*c));
System.out.println("value of z is "+z);
}

catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out of bounds");
}
}
}
o/p:
Array index is out of bounds

//demonstration of multiple catch blocks


//NestedCatch.java
import java.lang.Exception;
class NestedCatch
{
public static void main(String args[ ])
{
int a[ ]={5,10};
int b=5;
try
{

int x = a[2] / (b - a[0]);


}

catch(ArithmeticException e)
{
System.out.println("Division by zero");
}

catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out of bounds");
}

catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}
int y=a[1] / a[0];
System.out.println("value of y="+y);
}
}

o/p
Array index is out of bounds
value of y=2

finally statement
It is used to handle an exception that is not caught by any of the previous catch
statements. Finally block can be used to handle any exception generated within a
try block. It may be added immediately after the try block or after the last catch
block.

1)try
{
-----------
-----------
}

finally
{
----------
-----------
}

2)try
{
---------
---------
}
catch(-----)
{
------
------
}
catch(----)
{
-------
-------
}
.
.
.
finally
{
-------
------
}

NOTE : When a finally block is defined, it is guaranteed to execute, regardless of


whether or not an exception is thrown.

//usage of finally statement


// FinallyStat.java
class FinallyStat
{
public static void main(String args[ ])
{
int a[ ]={5,10};
int b=5;
try
{
int x = a[2] / b - a[0]; // a[2] does not exist since array a is having only 2
elements
}

// catch(ArithmeticException e)
// {
// System.out.println("Division by zero");
// }
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index is out of bounds");
}

catch(ArrayStoreException e)
{
System.out.println("Wrong data type");
}

finally
{
// int y=a[1] / a[0];
//System.out.println("value of y="+y);
System.out.println("Division by zero");
}
}
}

o/p
Division by zero
// Array index is out of bounds
// value of y=2

Throwing our own exceptions (user defined)


User defined (own) exceptions are defined by the user as per his requirement and
are raised explicitly when it is needed basing on a condition.
- Our own exceptions can be thrown using the keyword throw.

Syntax:
throw new throwable's subclass;
example:
throw new MyException();
throw new NumberFormatException();
//demonstration of throwing of our exception
import java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
super(message);
}
}

class TestMyException
{
public static void main(String args[ ])
{
int x=5,y=10000;
//int x=5,y=100;
try
{
float z=(float) x / (float) y; //type casting
if(z < 0.01) //raising an userdefined exception(checked) explicitly basing on
condition
{
throw new MyException("number is too small");
}
}
catch(MyException e)
{
System.out.println("Caught my exception");
System.out.println(e.getMessage( ) );
// getMessage() method displays message "Number is too small" caught by
catch block sent
// by object e
}
finally
{
System.out.println("Good Luck. Better try next time");
}
}
}

o/p
Caught my exception
Number is too small
Good Luck. Better try next time

NOTE :
The above example demonstrates the use of user-defined subclass of
Throwable class ie Exception is a subclass of Throwable and therefore
MyException is a subclass of Throwable class. An object of a class that extends
Throwable can be thrown and caught.

Throws Clause:
There could be certain situations where there is a possibility that a method
might throw certain kinds of exceptions but there is no exception handling
mechanism within the method. In such case, it is important that the method caller
is intimated explicitly that certain types of exceptions could be expected from the
caller method, and the caller must get prepared with some catching mechanism to
deal with it.
The throws clause is used in such a situation which is specified immediately
after the method declaration statement and just before the opening brace.

//use of throws
//ExampleThrows.java
import java.lang.Exception;
class ExampleThrows
{
static void divide( ) throws ArithmeticException
{
int x=22,y=0,z;
z=x/y;
System.out.println("value of z ="+z);
}
public static void main(String args[ ])
{
try
{
divide();
}
catch(ArithmeticException e)
{
System.out.println("Caught the exception "+e);
}
}
}

o/p
Caught the exception java.lang.ArithmeticException: / by zero

Multithreaded programming in Java(Multithreading):

A unique property of Java is its support for multithreading. That is java


enables us to use multiple flows of control in developing programs. Each flow of
control may be thought of as a separate tiny program or module known as thread
that run s in parallel to others. A program that contains multiple flows of control in
known as multithreaded program.
A thread is similar to a program that has a single flow of control which has a
beginning, a body, and an end, and executes commands sequentially.
Performing more than one task at a time (simultaneously) is known as
multitasking (example: windows, unix,..) but in systems terminology, it is known
as multithreading.
- Multithreading in java is a process of executing multiple threads simultaneously.
-Multithreading is a conceptual programming paradigm where a program
(process) is divided into two or more subprograms(processes), which can be
implemented at the same time parallel.
- It is important to remember that “threads running in parallel” does not really
mean that they actually run at the same time. Since, all the threads are running on a
single processor, the flows of execution is shared between the threads. The java
interpreter handles the switching of control between the threads in such as way that
it appears they are running concurrently.
- Thread is a flow of execution
For example, one subprogram can display an animation on the screen while
another may build the next animation to be displayed.
In computers, we have only one processor and doing only one thing at a time.
However, the processor switches between the processes so fast that it appears to
human beings that all of them are being done simultaneously.
Java programs, we have seen so far contain only one sequential flow of control
where the program begins, runs through a sequence of executions and finally ends.

Once initiated by the main thread, the threads A,B and C run concurrently and
share the resources jointly. It is just like a Joint Family sharing resources among all
of them.
The ability of a language to support multithreads is referred as concurrency.
Since threads in java are subprograms of a main application program and share the
same memory space, they are known as lightweight threads or lightweight
processes.
Applications of Multi Threading
Threads are extensively used in java-enabled browsers like HotJava. These
browsers can download a file to the local computer, display a web page in the
window, output another web page to a printer and so on.

Advantages of Java Multithreading


1) It enables programmers to do multiple things at one time. They can divide a
long program into threads and execute them in parallel. For example, we can send
tasks such as printing into the background and continue to perform some task in
the background and continue to perform some other task in the foreground. This
approach would considerably improve the speed of the program.
2) It doesn't block the user because threads are independent and you can perform
multiple operations at same time.
3) You can perform many operations together so it saves time.
4) Threads are independent so it doesn't affect other threads if exception occurs in
a single thread.

Difference between Multithreading and Multi tasking

Multithreading Multitasking
1.It is programming concept in which 1. It is an O/S concept in
a program or a process is divided into which multiple tasks are
two or more sub programs or threads performed simultaneously.
that are executed at the same time in
parallel.

2.It supports execution of multiple parts 2. It supports execution of


of a single program simultaneously multiple programs simul.

3. The processor has to switch between 3.The processor has to switch


different parts or threads of a program. different programs or processor
4.It is higly effiecient. 4. It is less efficient

5.A thread is the smallest unit in 5. A program or process is the


multithreading. smallest unit in a multitasking
environment.
6.It helps in developing efficient 6. It helps in developing efficient
program operating systems.

7.It is cost effective in case of 7. It is expensive in case of context switching


switching.

Creating threads:
Threads are implemented in the form of objects that contain a method called
run() which is the heart and soul of any thread.

public void run()


{
----------
---------- (statements for implementing thread)
}

The run() method should be invoked by an object of the concerned thread which
can be achieved by creating the thread and initiating it with the help of another
thread method called start().

We can create a thread by using any of the two following methods.


1) By creating a thread class
2) By converting a class to a thread

1. By creating a thread class - Define a class that extends thread class and override
its run() method with the code required by the thread.

2. By converting a class to a thread - Define a class that implements runnable


interface. The runnable interface has only one method, run() that is to be defined in
the method with the code to be executed by the thread.

Extending the thread class (Ist Method)


A class can be made as runnable as thread by extending the class java.lang.Thread
which includes the following steps
1. Declare the class as extending the Thread class
2. Implement the run() method that is responsible for executing the sequence of
code that the thread will execute
3. Create a thread object and call the start() method to initiate the thread execution.

Declaring the class

The thread class can be extended as follows

class MyThread extends Thread


{
------------
-----------
}

Implementing the run() Method


As the run() method has been inherited by the class MyThread, we have to
override this method in order to implement the code to be executed by our thread.

public void run()


{
-------------
------------- // Thread code here
}

NOTE : when a new thread is started, java call's the threads' run( ) method, so it is
in the run( ) where all the action takes place.

Starting New Thread


To create and run an instance of our thread class,

MyThread Thread1=new MyThread( );


Thread1.start( ); //invokes run( ) method

The first line initiates a new of class MyThread which just creates the object.
The thread that will run this object is not yet running. The thread is in a newborn
state.
The second line calls the start( ) method causing the thread to move into
runnable state. Then, the java runtime will schedule the thread to run by invoking
its run( ) method. Now, the thread is said to be in the running state.

// Example of using a java thread by extending thread class


//MultiThrd.java
import java.lang.Thread;
class MyThread extends Thread
{
public void run( )
{
System.out.println(" Thread is running ......" );
}
}
Class ThreadTest
{
public static void main(String args[ ])
{
MyThread t1=new MyThread();
t1.start( );
}
}

// Example of using a thread class


//ThreadTest.java
import java.lang.Thread;
class A extends Thread
{
public void run( )
{
for(int i=1;i<=5;i++) //thread code here
{
System.out.println(" From Thread A : i =" + i);
}
System.out.println(" Exit from Thread A");
}
}

class B extends Thread


{
public void run( )
{
for(int j=1;j<=5;j++)
{
System.out.println(" From Thread B : j =" + j);
}
System.out.println(" Exit from Thread B");
}
}

class C extends Thread


{
public void run( )
{
for(int k=1;k<=5;k++)
{
System.out.println(" From Thread C : k =" + k);
}
System.out.println(" Exit from Thread C");
}
}
class ThreadTest1
{
public static void main(String args[ ])
{
new A( ).start( );
new B( ).start( );
new C( ).start( );
}
}

NOTE : The program creates three threads A,B and C undertaking 3 different
tasks.

The statement,
new A( ).start( );
// in the main thread is the way of starting a thread

which is equivalent to

A threadA=new A( );
threadA.start();
Immediately after threadA is started, there will be two threads running in the
program ie main thread and the thread A. The start( ) method returns back to the
main thread immediately after invoking the run( ) method, thus allowing the main
thread to start the thread B. Similarly, it starts C thread. By the time, the main
method has reached the end of its main method, there are total of four(4) seperate
threads running in parallel.

Stopping and blocking a thread

Stopping a thread

To stop a thread from running further, stop() method can be used.


example:
threadA.stop( );
the above statement causes the thread to move to dead state.A thread also moves
to the dead state automatically when it reaches the end of its method.

Blocking a thread
A thread can also be temporarily suspended or blocked from entering into
runnable and running state by using either
sleep( ) // blocked for a specified time
suspend( ) // blocked until further orders
wait( ) // blocked until certain condition occurs

These methods cause the thread to go into blocked or not/non-runnable state. The
thread will return to the runnable state when the specified time is elapsed in the
case of sleep(), the resume() method is invoked in the case of suspend(), and the
notify() method is called in case of wait().

Life Cycle for a thread

Following are the different states that occur, during the life time of a thread
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Newborn state
when a thread is created, the thread is born and said to be in newborn state ie the
thread is not yet scheduled for running.
At this position, we can do
- schedule it for running using start() method. If scheduled, it moves to runnable
state
- kill using stop() method
Runnable state
Means that the thread is ready for execution and is waiting for the availability of
the processor. That is, the thread has joined the queue of threads that are waiting
for execution. If the thread have equal priority,
they are given time slots in round robin fashion ie First come - first serve(FIFO)
basis. This process of assigning time to threads is known as time-slicing. However,
if we want a thread to relinquish control to another thread to equal priority before it
turn comes, yield() method can be used.

Relinquishing control using yield() method

Running state
Running means the processor has given time to the thread for its execution.
The thread runs until it relinquishes control on its own or it is preempted by a
higher priority thread.A running thread may relinquish its control in one of
following situations

1. It has been suspended using suspend() which can be revived using resume(). It
is used when we want to suspend a thread for some time due to some reason but
do not want to kill it.
Relinquishing control using suspend() method

2. Sleep(time) method is used to make a thread to sleep for specified time period
where time is in milli seconds which means that thread is out of queue for some
time and thread reenters the runnable state as soon as the time period is elapsed.

Diag:Relinquishing control using sleep() method

3. Wait( ) method is used to make the thread wait until some event occurs and the
thread can be sheduled to run again using notify() method.

Daig:Relinquishing conrol using wait() method


Blocked state
A thread is said to be blocked when it is prevented from entering in to
runnable state and subsequently running state. This happens when thread is
suspended, sleeping or waiting in order to satisfy certain requirements. A blocked
thread is considered "not runnable" but not dead and therefore fully qualified to run
again.

Dead state
Every thread has a life cycle and a running thread end its life when it has
completed executing its run() method. It is a natural death. However, we can kill it
by sending the stop message to it at any state thus causing premature death to it. A
thread can be killed as soon as it is born, or while it is running or even when not is
in "not runnable"(blocked) condition.

Using thread methods


Thread class methods can be used to control the behaviour of a thread.
yield(),sleep() and stop() methods are used to move a thread from one state to
another.

//use of yield(),sleep() and stop() methods


//ThreadMethods.java
import java.lang.Exception;
import java.lang.Thread;
class A extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
if(i==1)
yield();
System.out.println("From thread A : i ="+i);
}
System.out.println("exit from thread A");
}
}

class B extends Thread


{
public void run()
{
for(int j=1;j<=5;j++)
{
System.out.println("From thread B : j ="+j);
if(j==3)
stop();
}
System.out.println("exit from thread B");
}
}

class C extends Thread


{
public void run()
{
for(int k=1;k<=5;k++)
{
System.out.println("From thread C : k ="+k);
if(k==1)
try
{
sleep(10000);
}
catch(Exception e)
{
System.out.println("exception is caught");
}
}
System.out.println("exit from thread C");
}
}

class ThreadMethods
{
public static void main(String args[ ])
{
A threadA=new A();
B threadB=new B();

C threadC=new C();

System.out.println("start thread A");


threadA.start();

System.out.println("start thread B");


threadB.start();

System.out.println("start thread C");


threadC.start();

System.out.println("End of main thread");


}
}

NOTE :
1) uses the yeild() method in thread A at the iteration i=1. Therefore, the thread A
although started first, has relinquished control to thread B. The stop() method in
thread B as killed it after implememting the for loop only 3 times. Mind that it has
not reached end of run(). (pre mature death). The thread C started sleeping after
executing the for loop only once. When it woke up (after 10000 mill seconds), the
other 2 threads have already completed their runs and therefore was running alone.
The main thread died much earlier than the other 3 threads.
2) The call to sleep( ) method is enclosed in a try block and followed by catch
block() which is necessary because the sleep( ) method throws an exception which
should be caught.If we fail to catch the exception, program will not compile.

Thread Exceptions
Java run system will throw illegalThreadStateException whenever attempt is
made to invoke a method that a thread cannot handle in given state. For example, a
sleeping thread cannot deal with the resume() method because a sleeping thread
cannot receive any instructions and the same is true for suspend() method when it
is used on a blocked(Not Runnable) state.

Whenever we call a thread that is likely to throw an exception, we have to supply


an appropriate handler to catch it which may take any of the following form

catch (ThreadDeath e)
{
----------- // killed thread
-----------
}

catch(Interruptedexception e)
{

----------- // cannot handle it in current state


-----------
}

catch(IllegalArithmeticException e)
{

----------- // Illegal method argument


-----------
}
catch(Exception e)
{

----------- // Any other


-----------
}

Thread Priority
In java, each thread is assigned a priority, which effects the order in which
it is scheduled for running. The threads which are discussed so far are of same
priority. The threads of the same priority are given equal treatment by java
scheduler, they share the processor on first come, first serve basis.
Priority of a thread can be set using setPriority() method
syntax:
Threadname.setPriority(intNumber);

intNumber is an integer value to which thread's priority is set. The Thread class
defines several priority constants

MIN_PRIORITY=1
NORM_PRIORITY=5(default)
MAX_PRIORITY=10

NOTE:default setting is NORM_PRIORITY

Whenever multiple threads are available for execution, the Java system
chooses the highest priority thread and executes it.
For a thread of lower priority to gain control, one of the following things should
happen
1. It stops running at the end of run( )
2. It is made to sleep using sleep( )
3. It is hold to wait using wait( )
However, if another thread of highest priority comes along, currently running
thread will be preempted by incoming thread thus forcing the current thread to
move to the runnable state.

//demonstration of priority of threads -


//ThreadPriority.java
import java.lang.Thread;
class A extends Thread
{
public void run( )
{
System.out.println("Thread A started" );
for(int i=1;i<=4;i++) //thread code here
{
System.out.println(" \t From Thread A : i =" + i);
}
System.out.println(" Exit from Thread A");
}
}

class B extends Thread


{
public void run( )
{
System.out.println("Thread B started" );
for(int j=1;j<=4;j++)
{
System.out.println("\tFrom Thread B : j =" + j);
}
System.out.println(" Exit from Thread B");
}
}

class C extends Thread


{
public void run( )
{
System.out.println("Thread C started" );
for(int k=1;k<=4;k++)
{
System.out.println(" From Thread C : k =" + k);
}
System.out.println(" Exit from Thread C");
}
}

class ThreadPriority
{
public static void main(String args[ ])
{
A threadA=new A();
B threadB=new B();
C threadC=new C();
threadC.setPriority(Thread.MAX_PRIORITY);
// threadB.setPriority(threadA.getPriority()+1);
threadB.setPriority(Thread.NORM_PRIORITY);
threadA.setPriority(Thread.MIN_PRIORITY);

System.out.println("Start Thread A");


threadA.start();

System.out.println("Start Thread B");


threadB.start();

System.out.println("Start Thread C");


threadC.start();

System.out.println("End of Main Thread");


}
}
Synchronization
Depending on the situation, we may get strange results when they try to use
data and methods outside themselves that lead to serious problems. Java enables us
to overcome this problem using technique known as synchronization.

Synchronized void update()


{
-------------------- /code here is synchronized
-------------------
}

When we declare a method synchronized, java creates a “mirror” and hands


it over to the thread that calls the method first time. As long as the thread holds the
monitor, no other thread can enter the synchronized section of code. A monitor is
like a key and thread that holds the key can only open the lock.

Synchronized (lock-object)
{
---------------- // code here is synchronized
---------------
}

Whenever a thread has completed its work of using synchronized method (or
block of code), it will hand over the monitor to the next thread that is ready to use
the same resource.
An interesting situation may occur when two or more threads are waiting to
gain control of a resource. Due to some reasons, the condition on which the
waiting threads rely on to gain control does not happen. These results what is
known as deadlock?
For example, assume that the thread A must access method1 before it can
release method2 but the thread B cannot release method1 until it get holds of
method2. Because these are mutually exclusive conditions, a deadlock occurs.

Thread A
{
Synchronized method2()
{
Synchronized method1()
{
-------
-------
}
}

Thread B
{
Synchronized method1()
{
Synchronized method2()
{
-------
-------
}
}

Implementing the Runnable Interface(II nd Method)


As we know that a thread can be created in 2 ways namely
1. using the extended thread class
2. implementing runnable interface

Implementing runnable interface


Runnable interface declares the run() method that is required for
implementing thread in our programs.
Steps:
1. declare the class as implementing the runnable interface
2. implement the run () method
3. create a thread by defining an object that is instantiated from the “runnable”
class as the target of the thread
4. call the thread start() method to run the thread

// Runnable interface
//RunnableTest.java
class X implements Runnable //step1
{
public void run() // step2
{
for(int i=1;i<=10;i++)
{
System.out.println("Thread x="+i);
}
System.out.println("End of Thread X");
}
}

class RunnableTest
{
public static void main(String args[])
{
X Runnable = new X();
Thread threadx = new Thread(Runnable); //step 3
threadx.start(); //step 4
System.out.println("end of main threead");
}
}
Java I/O (Input and Output)

is used to process the input and produce the output.

Java uses the concept of a stream to make I/O operation fast. The java.io package
contains all the classes required for input and output operations.

Stream

A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a


stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached
with the console.

1) System.out: standard output stream

2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an err

or message to the console.

1. System.out.println("simple message");
2. System.err.println("error message");

Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character


2. System.out.println((char)i);//will print the character

OutputStream

Java application uses an output stream to write data to a destination; it may be a


file, an array, peripheral device or socket.

InputStream
Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.

Let's understand the working of Java OutputStream and InputStream by the figure
given below.

OutputStream class

OutputStream class is an abstract class. It is the superclass of all classes


representing an output stream of bytes. An output stream accepts output bytes and
sends them to some sink.

Useful methods of OutputStream

Method Description

1) public void write(int)throws is used to write a byte to the


IOException current output stream.

2) public void is used to write an array of byte to


write(byte[])throws the current output stream.
IOException

3) public void flush()throws flushes the current output stream.


IOException

4) public void close()throws is used to close the current output


IOException stream.

OutputStream Hierarchy

InputStream class

InputStream class is an abstract class. It is the superclass of all classes representing


an input stream of bytes.

Useful methods of InputStream

Method Description

1) public abstract int reads the next byte of data from the
read()throws IOException input stream. It returns -1 at the end of
the file.
2) public int returns an estimate of the number of
available()throws bytes that can be read from the current
IOException input stream.

3) public void is used to close the current input


close()throws IOException stream.

InputStream Hierarchy

Java FileOutputStream Class

Java FileOutputStream is an output stream used for writing data to a file

If you have to write primitive values into a file, use FileOutputStream class. You
can write byte-oriented as well as character-oriented data through
FileOutputStream class. But, for character-oriented data, it is preferred to
use FileWriter
FileOutputStream class declaration

Let's see the declaration for Java.io.FileOutputStream class:

public class FileOutputStream extends OutputStream

FileOutputStream class methods


Method Description

protected void It is used to clean up the connection with the


finalize() file output stream.

void write(byte[] ary) It is used to write ary.length bytes from the


byte array

to the file output stream.

void write(byte[] ary, It is used to write len bytes from the byte
int off, int len) array starting at offset off to the file output
stream.

void write(int b) It is used to write the specified byte to the file


output stream.

FileChannel It is used to return the file channel object


getChannel() associated with the file output stream.

FileDescriptor It is used to return the file descriptor


getFD() associated with the stream.

void close() It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
fout.write(65);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Java FileOutputStream example 2: write string

import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
String s="Welcome to java ";
byte b[]=s.getBytes();//converting string into byte array
fout.write(b);
fout.close();
System.out.println("success...");
}catch(Exception e){System.out.println(e);}
}
}
Java FileInputStream Class

Java FileInputStream class obtains input bytes from a file. It is used for reading
byte-oriented data (streams of raw bytes) such as image data, audio, video etc. You
can also read character-stream data. But, for reading streams of characters, it is
recommended to use FileReader class.

Java FileInputStream class declaration

Let's see the declaration for java.io.FileInputStream class:

public class FileInputStream extends InputStream


Java FileInputStream class methods
Method Description

int available() It is used to return the estimated number of


bytes that can be read from the input stream.

int read() It is used to read the byte of data from the input
stream.

int read(byte[] b) It is used to read up to b.length bytes of data


from the input stream.

int read(byte[] b, It is used to read up to len bytes of data from


int off, int len) the input stream.

long skip(long x) It is used to skip over and discards x bytes of


data from the input stream.

FileChannel It is used to return the unique FileChannel


getChannel() object associated with the file input stream.

FileDescriptor It is used to return the FileDescriptor object.


getFD()

protected void It is used to ensure that the close method is call


finalize() when there is no more reference to the file input
stream.

void close() It is used to closes the stream.

Java FileInputStream example 1: read single character


import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=fin.read();
System.out.print((char)i);

fin.close();
}catch(Exception e){System.out.println(e);}
}
}
Note: Before running the code, a text file named as "testout.txt" is required to be
created.

Java FileInputStream example 2: read all characters

import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream("D:\\testout.txt");
int i=0;
while((i=fin.read())!=-1){
System.out.print((char)i);
}
fin.close();
}catch(Exception e){System.out.println(e);}
}
}

UNIT-IV
Applets
Applications written for www is commonly referred as applets. Applets are
web based applications which are used to write GUI applications.
Types of applets
Applets can be embedded into WebPages in 2 ways i.e we can write our own
applets and embed them into web pages or down load from remote system and
embed into webpage.

1. local applets
2. remote applets

local applet - an applet developed locally and stored in a local system is known as
local applet.

remote applet - applets downloaded from internet(remote computer/server) and


embedded in your webpage are known as remote applets.

chain of classes inherited by applet class


java.lang.Object
|

java.awt.Component
|
java.awt.Container
|
java.awt.Panel
|
java.applet.Applet

Applet class itself is a subclass of Panel class which is again a subclass of


Container class and so on. This shows that applet class inherits properties from a
long chain of classes. An applet can therefore, use variables and methods from all
these classes.

life cycle of applet


Methods in the life cycle of an applet

life cycle of an applet includes following states


- born or initialization state
- running state
- idle state
- dead or destroyed state

born or initialization state


Applet enters into this state when it is first loaded and is achieved by calling init()
method of Applet class.
At this stage , we may do the following
- create objects needed by the applet
- set up initial values
- load images or fonts
- set up colors

note : initialization occurs only once in the applet life cycle

public void init()


{
====
==== (action)
}

running state
Applet enters into this state when the system calls the start() method of Applet
class which occurs automatically after the applet is initialized .
Starting can also occur , if the applet is already in "stopped"(idle) state.

public void start()


{
====
==== (action)
}

Idle or Stopped state


An applet becomes idle when it is stopped from running. Stopping occurs
automatically when we leave the page containing the currently running applet. We
can do also by calling explicitly stop() method.

public void stop()


{
====
==== (action)
}

Dead state
An applet is said to be dead when it is removed from memory which occurs
automatically by invoking the destroy() method when we quit the browser.
NOTE : like initialization, destroying stage occurs only once in the applets life
cycle.

public void destroy()


{
====
==== (action)
}

Display state
Applet moves to display state whenever it has to perform output operations on
the screen which happens immediately after the applet enter into running state.
paint() method is called to accomplish the task.

public void paint(Graphics g)


{
====
==== (display statements)
}

steps for developing an applet


1: built an applet code (.java file)
2: create an executable applet (.class file)
3. design a web page using HTML tags
4: embedding <applet> tag into web page
5: create an HTML file
6: test the applet code using applet viewer
building applet code(java program)
import java.awt.*;
import java.applet.*;
-----
public class appletclassname extends Applet
{
---
}

public void paint(Graphics g) //applet code imports the java.awt package that
contains the Graphics class
{
---- //applet code here
}

HTML - stands for Hyper text markup language


- it is a scripting language used for designing WebPages
- written in notepad and saved as .html file

designing a web page


As java applets are programs that reside on web pages, it is necesary to have a
web page that reference that applet to run a java applet.
A web page is made up of text and HTMl tags that can be interpreted by a web
browser or an applet viewer. Web page are stored using file extension .HTML such
as myfile.html.
A web page is marked by an opening HTML tag <HTML> and closing HTML
tag </HTML> and is divided into 3 sections
1) Comment section (optional) - contains commenta about the web page. A
comment line begins iwth <! and ends with >.
2) Head section(optional)
it is defined with <HEAD> tag and closing </HEAD> tag. It contains title for the
web page as
<HEAD>
<TITLE> Welcome to java Applets </TITLE>
</HEAD>
note : the text enclosed in the tags <TITLE> and </TITLE> will appear in the title
bar of the web browser.

3) Body section - it contains the information about the web page and its behaviour.
<BODY>
<CENTER>
<H1> Welcome to the world of Applets </H1>
</CENTER>
<BR>
<APPLET ------>
</APPLET>
</BODY>

Applet tag
The <APPLET ...> tag supplies the name of the applet to be loaded and tells the
browser how much space the applet requires.
<BODY>
<CENTER>
<APPLET>
=======
=======
</APPLET>
</CENTER>
</BODY>

EX: Adding Applet to HTML file


<APPLET
CODE=hellojava.class
WIDTH=400
HEIGHT=200>
</APPLET>
Note : <Applet> tag specifies
- name of the applet
- width of the applet(in pixels)
- height of the applet(in pixels)
Running the applet
To run an applet, we need either of the tools
1) java enabled web browser(like Hot Java or Netcape)
2) Java Applet Viewer (as part of JDK)

Running the applet using Applet Viewer


d:\rjv> appletviewer hellojava.html
attributes of applet tag

1) code=AppletFileName.class specifies the name of the applet class to be


loaded
2) codebase=codebase-URL specifies the URL of the directory in which
appplet resides
3) width=pixels specifies the width & height of the space on
HTML page that will be reserved for
applet
height=pixels
4) name=applet-instance-name specifies the name for the applet so
that other applets on the page may
refer to the applet

//JAVA PROGRAM FOR CREATION OF APPLET

//HelloJava.java
import java.io.*;
import java.awt.*;
import java.applet.*;

public class HelloJava extends Applet


{
public void paint(Graphics g)
{
g.drawString("Welcome to applet programming",10,100);
}
}

note : compile HelloJava.java file which creates HelloJava.class file

//CREATION OF HTML PROGRAM WHERE LOCAL APPLET CAN BE


EMBEDDED
//HelloJava.html
<HTML>
<head>
<title> working with applets </title>
</head>
<body>

<center> welcome to Applets Environment </center>


<applet code=HelloJava.class width=400 height=200>
</applet>
</body>
</html>

running html file(applet)


HTML file can be run, using appletviewer browser from command prompt as

d:\rjv>appletviewer HelloJava.html

HTML - stands for Hyper text markup language


- it is a scripting language used for designing webpages
- written in notepad and saved as .html file

structure of HTML program

<HTML>
<HEAD>
---
<TITLE> ----- </TITLE>
<BODY>
----
----
</BODY>
</HEAD>
</HTML>

Working with HTML


- open notepad editior by chosing start->notepad->ok
- type html code
- save file as .HTML

passing parameters to applets


user defined parameters can be supplied to an applet using <PARAM...> tags
where each param tag has a name attribute like color and a value attribute such as
red.

ex:
<APPLET>
<PARAM = COLOR VALUE="red">
</APPLET

Similarly, text to be displayed by an applet can be changed by supplying new text


to the applet thru <PARM ..> tag as

ex:
<APPLET>
<PARAM NAME=text VALUE = " JAVA IS TRUE OOPL">
</APPLET>
NOTE : passing parameters to an applet code using <PARAM> tag is similar to
passing parameters to main() method using command line arguments which are
passed to an applet when it is loaded.
To set up and handle parameters,

1. include <PARAM ...> tags in HTML document


2. provide code in the applet to parse these parameters

//java program
//HelloJavaParameter.java
import java.io.*;
import java.awt.*;

public class HelloJavaParameter extends Applet


{
String str;
public void init()
{
str=getParameter("String");
if(str = = null)
str="JAVA";

str="HELLO"+str;
}
public void paint(Graphics g)
{
g.drawString(str,10,100);
}
}
o/p HELLOApplet!

note : now remove <PARAM> Tag from HTML file and run again.
//HelloJavaParameter.html
//HTML program
<HTML>
<!Parameterized HTML file with PARAM TAG>
<HEAD>
<TITLE>Welcome to java Applets </TITLE>
</HEAD>
<BODY>
<APPLET CODE="HelloJavaParameter.class width=400 height=200>
<PARAM NAME="string" value ="Applet!">
</APPLET>
</BODY>
</HTML>

Running an applet
d:\rjv>appletviewer HelloJavaParameter.html

//HelloJavaParameter1.html
//HTML program
<HTML>
<!Parameterized HTML file without PARAM TAG>
<HEAD>
<TITLE>Welcome to java Applets </TITLE>
</HEAD>
<BODY>
<APPLET CODE="HelloJavaParameter.class"
width=500
height=200 >
// <!PARAM NAME="string" value ="Applet!">
</APPLET>
</BODY>
</HTML>

aligning(adjusting) the display


The output of the applet can be aligned using the ALIGN attribute whose values
can be left,right,top,middle,bottom etc.
ex:
<APPLET CODE="HelloJavaParameter.class"
width=500
height=200
align=right>

//JAVA PROGRAM FOR CREATION OF APPLET with alignment

//not getting correct o/p


//align.java
import java.io.*;
import java.awt.*;
import java.applet.*;

public class align extends Applet


{
public void paint(Graphics g)
{
g.drawString("Welcome to applet programming with alignment",10,100);
}
}

//HTML program
<!align.html>
<html>
<body>
<APPLET CODE=align.class
width=500
height=200
align=right>
</applet>
</body>
</html>
Displaying numerical values
In Applets, numerical values can be displayed by first converting them into
strings and then using the drawString() of Graphics class which can be done easily
by calling ValueOf() method of String class.

//displaying numerical valuess


//NumValues.java
import java.io.*;
import java.awt.*;
public class NumValues extends Applet
{
public class paint(Graphics g)
{
int value1=10;
int value2=20;
int sum=value1+value2;
String s ="sum :"+String.ValueOf(sum);
g.drawString(s,100,1000);
}
}

//HTML program to display numerical values


<HTML>
<!displaying numerical values>

<BODY>
<APPLET CODE="NumValues.class"
width=300
height=300 >
</APPLET>
</BODY>
</HTML>
getting/reading values/input from the user
Applets treats inputs as text string. so, we must first create an area of the
screen in which user type and edit input items which can be done using textField
class of applet package.
Once the text fields are create fro receiving input, we can type values in the fields
and edit.
secondly, is to retrieve the items from the fileds for display of calculations.
note : text fields contain items in string form which need to converted to the
correct form.

// getting input from the user


//UserInput.java
import java.awt.*;
import java.applet.*;
public class UserInput extends Applet
{
TextField text1,text2;
public void init()
{
text1=new TextField(8);
text2=new TextField(8);
add(text1);s
add(text2);
text1.setText("0");
text2.setText("0");
}

public void paint(Graphics g)


{
int x=0,y=0,z=0;
String s1,s2,s;
g.drawString("Input a number in each box",10,50);
try
{
s1=text1.getText();
x=Integer.parseInt(s1);

s2=text2.getText();
y=Integer.parseInt(s2);
}

catch(Exception ex)
{ }

z=x+y;
s=String.valueOf(z);
g.drawString("sum is :",10,75);
g.drawString(s,100,75);
}

//public Boolean action(Event event, Object object)


//{
// repaint();
//return true;
// }

//HTML program
//UserInput.html
<!getting input from user>
<html>
<applet
code=UserInput.class
width=300
height=200 >
</applet>
</html>

running an applet
d:\rjv>appletviewer UserInput.html

Java Event Handling

The java.awt.event package provides many event classes and Listener


interfaces for event handling.

Java Event classes and Listener interfaces


Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener
ContainerEvent ContainerListener

FocusEvent FocusListener

Java Event Handling Code

We can put the event handling code into one of the following places:

1. Within class
2. Other class
3. Anonymous class

Java event handling by implementing ActionListener

import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);

//register listener
b.addActionListener(this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}

public void setBounds(int xaxis, int yaxis, int width, int height); have been used
in the above example that sets the position of the component it may be button,
textfield etc.

Java AWT Button

A button is basically a control component with a label that generates an event


when pushed. The Button class is used to create a labeled button that has platform
independent implementation. The application result in some action when the button
is pushed.

When we press a button and release it, AWT sends an instance of ActionEvent to
that button by calling processEvent on the button. The processEvent method of
the button receives the all the events, then it passes an action event by calling its
own method processActionEvent. This method passes the action event on to
action listeners that are interested in the action events generated by the button.

To perform an action on a button being pressed and released,


the ActionListener interface needs to be implemented. The registered new listener
can receive events from the button by calling addActionListener method of the
button. The Java application can use the button's action command as a messaging
protocol.

AWT Button Class Declaration

public class Button extends Component implements Accessible

Java AWT Button Example


import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {

// create instance of frame with the label


Frame f = new Frame("Button Example");
// create instance of button with label
Button b = new Button("Click Here");

// set the position for the button in frame


b.setBounds(50,100,80,30);

// add button to the frame


f.add(b);
// set size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Java AWT Label

The object

of the Label class is a component for placing text in a container. It is used to


display a single line of read only text. The text can be changed by a programmer
but a user cannot edit it directly.

It is called a passive control as it does not create any event when it is accessed. To
create a label, we need to create the object of Label class.

AWT Label Class Declaration

public class Label extends Component implements Accessible

AWT Label Fields

The java.awt.Component class has following fields:

1. static int LEFT: It specifies that the label should be left justified.
2. static int RIGHT: It specifies that the label should be right justified.
3. static int CENTER: It specifies that the label should be placed in center.
Java AWT Label Example

In the following example, we are creating two labels l1 and l2 using the
Label(String text) constructor and adding them into the frame.

import java.awt.*;
public class LabelExample {
public static void main(String args[]){

// creating the object of Frame class and Label class


Frame f = new Frame ("Label example");
Label l1, l2;

// initializing the labels


l1 = new Label ("First Label.");
l2 = new Label ("Second Label.");

// set the location of label


l1.setBounds(50, 100, 100, 30);
l2.setBounds(50, 150, 100, 30);

// adding labels to the frame


f.add(l1);
f.add(l2);

// setting size, layout and visibility of frame


f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Java AWT TextField

The object of a TextField class is a text component that allows a user to enter a
single line text and edit it. It inherits TextComponent class, which further
inherits Component class.
When we enter a key in the text field (like key pressed, key released or key typed),
the event is sent to TextField. Then the KeyEvent is passed to the
registered KeyListener. It can also be done using ActionEvent; if the ActionEvent
is enabled on the text field, then the ActionEvent may be fired by pressing return
key. The event is handled by the ActionListener interface.

AWT TextField Class Declaration


1. public class TextField extends TextComponent
Method Inherited

The AWT TextField class inherits the methods from below classes:

java.awt.TextComponent

java.awt.Component

java.lang.Object

import java.awt.*;
public class TextFieldExample1 {
// main method
public static void main(String args[]) {
// creating a frame
Frame f = new Frame("TextField Example");

// creating objects of textfield


TextField t1, t2;
// instantiating the textfield objects
// setting the location of those objects in the frame
t1 = new TextField("Welcome to events.");
t1.setBounds(50, 100, 200, 30);
t2 = new TextField("AWT events");
t2.setBounds(50, 150, 200, 30);
// adding the components to frame
f.add(t1);
f.add(t2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT TextArea

The object of a TextArea class is a multiline region that displays text. It allows the
editing of multiple line text. It inherits TextComponent class.

The text area allows us to type as much text as we want. When the text in the text
area becomes larger than the viewable area, the scroll bar appears automatically
which helps us to scroll the text up and down, or right and left.

AWT TextArea Class Declaration


1. public class TextArea extends TextComponent
Fields of TextArea Class

The fields of java.awt.TextArea class are as follows:

o static int SCROLLBARS_BOTH - It creates and displays both horizontal


and vertical scrollbars.
o static int SCROLLBARS_HORIZONTAL_ONLY - It creates and
displays only the horizontal scrollbar.
o static int SCROLLBARS_VERTICAL_ONLY - It creates and displays
only the vertical scrollbar.
o static int SCROLLBARS_NONE - It doesn't create or display any
scrollbar in the text area.

Java AWT TextArea Example

The below example illustrates the simple implementation of TextArea where we


are creating a text area using the constructor TextArea(String text) and adding it to
the frame.

//importing AWT class


import java.awt.*;
public class TextAreaExample
{
// constructor to initialize
TextAreaExample() {
// creating a frame
Frame f = new Frame();
// creating a text area
TextArea area = new TextArea("Welcome to events ");
// setting location of text area in frame
area.setBounds(10, 30, 300, 300);
// adding text area to frame
f.add(area);
// setting size, layout and visibility of frame
f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new TextAreaExample();
}
}

Java AWT Checkbox

The Checkbox class is used to create a checkbox. It is used to turn an option on


(true) or off (false). Clicking on a Checkbox changes its state from "on" to "off" or
from "off" to "on".

AWT Checkbox Class Declaration


1. public class Checkbox extends Component implements ItemSelectable, Accessible
Method inherited by Checkbox

The methods of Checkbox class are inherited by following classes:

o java.awt.Component
o java.lang.Object

Java AWT Checkbox Example

In the following example we are creating two checkboxes using the


Checkbox(String label) constructor and adding them into the Frame using add()
method.

import java.awt.*;
public class CheckboxExample1
{
// constructor to initialize
CheckboxExample1() {
// creating the frame with the title
Frame f = new Frame("Checkbox Example");
// creating the checkboxes
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100, 100, 50, 50);
Checkbox checkbox2 = new Checkbox("Java", true);
// setting location of checkbox in frame
checkbox2.setBounds(100, 150, 50, 50);
// adding checkboxes to frame
f.add(checkbox1);
f.add(checkbox2);

// setting size, layout and visibility of frame


f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
// main method
public static void main (String args[])
{
new CheckboxExample1();
}
}
Java AWT CheckboxGroup

The object of CheckboxGroup class is used to group together a set of Checkbox.


At a time only one check box button is allowed to be in "on" state and remaining
check box button in "off" state. It inherits the object class.

AWT CheckboxGroup Class Declaration


public class CheckboxGroup extends Object implements Serializable
Java AWT CheckboxGroup Example

import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroup cbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
Java AWT Choice

The object of Choice class is used to show popup menu of choices. Choice selected
by user is shown on the top of a menu. It inherits Component class.

AWT Choice Class Declaration


1. public class Choice extends Component implements ItemSelectable, Accessible
Methods inherited by class

The methods of Choice class are inherited by following classes:

o java.awt.Component
o java.lang.Object

Java AWT Choice Example

In the following example, we are creating a choice menu using Choice()


constructor. Then we add 5 items to the menu using add() method and Then add
the choice menu into the Frame.

import java.awt.*;
public class ChoiceExample1 {

// class constructor
ChoiceExample1() {

// creating a frame
Frame f = new Frame();

// creating a choice component


Choice c = new Choice();

// setting the bounds of choice menu


c.setBounds(100, 100, 75, 75);

// adding items to the choice menu


c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");

// adding choice menu to frame


f.add(c);

// setting size, layout and visibility of frame


f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}

// main method
public static void main(String args[])
{
new ChoiceExample1();
}
}
Java AWT List

The object of List class represents a list of text items. With the help of the List
class, user can choose either one item or multiple items. It inherits the Component
class.

AWT List class Declaration


1. public class List extends Component implements ItemSelectable, Accessible
Java AWT List Example

In the following example, we are creating a List component with 5 rows and
adding it into the Frame.

import java.awt.*;

public class ListExample1


{
// class constructor
ListExample1() {
// creating the frame
Frame f = new Frame();
// creating the list of 5 rows
List l1 = new List(5);

// setting the position of list component


l1.setBounds(100, 100, 75, 75);

// adding list items into the list


l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");

// adding the list to frame


f.add(l1);

// setting size, layout and visibility of frame


f.setSize(400, 400);
f.setLayout(null);
f.setVisible(true);
}

// main method
public static void main(String args[])
{
new ListExample1();
}
}

Java Swing

Java Swing is a part of Java Foundation Classes (JFC) that is used to create
window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.

Unlike AWT, Java Swing provides platform-independent and lightweight


components.

The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing

1) AWT components are platform- Java swing components


dependent. are platform-
independent.

2) AWT components Swing components


are heavyweight. are lightweight.
3) AWT doesn't support pluggable Swing supports pluggable
look and feel. look and feel.

4) AWT provides less Swing provides more


components than Swing. powerful
components such as
tables, lists, scrollpanes,
colorchooser, tabbedpane
etc.

5) AWT doesn't follows Swing follows MVC.


MVC(Model View Controller)
where model represents data,
view represents presentation and
controller acts as an interface
between model and view.

What is JFC

The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications.

The hierarchy of java swing API is given below.


Java Swing Examples

There are two ways to create a frame:

o By creating the object of Frame class (association)


o By extending Frame class (inheritance)

We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example

Let's see a simple swing example where we are creating one button and adding it
on the JFrame object inside the main() method.
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
}
}

Example of Swing by Association inside constructor

We can also write all the codes of creating JFrame, JButton and method call inside
the java constructor.

import javax.swing.*;
public class Simple {
JFrame f;
Simple(){
f=new JFrame();//creating instance of JFrame

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


b.setBounds(130,100,100, 40);

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
}

public static void main(String[] args) {


new Simple();
}
}

The setBounds(int xaxis, int yaxis, int width, int height)is used in the above
example that sets the position of the button.

Simple example of Swing by inheritance

We can also inherit the JFrame class, so there is no need to create the instance of
JFrame class explicitly.

import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);

add(b);//adding button on frame


setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}
}

Java JButton

The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It
inherits AbstractButton class.

JButton class declaration

Let's see the declaration for javax.swing.JButton class.

1. public class JButton extends AbstractButton implements Accessible


Java JButton Example
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}

Java JLabel

The object of JLabel class is a component for placing text in a container. It is used
to display a single line of read only text. The text can be changed by an application
but a user cannot edit it directly. It inherits JComponent class.

JLabel class declaration

Let's see the declaration for javax.swing.JLabel class.

1. public class JLabel extends JComponent implements SwingConstants, Accessible


Java JLabel Example

import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;
l1=new JLabel("First Label.");
l1.setBounds(50,50, 100,30);
l2=new JLabel("Second Label.");
l2.setBounds(50,100, 100,30);
f.add(l1); f.add(l2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}

You might also like