Oops Final Contents
Oops Final Contents
CHAPTER 1
Example:
1) Class : student
Object: kavitha, Ahila
2) Class : Department
Object: EEE, ECE, CSE
Classes in Java
public class student
{
int rollno;
int age;
void input()
{
Variables in class }
● }
Local variables
Variables defined inside methods, constructors or blocks are called local variables.
● Instance variables
Instance variables are variables within a class but outside any method.
● Class variables
Class variables are variables declared within a class, outside any method, with the static keyword.
Objects
Class
1. For a single class, we can create many 1. For many objects, We can create one
objects. single class.
2. We cannot assign values to class 2. We can assign values to objects
3. Memory is not allocated once class is 3. Memory is allocated once object is created.
created
1.1.2 ABSTRACTION
It refers to the act of representing essential features without including the background details or
explanations. It is one of the key concepts of object-oriented programming (OOP) languages. Its
main goal is to handle complexity by hiding unnecessary details from the user.
For example, people do not think of a car as a set of tens of thousands of individual parts. They
think of it as a well-defined object with its own unique behavior. This abstraction allows people to
use a car to drive to the desired location without worrying about the complexity of the parts that
form the car. They can ignore the details of how the engine, transmission, and braking systems
work. Instead, they are free to utilize the object as a whole.
Abstarction in Java
● In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100%
abstraction using interfaces.
1.1.3 ENCAPSULATION
Encapsulation is the process of combining data and functions into a single unit. In Java, the basis
of encapsulation is the class. Encapsulation achieves the concept of data hiding.
Data hiding: Data inside the class is accessible only through the function within the class
Advantage of Encapsulation
● It provides you the control over the data.
● It is a way to achieve data hiding in Java because other class will not be able to access the
data through the private data members.
● The encapsulate class is easy to test. So, it is better for unit testing.
Abstarction Encapsulation
1. It refers to the act of representing essential 1. Encapsulation is the process of combining
features without including the background data and functions into a single unit. In Java,
details or explanations. the basis of encapsulation is the class
2. It is used in the design phase. 2. It is used in the implementation phase.
1.1.4 INHERITANCE
Inheritance is the process of forming new class from the existing class.
● Existing class is also called as parent class or base class or super class.
● New class is also called as child class or derived class.
For example,
● Animal is the base class.
● Mammal and reptile are the deived class of Animal. So they inherits the properties from
Animal base class.
● Whale and Dog are the derived class of Mammal. So they inherits the properties from
mammal base class.
Advantage of Inheritance
1. Reusability
2. Reducing the code size of program.
3. Sub class inherits all the properties from base class.
1.1.5 POLYMORPHISM
Polymorphism is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs.
● The word "poly" means many
● "morphs" means forms.
● So polymorphism means many forms.
Example:
Here,
● Shape is the base class.
● In the Circle class, draw() is used to draw the circle.
● In the Rectangle class, draw() is used to draw the rectangle.
● In the Triangle class, draw() is used to draw the triangle.
1.2 OOP CONCEPTS IN JAVA- CHARACTERISTICS OF JAVA
Java is a object oriented, platform independent, portable, compiled and interpreted programming
language. Java is an object-oriented programming language developed by James Gosling and
colleagues at Sun Microsystems in the early 1990s. Java was started as a project called "Oak" by
James Gosling in June 1991.
Characteristics Of Java are following:
1. Simple
2. Secure
3. Portable
4. Platform independent
5. Object-oriented
6. Robust
7. Multithreaded
8. Architecture-neutral
9. Interpreted
10. High performance :
11. Distributed
12. Dynamic
Simple :
● Java is Easy to write and more readable.
● Java has a concise, cohesive set of features that makes it easy to learn and use.
Secure :
● Java program cannot harm other system
● Java provides a secure means of creating Internet applications.
● Java provides secure way to access web applications.
Portable :
● Java programs can be transferred over world wide web (e.g applets)
Platform independent:
● Programs in java can be executed on a variety of platforms.
Object-oriented :
● Java programming is object-oriented programming language.
● Like C++, java provides most of the object oriented features.
● Java is pure OOP Language. (while C++ is semi object oriented)
Robust :
● Java encourages error-free programming by being strictly typed and performing run-time
checks.
Multithreaded :
● Java provides integrated support for multithreaded programming.
Architecture-neutral :
● Java is not tied to a specific machine or operating system architecture.
● Java is machine independent.
Interpreted :
● Java supports cross-platform code through the use of Java bytecode.
● Bytecode can be interpreted on any platform by JVM (Java Virtual Machine).
High performance :
● Bytecodes are highly optimized.
● JVM can execute bytecodes much faster .
Distributed :
● Java is designed with the distributed environment.
● Java can be transmitted over internet.
Dynamic :
● Java programs carry substantial amounts of run-time type information with them that is
used to verify and resolve accesses to objects at run time.
C C++ Java
Platform dependent Platform dependent Platform independent
It needs to be compiled It needs to be compiled It needs to be compiled and
interpreted
No multithreading No multithreading multithreading
Pointers No pointers No pointers
No templates Templates Templates
Database handling is complex. Database handling is complex. Database handling is easy.
● javac
o It converts source file into byte code
● java
o It converts byte code into machine code
● jdb (java debugger)
o Find errors in program.
● javap (java disassembler)
o Converts byte code into program description
● javah
o create the header files
● javadoc
o creates HTML documents from source file.
● appletviewer
o execute java applets.
The classes in this package are used for design of Java programming language.
3. Networking Package
Package: java.net
The classes in this package are used for networking purposes.
4. Utility package
Package: java.util
The classes in this package are used for date and time facilities, internationalization, and a random-
number generator
5. Text classes
Package: java.text
The classes in this package are used for handling text.
Java Runtime Environment (JRE)
JRE is part of the Java Development Kit (JDK), but can be downloaded separately. JRE was
originally developed by Sun Microsystems Inc., a wholly-owned subsidiary of Oracle
Corporation.
JRE consists of the following components:
Name of the component Elements of the component
Deployment technologies Deployment
Java Web Start
Java Plug-in
User interface toolkits Abstract Window Toolkit (AWT)
Swing
Input methods.
Integration libraries Interface Definition Language (IDL)
Java Database Connectivity (JDBC)
Remote Method Invocation (RMI)
Scripting.
base libraries Input/Output (I/O)
Beans
Math
Networking
Security
Lang and util base libraries lang and util
Versioning
Zip
Logging
Java Virtual Machine (JVM) Java HotSpot Client
Server Virtual Machines
Java Virtual Machine (JVM)
The JVM is an interpreter for the bytecode form of the program. It steps through one bytecode
instruction at a time. It is an abstract computing machine that enables a computer to run
a Java program. The JVM is a program that provides the runtime environment necessary for Java
programs to execute. Java programs cannot run without JVM .
1.4 JAVA SOURCE FILE STRUCTURE / STRUCTURE OF JAVA PROGRAM
Java source file is a text file that contains one or more class definitions. Java source file must be
saved with an extension of “.java”.
To create Java source file, we need any of the following:
● Notepad − Text editor
● Netbeans − A Java IDE that is open-source and free
● Eclipse − A Java IDE developed by the eclipse open-source community
Rules:
o The package statement should be the first line in the source file. .
o If a package statement is not used, the class, interfaces, enumerations, and annotation types
will be placed in the current default package.
Keyword: package
DEPARTMENT OF CSE Page 12
Object Oriented Programming 2019
Syntax
Package packagename;
Example:
package animals;
class Animal
{
public void eat();
public void travel();
}
iii) Import Statement:
The import statement makes external classes available to the current Java source program at the
time of compilation.
Keyword: import
Syntax
● To import a single class, we specify the name of the class
import packagename;
● To import all classes, we specify *.
import packagename.* ;
Examples
import mypackage.MyClass;
import mypackage.reports.accounts.salary.EmpClass;
import java.awt.*;
iv) Interface statemant
Interface is like a class but it includes group of method definitions. Interfaces are like a class that
includes a group of method declarations. It's an optional section.
Keyword: interface
Syntax
Interface interfacename
Example:
interface Animal
{
public void eat();
public void travel();
}
v) class definitions
A Java program may contain one or more class definitions.
Keyword:
class
Syntax
class classname
{
//statements
}
Example:
class Animal
{
public void eat();
public void travel();
}
vi) main method class
Every java program requires the main method as the starting point of the program. This is an
essential part of a Java program. There may be many classes in a Java program, and only one
class defines the main method.
Example:
Class sample
{
Public static void main(String args[])
{
//statements
}
}
1.5 COMPILATION
Java source code is compiled into bytecode using javac compiler. The bytecodes are platform-
independent instructions for the Java VM. They are saved on the disk with the file extension .class.
Steps:
1. Java programs need to be compiled to bytecode.
2. When the bytecode is run, it needs to be converted to machine code.
Compiling the Program
javac sample.java
2. Character constant
i.Char constant
const char a =’X’;
ii.String constant
const string s=”hello”;
Expressions:
An expression is a sequence of operators and operands that specifies the computation
Simple Expression
An expression that has only one operator is known as simple expression.
Example:
X=a+b;
X=++a;
Compound Expression
An expression that has more than one operator is known as compound expression.
Example:
X=a+b*c/f;
Arithmetic Expression
An expression consisting of arithmetic operators is known as arithmetic expression.
Example:
X=a+b;
Logical Expression
An expression consisting of logical operators is known as Logical expression.
Example:
X=a>b;
1.7 DEFINIG CLASSES IN JAVA
A class can be defined as a template/blueprint that describes the behavior/state of objects. Class
is a set of objects that share the common structure and behavior. The class is at the core of Java .
Syntax of class:
class classname
{
datatype instance-variable1;
datatype instance-variable2;
...
datatype instance-variableN;
datatype methodname1(parameter-list)
{
// body of method
}
...
datatype methodnameN(parameter-list)
{
// body of method
}
}
● The data, or variables, defined within a class are called instance variables.
Object
An object is an instance of a class. Objects have states and behaviors.
Example: Dog
states: color, name, breed
behaviors : wagging the tail, barking, eating.
Syntax
i) Object declarartion
Classname objectname;
ii) Object instantiation
Objectname = new classname( );
Example:
Rectangle rect ;
Rect= new Rectangle( );
(OR)
Rectangle rect = new Rectangle( );
● rect will be an instance of Rectangle.
Accessing variables in class:
To access these variables, we will use the dot (.) operator.
Syntax
objectname. variable;
objectname. methodname( );
Example:
rect.length =10;
rect.getdata( );
Program:
//Rectarea.java
class Rectangle
{
double length;
double width;
double area;
Rectangle (double x, double y)
{
length = x;
width = y;
}
double calculate( )
{
area = length * width;
return area;
}
}
class Rectarea
{
public static void main(String args[])
{
Rectangle rect1 = new Rectangle( 25,10);
double area1;
area1= rect.calculate();
System.out.println(“ AREA OF RECTANGLE = “ + area1);
}
}
Output:
javac Rectarea.java
java Rectarea
AREA OF RECTANGLE = 250
Predefined Class
Predefined class are already defined. Users cannot change the definition of predefined class. Some
of the predefined classes are,
● String
● StringBuffer
● Math
● Vector
● Hashtable
● Date
1.8 CONSTRUCTORS
Constructors are used for initializing new objects immediately when it is created .Every class has
a constructor. If the constructor is not defined in the class, the Java compiler builds a default
constructor for that class.
Types of Constructors
double area1;
area1= rect1.calculate();
System.out.println(“ AREA OF RECTANGLE = “ + area1);
Rectangle rect2 = new Rectangle( 25,10);
double area2;
area2= rect2.calculate();
System.out.println(“ AREA OF RECTANGLE = “ + area2);
}
}
Output:
javac Rectarea.java
java Rectarea
DEFAULT CONSTRUTOR
AREA OF RECTANGLE = 0
PARAMETERIZED CONSTRUTOR
AREA OF RECTANGLE = 250
Constructors vs methods
Constructors Methods
Construcor name must be same as the class It is not necessary for the method in java.
name.
Constructors do not have any return type methods have the return type
Constructor is called only once at the time of Methods can be called any numbers of time.
Object creation
1.9 METHODS IN JAVA
A method is a collection of statement that performs specific task. In Java, method define the
behavior of that class.
Advantages of methods
● Program development and debugging are easier
● Increases code sharing and code reusability
● Increases program readability
● It makes program modular and easy to understanding
● It shortens the program length by reducing code redundancy
Types of methods
There are two types of methods in Java programming:
● Standard library methods (built-in methods or predefined methods)
● User defined methods
Standard library methods
The standard library methods are built-in methods in Java programming to handle tasks such as
mathematical computations, I/O processing, graphics, string handling etc. These methods are
already defined.
Packages Library Descriptions
Methods
java.lang.Math acos() Computes cosine of the argument
exp() Computes the exponent value
abs() Computes absolute value of argument
Method Call
A method gets executed only when it is called.
The syntax for method call is.
Syntax:
methodname(parameters);
The number and type of parameters passed in method call should match exactly with the parameter
list mentioned in method prototype.
Classification of method based on arguments and return values
● Method with no arguments and no return value
● Method with no arguments and a return value
● Method with arguments and no return value
● Method with arguments and a return value.
i) Method with no arguments and no return value
In this type of method, no value is passed in between calling method and called method.
Program:
//Sample.java
class sample
{
void add( )
{
int a=10,b=20;
System.out.println("Sum:"+(a+b));
}
public static void main(String[] args)
{
sample s = new sample( );
s.add(); // method call with no arguments
}
}
Output:
javac sample.java
java sample
Sum : 30
ii) Method with no arguments and a return value
In this type of method, no value is passed from calling method to called method but a value is
returned from called method to calling method.
Program:
//Sample.java
class sample
{
int add( )
{
int a=10,b=20;
return(a+b);
}
public static void main(String[] args)
{
int sum;
sample s=new sample( );
sum=s .add();
System.out.println("Sum:"+sum);
}
}
Output:
javac sample.java
java sample
Sum : 30
iii) Method with arguments and no return value
In this type of method, parameters are passed from calling method to called method but no value
is returned from called method to calling method.
Program:
//Sample.java
class sample
{
void add(int x,int y)
{
System.out.println("Sum:"+(x+y));
}
public static void main(String[] args)
{
int a=10,b=20;
sample s = new sample( );
s.add(a,b); // method call with arguments
}
}
Output:
javac sample.java
java sample
Sum : 30
iv) Method with arguments and a return value.
In this type of method, there is data transfer in between calling method and called method. Here,
when the method is called program control transfers to the called method with arguments, executes
the method, and return the value back to the calling method.
Program:
//Sample.java
class sample
{
int add(int x,int y)
{
return(x+y);
}
public static void main(String[] args)
{
int a=10,b=20;
sample s = new sample( );
System.out.println("Sum:"+obj.add(a,b));
}
}
Output:
javac sample.java
java sample
Sum : 30
Parameter passing in Java
The commonly available parameter passing methods are:
● Pass by value / call by value
● Pass by reference / call by reference
i) Pass by Value
● Values of actual arguments are passed to formal parameter.
● Changes made in formal parametrs does not affect the actual argument.
Program:
//Sample.java
class sample
{
void add(int x,int y)
{
System.out.println("Sum:"+(x+y));
}
public static void main(String[] args)
{
int a=10,b=20;
sample s = new sample( );
s.add(a,b); // method call with arguments
}
}
Output:
javac sample.java
java sample
Sum : 30
ii) Pass by Reference
● Reference (address) of the actual parameters is passed to the local parameters in the method
definition.
● Changes made in formal parametrs affect the actual argument.
Program:
//Sample.java
void swap(sample ref) // method to interchange values
{ /* Object is passed by reference. So the original object value
int temp;
a, b gets changed*/
temp = ref.a;
ref.a = ref.b;
ref.b = temp;
}
Method Overloading
Method overloading is the process of having multiple methods with same name that differs in
parameter list. The number and the data type of parameters must differ in overloaded methods. It
is one of the ways to implement polymorphism in Java. When a method is called, the overloaded
method whose parameters match with the arguments in the call gets invoked.
Program for addition using Method Overloading
//sample.java
class MethodOverload
{
void add()
{
System.out.println("No parameters");
}
void add(int a,int b)
{
System.out.println("Sum:"+(a+b));
}
void add(int a,int b,int c)
{
System.out.println("Sum:"+(a+b+c));
}
}
class sample
{
public static void main(String[] args)
{
MethodOverload m=new MethodOverload();
m.add();
m.add(1,2);
m.add(1,2,3);
}
}
Output:
javac sample.java
java sample
No parameters
Sum:3
Sum:6
Sum:35.7
finalize() method
The finalize() method is called the finalizer. finalize() is the method of Object class. The main
purpose of a finalizer is, however, to release resources used by objects before they’re removed
from the memory. finalize() method overrides to dispose system resources, perform clean-up
activities and minimize memory leaks.
Syntax
protected void finalize() throws Throwable
{
…………….
}
Program:
//sample.java
import java.util.*;
class sample
{
public static void main(String[] args)
{
sample s = new sample();
System.out.println("" + s.getTime());
System.out.println("Finalizing...");
s.finalize();
System.out.println("Finalized.");
}
}
Output:
javac sample.java
java sample
The public access specifier has highest level of accessibility. Methods, class, and fields declared
as public are accessible by any class in the same package or in other package.
Program:
//sample.java
class Example
{
public int x=10;
}
class sample
{
public static void main(String[] args)
{
Example e = new Example ( );
System.out.println(e.x);
}
}
Output:
javac sample.java
java sample
10
Private access modifier provides low level of accessibility. Private data fields and methods are
accessible only inside the class where it is declared. Encapsulation and data hiding can be achieved
using private specifier.
Program:
//sample.java
class Example
DEPARTMENT OF CSE Page 29
Object Oriented Programming 2019
{
private int x;
public int y;
}
class sample
{
public static void main(String[] args)
{
Example e = new Example ( );
System.out.println(e.x);
System.out.println(e.y);
}
}
Output:
javac sample.java
java sample
10
Error: cannot access y
If the specifier is not mentioned, then it is treated as default. There is no default specifier keyword.
Using default specifier we can access class, method, or field from the same package, but not from
outside this package.
Program:
//sample.java
class Example
{
int x=10;
}
class sample
{
public static void main(String[] args)
{
Example e = new Example ( );
System.out.println(e.x);
}
}
Output:
javac sample.java
java sample
10
Protected methods and fields are accessible within same class, subclass inside same package.
Program:
//sample.java
class A
{
protected int x=10;
}
class B extends A
{
protected int y=20;
}
class sample
{
public static void main(String[] args)
{
B b = new B ( );
System.out.println(b.x);
System.out.println(b.y);
}
}
Output:
javac sample.java
java sample
10
20
1.11 STATIC MEMBERS
Static Members can be static variable or static method or static block or static class or static import.
Static Members can be used accessed without using any object. The static keyword can be used
with:
● Variable (static variable or class variable)
● Method (static method or class method)
● Block (static block)
● Nested class (static class)
● import (static import)
i) Static variable
Variable declared with keyword static is a static variable. It is a class level variable commonly
shared by all objects of the class.
● Automatically initialized to 0.
● Static variables can be accessed directly in static and non-static methods.
Syntax:
● Declaration : static datatype variable
● Accessing : classname.staticvariable
Program:
//sample.java
class Example
{
static int a=10;
}
class sample
{
public static void main(String[] args)
{
System.out.println(Example.a);
}
}
Output:
javac sample.java
java sample
10
A static block is a block of code enclosed in braces, preceded by the keyword static. The
statements within the static block are first executed automatically before main when the class is
loaded into JVM. A class can have any number of static blocks.
Syntax: static
{
…………….
}
Example:
class sample
{
static
{
System.out.println("First static block");
}
public static void main(String[] args)
{
sample obj=new sample ();
}
}
Output:
javac sample.java
java sample
First static block
iv) static class
Nested class is a class declared inside another class. The inner class must be a static class declared
using keyword static.
Syntax:
class OuterClass
{
……..
static class InnerClass
{
……….
}
}
Example:
class Outer
{
static class Inner
{
void show( )
{
System.out.println(“welcome”);
}
}
}
class sample( )
{
public static void main(String args[])
{
Outer.Inner obj=new Outer.Inner();
obj.show();
}
}
Output:
javac sample.java
java sample
welcome
v) Static Import
The static import allows the programmer to access any static members of imported class directly.
Syntax:
import static package_name;
Advantage:
● Less coding is required if you have access any static member of a class oftenly.
Disadvantage:
● Overuse of static import makes program unreadable and unmaintable.
Example:
import static java.lang.System.*;
class sample
{
public static void main(String args[])
{
out.println("Static Import Example");
}
}
Output:
javac sample.java
java sample
Static Import Example
1.12 COMMENTS
The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method, class or
any statement.
There are 3 types of comments in java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment / Javadoc comment
1.12.1 SINGLE LINE COMMENT
The single line comment is used to comment only one line.
Syntax:
//This is single line comment
Program:
class sample //Here, sample is a classname
{
public static void main(String[] args)
{
int i=10; //Here, i is a variable
System.out.println(i);
}
}
Output:
javac sample.java
java sample
10
1.12.2 MULTI LINE COMMENT
The multi line comment is used to comment multiple lines of code.
Syntax:
/*
This
is
multi line
comment
*/
Program:
class sample
{
public static void main(String[] args)
{
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}
Output:
javac sample.java
java sample
10
1.12.3 DOCUMENTATION COMMENT / JAVADOC COMMENT
Javadoc is a JDK tool that generates API documentation from documentation comments. It is used
for generating Java code documentation in HTML format from Java source code.
Structure of Javadoc Comments
Javadoc comments are any multi-line comments ("/** ... */") that are placed before class, field, or
method declarations. They must begin with a slash and two stars, end with with one star and slash.
Syntax:
/**
* This is documentation comment
*/
Types:
1. Classlevel comments
o provides decription and purpose of a class.
2. datamemberlevel comments
o provides decription and purpose of a datamember.
3. methodlevel comments
o provides decription and purpose of a method.
4. Constructorlevel comments
o provides decription and purpose of a constructor
Example:
/**
*sample class provides methods to get addition and subtraction of given 2 numbers.
* @author kavitha
*/
class sample
{
/**
* The add() method returns addition of given numbers
* @param a,b
*/
static int add(int a, int b)
{
return a+b;
}
/**
* The sub() method returns subtraction of given numbers.
* @param a,b
*/
public static int sub(int a, int b)
{
return a-b;
}
}
Compile it by javac tool:
javac sample.java
Create Documentation API by javadoc tool:
javadoc sample.java
commonly used Javadoc tags .
1.13 DATATYPES
Data types represent the category of values used in program.. In java, there are two categories of
data types:
o Primitive data types
o Non-primitive data types
Example:
Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. It is an 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.
Example:
byte a = 10;
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between (-216) to (216-
1).The char data type is used to store characters.
Example: char x = 'A';
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between
(-216) to (216- 1). Its default value is 0.
Example:
short s = 10000;
Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between (-231)
to (231 -1). Its default value is 0.
Example:
int a = 100000;
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between (-263) to (263-
1). Its default value is 0.
Example:
long a = 100000L;
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited.
It is recommended to use a float (instead of double) if you need to save memory in large arrays of
floating point numbers. Its default value is 0.0F.
Array:
Array is a collection of elements of similar data type stored in contiguous memory location. It is
index based and the first element is stored at 0th index.
20
1.14 VARIABLES
A variable is a name which holds the value while the java program is executed. A variable is
assigned with a datatype. Variable is a name of memory location.
Synatx:
datatype variablename= value;
Example:
int a=10;
There are three types of variables in java:
1. Local variable
2. Instance variable
3. Static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. We can use this variable
only within that method. A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called instance variable.
It is not declared as static. It is called instance variable because its value is instance specific and
is not shared among instances.
3) Static variable
A variable which is declared as static is called static variable. It cannot be local. We can create a
single copy of static variable and share among all the instances of the class. Memory allocation for
static variable happens only once when the class is loaded in the memory.
Program:
class Sample
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Output:
javac sample.java
java sample
20
1.15 OPERATORS
Operator is a symbol that is used to perform operations. Java provides a rich set of operators to
manipulate variables. For example: +, -, *, / etc.
There are many types of operators. They are,
1. Arithmetic Operators :
* / %
+ -
2. Relational Operators
Comparison : < > <= >= instanceof
Equality : == !=
3. Bitwise Operators
bitwise AND : &
bitwise exclusive OR : ^
bitwise inclusive OR : |
4. Logical Operators
logical AND : &&
logical OR : ||
logical NOT : ~ !
5. Assignment Operators: =
6. Ternary operator: ? :
7. instance of operator
8. Unary operator
Postfix : expr++ expr—
Prefix : ++expr --expr +expr -expr
i) Arithmetic Operators
Operator Description Example
+ (Addition) Adds values on either side of the operator. A + B will give 30
Subtracts right-hand operand from left-hand
- (Subtraction) A - B will give -10
operand.
Multiplies values on either side of the
* (Multiplication) A * B will give 200
operator.
Divides left-hand operand by right-hand
/ (Division) B / A will give 2
operand.
Divides left-hand operand by right-hand
% (Modulus) B % A will give 0
operand and returns remainder.
Program
class sample
{
public static void main(String args[])
{
int a = 10;
int b = 20;
System.out.println("add: " + (a + b) );
System.out.println("sub : " + (a - b) );
System.out.println("Mul: " + (a * b) );
System.out.println("Div: " + (b / a) );
System.out.println("modulo = " + (b % a) );
}
}
Output:
javac sample.java
java sample
add: 30
sub: -10
Mul: 200
Div: 2
modulo: 0
ii) Relational Operators
Operator Description Example
Checks if the values of two operands are equal or
== (equal to) (A == B) is not true.
not, if yes then condition becomes true.
Checks if the values of two operands are equal or
!= (not equal to) not, if values are not equal then condition becomes (A != B) is true.
true.
Checks if the value of left operand is greater than the
> (greater than) value of right operand, if yes then condition becomes (A > B) is not true.
true.
Checks if the value of left operand is less than the
< (less than) value of right operand, if yes then condition becomes (A < B) is true.
true.
Checks if the value of left operand is greater than or
>= (greater than
equal to the value of right operand, if yes then (A >= B) is not true.
or equal to)
condition becomes true.
Checks if the value of left operand is less than or
<= (less than or
equal to the value of right operand, if yes then (A <= B) is true.
equal to)
condition becomes true.
Program
Class Test
{
public static void main(String args[])
{
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
}
}
Output:
javac sample.java
java sample
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = fals
iii) The Bitwise Operators
Operator Description Example
Binary AND Operator copies a bit to the (A & B) will give 12 which is
& (bitwise and)
result if it exists in both operands. 0000 1100
Binary OR Operator copies a bit if it exists (A | B) will give 61 which is
| (bitwise or)
in either operand. 0011 1101
Binary XOR Operator copies the bit if it is (A ^ B) will give 49 which is
^ (bitwise XOR)
set in one operand but not both. 0011 0001
(~A ) will give -61 which is
Binary Ones Complement Operator is 1100 0011 in 2's complement
~ (bitwise compliment)
unary and has the effect of 'flipping' bits. form due to a signed binary
number.
Binary Left Shift Operator. The left
A << 2 will give 240 which is
<< (left shift) operands value is moved left by the number
1111 0000
of bits specified by the right operand.
Binary Right Shift Operator. The left
operands value is moved right by the A >> 2 will give 15 which is
>> (right shift)
number of bits specified by the right 1111
operand.
Shift right zero fill operator. The left
operands value is moved right by the
A >>>2 will give 15 which is
>>> (zero fill right shift) number of bits specified by the right
0000 1111
operand and shifted values are filled up with
zeros.
iv) Logical Operators
Operator Description Example
Called Logical AND operator. If both the operands
&& (logical and) (A && B) is false
are non-zero, then the condition becomes true.
Called Logical OR Operator. If any of the two
|| (logical or) operands are non-zero, then the condition becomes (A || B) is true
true.
Called Logical NOT Operator. Use to reverses the
! (logical not) logical state of its operand. If a condition is true then !(A && B) is true
Logical NOT operator will make false.
Program:
class sample
{
public static void main(String args[])
{
boolean a = true;
boolean b = false;
System.out.println("a && b = " + (a&&b));
System.out.println("a || b = " + (a||b) );
System.out.println("!(a && b) = " + !(a && b));
}
}
Output:
javac sample.java
java sample
a && b = false
a || b = true
!(a && b) = true
v) Assignment Operators
Operator Description Example
Simple assignment operator. Assigns values from C = A + B will assign value of A +
=
right side operands to left side operand. B into C
Add AND assignment operator. It adds right
+= operand to the left operand and assign the result to C += A is equivalent to C = C + A
left operand.
Subtract AND assignment operator. It subtracts
-= right operand from the left operand and assign the C -= A is equivalent to C = C – A
result to left operand.
Multiply AND assignment operator. It multiplies
*= right operand with the left operand and assign the C *= A is equivalent to C = C * A
result to left operand.
Divide AND assignment operator. It divides left
/= operand with the right operand and assign the result C /= A is equivalent to C = C / A
to left operand.
Modulus AND assignment operator. It takes
%= modulus using two operands and assign the result C %= A is equivalent to C = C % A
to left operand.
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
vi) Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands
and is used to evaluate Boolean expressions.
Syntax:
Condition ? exp1 : exp2;
● If condition is true, exp1 is executed
● If condition2 is false, exp2 is executed
Program:
class sample
{
public static void main(String args[])
{
int a=10;
int b=20;
int c;
c= a> b? a: b;
System.out.println( “greatest number :” + c);
}
}
Output:
javac sample.java
java sample
greatest number : 20
vii) instanceof Operator
This operator is used only for object reference variables. The operator checks whether the object
is of a particular type (class type or interface type.
Program:
class sample
{
public static void main(String args[])
{
String name ="James";
boolean result = name instanceof String;
System.out.println( result );
}
}
Output:
javac sample.java
java sample
true
Precedence of Java Operator
Larger number means higher precedence.
Lower number means less precedence.
Precedence Operator Type Associativity
() Parentheses
15 [] Array subscript Left to Right
· Member selection
++ Unary post-increment
14 Right to left
-- Unary post-decrement
++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
13 Right to left
- Unary minus
! Unary logical negation
~ Unary bitwise complement
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension
< Relational less than
<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
Program:
// Precedence.java
class Precedence
{
public static void main(String[] args)
{
int a = 4, b = 2, c = 5, result;
result = a+b*c/2;
System.out.println(result);
}
}
Output:
javac Precedence.java
java Precedence
9
1.16 CONTROL FLOW
Java Control statements control the flow of execution in a java program, based on data values and
conditional logic used. There are three main categories of control flow statements;
● Selection statements: if, if-else and switch.
● Loop statements: while, do-while and for.
● Transfer statements: break, continue, return
Syntax:
if (condition)
{
………..
}
else
{
…………
}
Program1 : largest among two numbers
class sample
{
public static void main(String[] args)
{
int a = 10, b = 20;
if (a > b)
System.out.println("%d is largest",a);
else
System.out.println("%d is largest",b);
}
}
Output:
javac sample.java
java sample
20 is largest
Program2 : odd or even number
class sample
{
public static void main(String[] args)
{
int a = 10;
if(a%2==0)
System.out.println("even number");
else
System.out.println("odd number");
}
}
Output:
javac sample.java
java sample
even number
iii) if-else-else if
It is a multiway selection statement. If the condition1 is true, the statements in the if block are
executed. If the condition1 is false and condition2 is true, the statements in the else if block are
executed. Otherwise, else block is exceuted.
Syntax:
if (condition1)
{
………..
}
else if (condition2)
{
…………
}
else
{
………
}
Program : largest among three numbers
class sample
{
public static void main(String[] args)
{
int a = 10, b = 20,c=30;
if (a > b && a>c)
System.out.println("%d is largest",a);
else if(b>c)
System.out.println("%d is largest",b);
else
System.out.println("%d is largest",c);
}
}
Output:
javac sample.java
java sample
30 is largest
iv) nested if
The nested if statement represents the if block within another if block. Here, the inner if block
condition executes only when outer if block condition is true.
Syntax:
if(condition)
{
if(condition)
{
………..
}
}
class sample
{
public static void main(String[] args)
{
int age=20;
int weight=80;
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
}
}
}
Output:
javac sample.java
java sample
You are eligible to donate blood
i) while Statement
The while statement is repetitive control structure that executes a block of code while a condition
is true.
Syntax
while (condition)
{
// code block to be executed
}
Program: Printing Numbers from 1 to 5
class sample
{
public static void main(String[] args)
{
int i = 1;
while (i <= 5)
{
System.out.println(i);
i++;
}
}
}
Output:
javac sample.java
java sample
1
2
3
4
5
ii) do-while Loop Statement
The do/while loop is a variant of the while loop. The do—while loop executes atleast once without
checking the condition. It begins with the keyword do, followed by the statements of the loop.
Syntax
do
{
………. // code block to be executed
}while (condition);
Program: Printing Numbers from 1 to 5
class sample
{
public static void main(String[] args)
{
int i = 1;
do
{
System.out.println(i);
i++;
} while(i<=5);
}
}
Output:
javac sample.java
java sample
1
2
3
4
5
iii) for Loop
The while statement is repetitive control structure that executes a block of code for a specified
number of times. It’s a counter controlled loop.
Syntax
for (initalization; condition; increment/decrement)
{
// code block to be executed
}
Program: Printing Numbers from 1 to 5
class sample
{
public static void main(String[] args)
{
for (int i = 1; i < =5; i++)
{
System.out.println(i);
}
}
}
Output:
javac sample.java
java sample
1
2
3
4
5
Transfer statements are used to transfer the flow of execution from one statement to another.
i) Continue Statement
A continue statement stops the current iteration of a loop (while, do or for) continue with next
iteration.
Syntax:
continue;
Program: Printing Numbers from 1 to 5 except 3
class sample
{
public static void main(String[] args)
{
for (int i = 1; i < =5; i++)
{
if( i==3)
continue;
System.out.println(i);
}
}
}
Output:
javac sample.java
java sample
1
2
4
5
The break statement terminates the loop (for, while, do or switch statement). Break statement can
be used when we want to jump immediately to the statement following the enclosing control
structure.
Syntax:
break;
Program:
class sample
{
public static void main(String[] args)
{
for (int i = 1; i < =5; i++)
{
if( i==3)
break;
System.out.println(i);
}
}
}
Output:
javac sample.java
java sample
1
2
1.17 ARRAYS
Array is a collection of elements of similar data type stored in contiguous memory location. It is
index based and the first element is stored at 0th index.
Advantages of Array
● Code Optimization: Multiple values can be stored under common name. Date retrieval or
sorting is an easy process.
● Random access: Data at any location can be retrieved randomly using the index.
Disadvantages of Array
● Inefficient memory usage: Array is static. It is not resizable at runtime based on number of
user’s input. To overcome this limitation, Java introduce collection concept.
Types of Array
There are two types of array.
● One Dimensional Array
● Multidimensional Array
1.17.1 ONE DIMENSIONAL ARRAY
Array with only one subscript is known as one dimensional array.
Syntax for declaration:
datatype[] arrayName;
Or
datatype arrayName [];
Example:
int[] a;
Instantiation of an Array
Array can be created using the new keyword. To allocate memory for array elements, we must
mention the array size.
Syntax:
arrayname=new datatype[size];
Or
datatype[] arrayname=new datatype[size]; //declaration and instantiation
Example:
int[] a=new int[5];
Initialize array
Syntax:
datatype[] arrayname=new datatype[]{list of values separated by comma};
Or
datatype[] arrayname={ list of values separated by comma};
Example:
int[] a={12,13,14};
int[] a=new int[]{12,13,14};
Accessing array elements
The array elements can be accessed by using indices. The index starts from 0 and ends at (array
size-1). Each element in an array can be accessed using for loop.
Program: Storing and sorting the values of array
class arraysort
{
public static void main(String args[])
{
int a[5]={20,30,10,40};
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
a.sort( );
System.out.prinln(“sorted array”);
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
Output:
javac sample.java
java sample
20
30
10
40
sorted array
10
20
30
40
1.17.2 TWO DIMENSIONAL ARRAY
Array with two subscript is known as one dimensional array.
Syntax for declaration:
datatype[ ][ ] arrayName;
Or
Datatype arrayName[ ] [];
Example:
int[ ][ ] a;
(OR)
int a[ ][ ];
Instantiation of an Array
Array can be created using the new keyword. To allocate memory for array elements, we must
mention the array size.
Syntax:
arrayname=new datatype[rowsize][columnsize];
Or
datatype[ ][ ] arrayname=new datatype [rowsize][columnsize];
Example:
int[ ][ ] a=new int[5][5];
Initialize array
Syntax:
datatype[][ ] arrayname=new datatype[ ][ ]{list of values separated by comma};
Or
datatype[ ][ ] arrayname={ list of values separated by comma};
Example:
int[ ][ ] a={12,13,14};
int[ ][ ] a=new int[ ][ ]{12,13,14};
Accessing array elements
The array elements can be accessed by using indices. The index starts from 0 and ends at (array
size-1). Each element in an array can be accessed using for loop.
}
}
Output:
javac MatrixAddition.java
java MatrixAddition
2 6 8
4 8 6
4 6 9
● Prevent naming conflicts - It is generally used to avoid naming conflicts. For example,
there can be two classes with same name in different packages, company.branch1.Employee and
company.branch2.Employee
● Make searching/locating and usage of classes, interfaces, enumerations and annotations
easier, etc.
● Provide access protection based on the access specifier used.
Types of Packages
Based on whether the package is defined by the user or not, packages are divided in two
categories:
● Built-in packages / Predefined packages
● User-defined packages / Java API packages
1.18.1 BUILT-IN PACKAGES
Java has various in-built packages which are already defined. These packages consist of a large
number of classes which are a part of Java API. Some of the commonly used built-in packages
are:
Built-in Definition Some Classes & Interfaces available
Package inside package
java.lang Basic package which is PrintWriter, String, StringBuilder,
automatically imported in all StringBuffer, All Wrapper Classes,
programs. Thread, Runnable, Throwable ,
Exception etc
java.io It contains classes related to Scanner, File , FileReader , FileWriter,
input/output operations BufferedReader,InputStreamReader,
IOException, FileNotFoundException
java.util It contains utility classes which Date , Calender, Stack , Queue ,
implement data structures like Vector , ArrayList, Set, HashMap
Linked List, Dictionary and
support for Date / Time
operations
java.applet Contains classes for creating Applet, AppletContext, AppletStub
Applets
java.awt Contain classes for Button, Label, TextArea, Menu,
implementing the components MenuItem
for graphical user interfaces
java.net Contain classes for supporting HttpCookie, ServerSocket, Socket,
networking operations URLConnection
java.sql classes used for JDBC Connection, DriverManager,
programming ResultSet, SQLException
1.17.2 USER-DEFINED PACKAGES
These are the packages that are defined by the user. The package keyword is used to create a
package in java. The general form of the package statement is:
Syntax:
package pkgname;
Here, pkgname is the name of the package.
Example:
package MyPack;
// Subtraction.java
package MyPack;
public class Subtraction
{
public void sub(int a,int b)
{
System.out.println(“Difference:”+(a-b));
}
}
//Package Usage
//sample.java
import MyPack.*;
public class sample
{
public static void main(String args[])
{
Addition a=new Addition();
a.add(10,20);
Subtraction s=new Subtraction();
s.sub(10,20);
}
}
Output:
javac sample.java
java sample
Sum:30
Difference:10
3. Define Polymorphism.
Polymorphism is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs.
● The word "poly" means many
● "morphs" means forms.
● So polymorphism means many forms.
It refers to the act of representing essential features without including the background details or
explanations. It is one of the key concepts of object-oriented programming (OOP) languages. Its
main goal is to handle complexity by hiding unnecessary details from the user.
5. Define Encapsulation
Encapsulation is the process of combining data and functions into a single unit. In Java, the basis
of encapsulation is the class. Encapsulation achieves the concept of data hiding.
Data hiding: Data inside the class is accessible only through the function within the class
▪ Relational Operators
▪ Logical Operators
▪ Assignment Operators
5. Instance variable
6. Static variable
Synatx:
datatype variablename= value;
Example:
int a=10;
class Rectangle
{
Rectangle ( )
{
…..
}
}
23. What are the differences between static variable and instance variable?
Static Variables Instance Variables
1.Memory for static variable is allocated only 1. Memory for instance variable is allocated
once when class is loaded each time when an object is created
2. The memory is commonly shared by all 2. Each object memory is independent
objects of the class
3.Static variables are accessible without objects 3. Instance variables are accessible only using
objects
4. They are automatically initialized to default 4. Not initialized automatically
values
5. Example: static int no; 5. Example: int no=10;
ADDITIONAL PROGRAMS
1. Sum of two numbers
//sample.java
import java.io.*;
import java.util.Scanner;
public class sample
{
public static void main(String[] args)
{
int num1, num2, sum;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Enter Second Number: ");
num2 = sc.nextInt();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}
Output:
javac sample.java
java sample
Enter First Number:
121
Enter Second Number:
19
Sum of these numbers: 140
2. check Even or Odd number
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String args[])
{
int num;
System.out.println("Enter number:");
Scanner sc= new Scanner(System.in);
num = sc.nextInt();
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}
Output:
javac sample.java
java sample
Enter number:
78
Entered number is even
3. Calculate Area Of Circle
//area.java
import java.io.*;
import java.util.Scanner;
class area
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the radius:");
double r= sc.nextDouble();
double area=(22*r*r)/7 ;
System.out.println("Area of Circle is: " + area);
}
}
Output:
javac area.java
java area
Enter the radius :7
Area of circle : 154.0
4. alphabet is vowel or consonant
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
System.out.println("Enter the character:");
char ch=sc.next( );
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' )
System.out.println(ch + " is vowel");
else
System.out.println(ch + " is consonant");
}
}
Output:
javac sample.java
java sample
Enter the character: i
i is vowel
5. Reverse of a string
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String[ ] arg)
{
String str;
char ch;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a string : ");
str=sc.nextLine();
System.out.println("Reverse of a tring:");
for(int j=str.length();j>0;--j)
{
System.out.print(str.charAt(j-1));
}
}
}
Output:
javac sample.java
java sample
Enter a string : java
Reverse of a String: avaj
7. Reverse A Number
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String[] arg)
{
int a,res=0,n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
n=sc.nextInt();
while(n!=0)
{
a=n%10;
res=(res*10)+a;
n=n/10;
}
System.out.println("reverse of a number is "+res);
}
}
Output:
javac sample.java
java sample
Enter a number : 123
Reverse of a String: 321
8. Calculate Factorial
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
n=sc.nextInt();
fact=1;
for(int i=1;i<=n;i++)
{
fact=fact*i;
}
System.out.println("factoral="+fact);
}
}
Output:
javac sample.java
java sample
Enter a number : 5
factorial =120
9. fibnacci series
//sample.java
import java.io.*;
import java.util.Scanner;
class sample
{
public static void main(String args[])
{
int n1=0,n2=1;
int n3,i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
count=sc.nextInt();
System.out.print(n1+" "+n2);//printing 0 and 1
for(i=2;i<count;++i)
{
n3=n1+n2;
System.out.print(" "+n3);
n1=n2;
n2=n3;
}
}
}
Output:
javac sample.java
java sample
0 1 1 2 3 5 8 13 21 34
10. Check Prime Number using a for loop
import java.io.*;
import java.util.Scanner;
public class sample
{
public static void main(String[] args)
{
int num;
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
num=sc.nextInt();
boolean flag = false;
for(int i = 2; i <= num/2; ++i)
{
if(num % i == 0)
{
flag = true;
break;
}
}
if (flag=true)
System.out.println(num + " is a prime number.");
else
System.out.println(num + " is not a prime number.");
}
}
Output:
javac sample.java
java sample
Enter a number : 9
9 is not a prime number.
Example:
Types of inheritance
There are four types of inheritance. They are,
1. Single inheritance
2. Multi level inheritance
3. Hiearchical inheritance
4. Hybrid inheritance
i) Single Inheritance :
In single inheritance, there is one super class and one sub class(a subclass inherit the
features of one superclass)
Synatx:
Class superclass
{
…………
}
class Subclass extends Superclass
{
…………….
}
Employee
} id= 100
class Manager extends Employee
printman()
{
int id=100;
void printman( )
{
System.out.println("ID: “+id);
}
}
class single
{
public static void main(String[] args)
{
Manager m= new Manager( );
m.printemp( );
m.printman( );
}
}
Output:
javac single.java
java single
NAME : kavitha
ID : 100
ii) Multilevel Inheritance:
DEPARTMENT OF CSE Page 81
Object Oriented Programming 2019
In Multilevel Inheritance, there ia s a sub class with one super class but that super class is
derived from another super class (a subclass inherit the features of one superclass)
Here,
● ClassA is the super class.
● ClassB is the immediate super class.
● ClassC is the sub class.
Syntax:
class classA
{
…………
}
class classB extends classA
{
…………….
}
class classC extends classB
{
…………….
}
Example
Employee
} id= 100
class Manager extends Employee
printman( )
{
int id=100;
void printman( )
{
System.out.println("ID: “+id);
}
}
class Generalmanager extends Manager
{
int salary = 10000;
void printgen( )
{
System.out.println("SALARY :”+salary);
}
}
class multillevel
{
public static void main(String[] args)
{
Generalmanager g= new Generalmanager( );
g.printemp( );
g.printman( );
g.printgen( );
}
}
Output:
javac multillevel.java
java multillevel
NAME : kavitha
ID : 100
SALARY :10000
iii) Hierarchical Inheritance:
In Hierarchical Inheritance, there is one super class and more than one sub classes (a subclass
inherit the features of one superclass)
Here,
● ClassA is the super class.
● ClassB and classC are the sub class.
Syntax:
class classA
{
…………
}
class classB extends classA
{
…………….
}
class classC extends classA
{
…………….
}
Employee
name= “ kavitha”
Program:
//hierarchichal.java printemp( )
class Employee
{
String name=”kavitha”;
void printgen(
extends) extends
{
System.out.println("NAME:”+name);
Manager Programmer
}
id= 100 Language=”java”
}
class Manager extends
printman( ) Employee printgen( )
{
int id=100;
void printman( )
{
System.out.println("ID: “+id);
}
}
class Programmer extends Employee
{
String language=”java”;
void printpro( )
{
System.out.println("LANGUAGE: +language);
}
}
DEPARTMENT OF CSE Page 84
Object Oriented Programming 2019
class hierarchichal
{
public static void main(String[] args)
{
Manager m= new Manager( );
Programmer p =new Programmer( );
m.printemp( );
m.printman( );
p.printpro( );
}
}
Output:
javac hierarchichal.java
java hierarchichal
NAME : kavitha
ID : 100
LANGUAGE: java
Here,
● ClassA is the super class.
● ClassB and classC are the sub class of ClassA.
● ClassD is the subclass of classC
Syntax:
class classA
{
…………
}
class classB extends classA
{
…………….
}
class classC extends classA
{
…………….
}
class classD extends classC
{
…………….
}
Example:
Program: Employee
//hybrid.java
class Employee name= “ kavitha”
{
printemp( )
String name=”kavitha”;
void printgen( )
{
System.out.println("NAME:”+name);
extends extends
}
} Manager Programmer
class Manager extends Employee
{
id= 100 Language=”java”
int printman(
id=100; ) printgen( )
void printman( )
{
System.out.println("ID: “+id);
extends
}
} Generalmanager
class Programmer extends Employee
{ salary= 10000
String language=”java”;
printgen( )
void printpro( )
{
System.out.println("LANGUAGE: +language);
}
}
class Generalmanager extends Manager
{
int salary = 10000;
void printgen( )
{
System.out.println("SALARY :”+salary);
}
}
class hybrid
{
public static void main(String[] args)
{
Generalmanager g= new Generalmanager( );
Programmer p =new Programmer( );
g.printemp( );
g.printman( );
g.printgen( );
p.printpro( );
}
}
Output:
javac hybrid.java
java hybrid
NAME : kavitha
ID : 100
SALARY : 10000
LANGUAGE: java
2.2 PROTECTED MEMBERS
Protected methods and fields are accessible within same class, subclass inside same package. It is
mainly used in inheritance. Protected memebers can be,
● Protected data
● Protected method
● Protected class
Access Modifiers default private protected public
Accessible inside the class Yes Yes Yes Yes
Keyword:
protected
Program:
//Sample.java
class Employee
{
String name=”kavitha”;
protected void printgen( )
{
System.out.println("NAME:”+name);
}
}
class Manager extends Employee
{
int id=100;
void printman( )
{
System.out.println("ID: “+id);
}
}
class sample
{
public static void main(String[] args)
{
Manager m= new Manager( );
m.printemp( );
m.printman( );
}
}
Output:
javac sample.java
java sample
//ERROR: cannot acess
The constructors of the superclass are never inherited by the subclass. super() can be used to
invoke immediate parent class constructor.
Use of super keyword:
● Access superclass variables
● Access superclass method
● Access superclass constructor
Use of super with constructors:
The super keyword can also be used to invoke the parent class constructor.
Syntax:
super();
super(parameterlist);
● super() must always be the first statement inside a subclass constructor.
Constructor chaining:
When we invoke a super() statement within a subclass constructor, we are invoking the immediate
super class constructor
Prgram:
class A
{
A( )
{
System.out.println("In A class Constructor");
}
}
class B extends A
{
B( )
{
super();
System.out.println("In B class Constructor");
}
}
class C extends B
{
C( )
{
super();
System.out.println("In C class Constructor");
}
}
class sample
{
public static void main(String[] args)
{
C ca = new C( );
}
}
Output:
javac sample.java
java sample
In A class Constructor
In B class Constructor
In C class Constructor
2.4 THE OBJECT CLASS
The Object class is the parent class of all the classes in java by default (directly or indirectly).
The java.lang.Object class is the root of the class hierarchy. Some of the Object class are Boolean,
Math, Number, String etc.
Object
Some of the important methods defined in Object class are listed below.
Object class Methods Description
boolean equals(Object) returns true if two references point to the same object.
String toString() Converts object to String
void notify()
void notifyAll() Used in synchronizing threads
void wait()
void finalize() called just before an object is garbage collected
Object clone() Returns a new object that are exactly the same as the current object
int hashCode() Returns a hash code value for the object.
i) toString()
It converts object to String
Syntax:
Obj.toString( );
Output format:
classname@memoryaddress
Program:
//sample.java
class sample
{
………
}
Abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method. Abstract method can never be final and static.
Note:
A normal class (non-abstract class) cannot have abstract methods.
Syntax:
abstract returntype methodname ();
Rules
1. Abstract class can have abstract and non-abstract methods
2. A normal class (non-abstract class) cannot have abstract methods.
3. Abstract class cannot be instantiated.
4. Abstract method can never be final and static.
5. Abstract classes can have Constructors, Member variables and Normal methods.
Program:
//sample.java
abstract class A
{
abstract void display();
}
class B extends A
{
void display()
{
System.out.println("In B class ");
}
}
class C extends A
{
void display()
{
System.out.println("In C class”);
}
}
class sample
{
public static void main(String[] args)
{
B b =new B( );
C ca = new C( );
b.display( );
ca.display( );
}
}
Output:
javac sample.java
java sample
In B class
In C class
}
}
class B extends A
{
void display()
{
System.out.println("B class");
}
}
class sample
{
public static void main(String args[])
{
B obj= new B();
obj.display();
}
}
Output:
javac sample.java
java sample
/sample.java:11: error: display() in B cannot override display() in A
Points to be remembered while using final methods:
❖ Private methods of the superclass are automatically considered to be final.
❖ Since the compiler knows that final methods cannot be overridden by a subclass, so these
methods can sometimes provide performance enhancement by removing calls to final methods and
replacing them with the expanded code of their declarations at each method call location.
ii) Final Class
❖ Final class is a class that cannot be extended i.e. it cannot be inherited.
❖ A final class can be a subclass but not a superclass.
❖ Declaring a class as final implicitly declares all of its methods as final.
Syntax:
final class classname public final class A
{ {
OR
//code //code
} }
Program:
//sample.java
final class A
{
void display()
{
System.out.println("A class");
}
}
class B extends A
{
void display()
{
System.out.println("B class");
}
}
class sample
{
public static void main(String args[])
{
B obj= new B();
obj.display();
}
}
Output:
javac sample.java
java sample
/sample.java:11: error: B cannot inherit from final A
2.7 INTERFACES
An interface is a reference type in Java. It supports multiple inheritance.
● It is similar to class.
● Interface may also contain abstract methods, default methods, static methods
● An interface can contain any number of methods.
● It gives outline for class
2.7.1 Defining an Interface
An interface is defined by using keyword “interface”
Keyword: interface
Syntax:
interface interfacename
{
datatype instance-variable1;
datatype instance-variable2;
...
datatype instance-variableN;
datatype methodname1(parameter-list)
{
// body of method
}
...
datatype methodnameN(parameter-list)
{
// body of method
}
}
Example:
interface Animal
{
public void eat();
public void travel();
}
2.7.2 Implementing an Interface
Once an interface has been defined, one or more classes can implement that interface.
Keyword: implements
Syntax:
class classname implements interfacename
{
// class-body
}
❖ A class can implement more than one interface at a time.
Example:
Class Mammal implements Animal
{
…………
}
2.7.3 Extending interface
The interface can be extended using multiple inheritance.
Keyword: extends
Syntax:
interface interface
{
…………
}
interface interface extends superinterface
{
…..
}
}
interface Showable
{
void show();
}
class A implements Printable,Showable
{
void print()
{
System.out.println("Hello");
}
void show()
{
System.out.println("Welcome");}
}
}
class sample
{
public static void main(String args[])
{
A obj = new A ();
obj.print();
obj.show();
}
}
Output:
javac sample.java
java sample
Hello
Welcome
2.7.4 Diffference between class and interface
Parameters Class Interface
Basic A class can be instantatied An interface can never be instantiated
Keyword class interface
The members of a class can be private,
The members of an interface are
Access specifier
public or protected. always public.
Methods The methods of a class are defined The methods are not defined
An interface can extend multiple
A class can implement any number of
inheritance interfaces but cannot implement any
interfaces
interface.
Inheritance
extends implements
keyword
Program:
//sample.java
import java.io.*;
class student
{
int a = 10;
int b =20;
}
class sample
{
public static void main(String[] args)
{
student s1 = new student( );
System.out.println(“a=”+ s1.a);
System.out.println(“a=”+ s1.b);
student s2=s1.clone();
System.out.println(“a=”+ s2.a);
System.out.println(“a=”+ s2.b);
}
}
Output:
javac sample.java
java sample
a = 10
b =20
a = 10
b =20
Inner classes are the non staic nested classes. It can be used as the security mechanism in Java. It
is a class that is defined inside the other class.
OUTER
Syntax CLASS
of Inner class
class Outer_class
{ INNER
class Inner_classCLASS
{
…….
}
}
Advantage of java inner classes
● Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class
● Nested classes are used to develop more readable and maintainable code
● Code Optimization: It requires less code to write.
Types of inner class:
1. Non-static nested class (inner class)
a. Member inner class
b. Anonymous inner class
c. Local inner class
2. Static nested class
Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner A class created for implementing interface or extending class. Its name is
Class decided by the java compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
}
}
Program:
//sample.java
class outer
{
class Inner
{
void display()
{
System.out.println("This is an inner class”);
}
public static void main(String args[])
{
outer out = new outer( );
outer.inner in = out.new inner( );
in.display( );
}
}
}
Output:
javac sample.java
java sample
This is an inner class
ii) Anonymous Inner Class
An inner class declared without a class name is known as an anonymous inner class. The
anonymous inner classes can be created and instantiated at the same time.
Program:
//sample.java
class Inner
void display()
};
out.display();
Output:
javac sample.java
java sample
Program:
//sample.java
class outer
{
void display()
{
class Inner
{
void print()
{
System.out.println("This is an inner class”);
}
}
Inner in = new Inner( );
in.print( );
}
public static void main(String args[])
{
outer out = new outer( );
out.display( );
}
}
Output:
javac sample.java
java sample
This is an inner class
2.10 ARRAYLIST
ArrayList is a part of collection framework. It is present in java.util package. It provides us
dynamic arrays in Java.
● ArrayList inherits AbstractList class and implements List interface.
● ArrayList is initialized by a size; however the size can increase if collection grows or shrink
if objects are removed from the collection.
● Java ArrayList allows us to randomly access the list.
● ArrayList cannot be used for primitive types, like int, char, etc.
● ArrayList in Java is much similar to vector in C++.
Constructor Description
ArrayList(Collection c) It is used to build an array list that is initialized with the elements of the
collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
Method Description
void add(int index, Object It is used to insert the specified element at the specified position index in a list.
element)
boolean addAll(Collection c) It is used to append all of the elements in the specified collection
void clear() It is used to remove all of the elements from this list.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the specified
element
Object[] toArray() It is used to return an array containing all of the elements in this list in the correct
order.
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean addAll(int index, It is used to insert all of the elements in the specified collection into this list,
Collection c) starting at the specified position.
Object clone() It is used to return a shallow copy of an ArrayList.
Program:
//sample.java
import java.util.*;
class Arraylistexample
{
public static void main(String args[])
{
ArrayList<String> a1=new ArrayList<String>();
a1.add("Bala");
a1.add("Mala");
a1.add("Vijay");
ArrayList<String> a2=new ArrayList<String>();
a2.add("kala");
a2.add("Banu");
a1.addAll(a2);
Iterator itr=a1.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
Output:
javac sample.java
java sample
Bala
Mala
Vijay
2.11 JAVA STRING
Strings are defined as an array of characters. It must be specified within double quotes. The
difference between a character array and a string is the string is terminated with a special character
‘\0’.
The string objects can be created using two ways.
1. By String literal
2. By new Keyword
i) String Literal
Java String literal is created by using double quotes.
Syntax:
String stringname = “sequenceofcharacters”;
Example:
String str = "java”;
ii) By new keyword
Syntax:
String stringname = new String(“sequenceofcharacters”);
Example:
String str = new String("java”);
Method Description
char charAt(int index) returns char value for the particular index
int length() returns string length
String substring(int beginIndex) returns substring for given begin index
String substring(int beginIndex, returns substring from given begin index to end index
int endIndex)
boolean equals(Object another) checks the equality of string with object
boolean isEmpty() checks if string is empty
String replace(char old, char new) replaces all occurrences of specified char value
String replace(CharSequence old, replaces all occurrences of specified CharSequence
CharSequence new)
int indexOf(int ch, int fromIndex) returns specified char value index starting with given
index
int indexOf(String substring) returns specified substring index
int indexOf(String substring, int returns specified substring index starting with given
fromIndex) index
System.out.println(s1.substring(7,13);
//equals
if(s1.equals(s2))
System.out.println(“same”);
else
System.out.println(“different”);
//uppercase
System.out.println(s1.toUppercase());
//lowercase
System.out.println(s2.toLowercase());
//length
System.out.println(s1.length());
//charat()
System.out.println(s1.charAt(5));
//indexof
System.out.println(s1.indexOf(t));
if(s1.compare(s2)
System.out.println(“s1<s2”);
else
System.out.println(“s1>s2”);
//trim
System.out.println(s1.trim());
//concatenation
System.out.println(s1.concat(s2));
//append
System.out.println(s1.append(s2));\
}
}
Output:
javac stringhandling.java
java stringhandling
s1=object oriented
s2= java
object oriented java
oriented
same
OBJECT
Java
14
t
5
s1>s2
objectoriented
object oriented java
object oriented java
1. Shallow cloning
2. Deep Cloning
2. What is class hierarchy? Give example. ( Nov/Dec 2018)
The class hierarchy defines the inheritance relationship between the classes. The root of the
class hierarchy is the class Object. Every class in Java directly or indirectly extends (inherits
from) this class.
● Existing class is also called as parent class or base class or super class.
● New class is also called as child class or derived class.
3. What is meant by Inheritance? List types (OR) Define super class and subclass.
Inheritance is the process of forming new class from the existing class.
● Existing class is also called as parent class or base class or super class.
● New class is also called as child class or derived class.
●
super();
super(parameterlist);
7. Distinguish between interface and class.
Parameters Class Interface
Basic A class can be instantatied An interface can never be instantiated
Keyword class interface
The members of a class can be private,
The members of an interface are
Access specifier
public or protected. always public.
Methods The methods of a class are defined The methods are not defined
An interface can extend multiple
A class can implement any number of
inheritance interfaces but cannot implement any
interfaces
interface.
Inheritance
extends implements
keyword
An interface can never have a
A class can have constructors to
Constructor constructor as there is hardly any
initialize the variables.
variable to initialize.
class class_Name interface interfaceName
{ {
Declaration //fields //fields
Syntax //Methods //Methods
} }
8. Define abstract class and abstract methods.
Abstract class:
A class that is declared as abstract is known as abstract class. Abstract class can have abstract
and non-abstract methods. It cannot be instantiated.
Keyword :
abstract
Syntax:
abstract class classname
{
………
}
Abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method. Abstract method can never be final and static.
A normal class (non-abstract class) cannot have abstract methods.
Syntax:
abstract returntype methodname ();
9. Write short notes on Object class.
The Object class is the parent class of all the classes in java by default (directly or indirectly).
The java.lang.Object class is the root of the class hierarchy. Some of the Object class are Boolean,
Math, Number, String etc.
Object
Keyword: interface
Syntax:
interface interfacename
{
datatype instance-variable1;
datatype instance-variable2;
...
datatype instance-variableN;
datatype methodname1(parameter-list)
{
// body of method
}
...
datatype methodnameN(parameter-list)
{
// body of method
}
}
12. How will you find out the length of a string in java? Give an example?
length() : returns string length
Example:
String str1 = "object oriented";
System.out.println(s1.length());
Output: 14
13. What is inner class? Give types
Inner classes are the non-static nested classes. It can be used as the security mechanism in Java. It
is a class that is defined inside the other class.
OUTER
Syntax CLASS
of Inner class
class Outer_class
{ INNER
class Inner_classCLASS
{
…….
}
}
4. By new Keyword
i) String Literal
Java String literal is created by using double quotes.
Syntax:
String stringname = “sequenceofcharacters”;
Example:
String str = "java”;
ii) By new keyword
Syntax:
String stringname = new String(“sequenceofcharacters”);
Example:
String str = new String("java”);
ArrayList(Collection c) It is used to build an array list that is initialized with the elements of the
collection c.
ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.
An abstract class can have both abstract An interface can have only abstract
methods
and concrete methods methods
An abstract class can extend only one An interface can extend any number
extends
class or one abstract class at a time of interfaces at a time
abstract class className interface interfaceName
{ {
Declaration //fields //fields
Syntax //Methods //Methods
} }
Method Description
char charAt(int index) returns char value for the particular index
int length() returns string length
String substring(int beginIndex) returns substring for given begin index
String substring(int beginIndex, returns substring from given begin index to end index
int endIndex)
boolean equals(Object another) checks the equality of string with object
boolean isEmpty() checks if string is empty
String replace(char old, char new) replaces all occurrences of specified char value
Syntax:
protected void finalize() // finalize() is called just once on an object
{
………………
}
4. Develop an Employee class which implements the Comparable and Cloneable interfaces.
Implement the sorting of persons (based on name in alphabetical). Also implement the
shallow copy (for name and age) and deep copy (for DateOfJoining
5. Declare an abstract class to represent a bank account with data members name, account
number, address and abstract methods withdraw and deposit. Method display() is needed to show
balance. Derive a subclass Savings Account and add the following details: return on investment
and the method calcAmt() to show the amount in the account after 1 year. Create instance of
Savings Account and show the use of withdraw and deposit abstract methods
ADDITIONAL PROGRAMS
1. Check Palindrome
// Palindrome.java
class Palindrome
{
public static void main(String[] args)
{
int num = 121, rev = 0, remainder;
while( num != 0 )
{
remainder = num % 10;
rev = rev* 10 + remainder;
num /= 10;
}
if (originalInteger == reversedInteger)
System.out.println(originalInteger + " is a palindrome.");
else
System.out.println(originalInteger + " is not a palindrome.");
}
}
Output:
javac Palindrome.java
java Palindrome
121 is a palindrome number.
2. Program to display student grade details
//studentgrade.java
import java.util.Scanner;
class studentgrade
{
public static void main(String[] args)
{
int english, chemistry, computers, physics, maths;
float total, Percentage;
Scanner sc = new Scanner(System.in);
System.out.print(" Please Enter the Five Subjects Marks : ");
english = sc.nextInt();
chemistry = sc.nextInt();
computers = sc.nextInt();
physics = sc.nextInt();
maths = sc.nextInt();
total = english + chemistry + computers + physics + maths;
Percentage = (total / 500) * 100;
System.out.println(" Total Marks = " + total);
System.out.println(" Marks Percentage = " + Percentage);
if(Percentage >= 80)
{
System.out.println("Grade A");
}
else if(Percentage < 80 && Percentage >=60)
{
System.out.println("Grade B");
}
else if(Percentage <60 && Percentage >=40)
{
System.out.println("\n Grade C");
}
else
{
System.out.println("Grade D");
}
}
}
Output:
javac studentgrade.java
java studentgrade
Please Enter the Five Subjects Marks : 80 80 70 85 94
Total Marks=409.0
Marks Percentage =81.6
Grade B
3. String operations using ArrayList
import java.util.*;
public class sample
{
public static void main(String[] args)
{
ArrayList<String> lst = new ArrayList<String>();
lst.add("C"); // add() takes Object. String upcast to Object implicitly
lst.add("Java");
lst.add("Perl");
System.out.println(lst);
int choice;
String s;
System.out.pritln(“1.append 2.insert 3.search 4. List”);
Scanner sc=new Scanner(System.in);
System.out.println("enter choice");
choice=sc.nextInt();
switch(choice)
{
case 1:
System.out.println("enter String");
s=sc.next();
lst.add(s);
System.out.println(lst);
break;
case 2:
System.out.println("enter index and string to insert");
int index=sc.nextInt();
s=sc.next();
lst.add(index,s);
System.out.println(lst);
break;
case 3:
System.out.println("enter String to search");
s=sc.next();
System.out.println(lst.contains(s));
break;
case 4:
System.out.println(lst);
break;
default:
System.out.println("enter correct choice");
}
}
}
CHAPTER III
DEPARTMENT OF CSE Page 120
Object Oriented Programming 2019
Errors are not exception.Errors are problems that may arise beyond the control of the user.
Exception Hierarchy
Exceptions can be classified into three categories
1. Checked Exception / Compile time Exeptions
2. Unchecked exception / Runtime Exeptions
3. Own Exception
3.1. 1.CHECKED EXCEPTIONS
A checked exception is an exception that occurs at the compile time, also called as compile time
(static time) exceptions. These exceptions cannot be ignored at the time of compilation.
Checked Exception is divided into following types,
i) ClassNotFound Exception
ii) IllegalAccess Exception
iii) NoSuchField Exception
iv) NoSuchMethod Exception
v) EOF Exception
vi) FileNotFound Exception
vii) UnknownHost Exception
i) ClassNotFound Exception
If the class is not found in the program,the exception is thrown
ii) IllegalAccess Exception
If the denied class is accessed, the exception is thrown.
iii) NoSuchField Exception
If the field does not exist in the program,the exception is thrown.
iv) NoSuchMethod Exception
If the method does not exist in the program,the exception is thrown.
v) EOF Exception
If the EndOfFile is not reached,the exception is thrown.
i) FileNotFound Exception
If the file is not found,the exception is thrown.
ii) UnknownHost Exception
If the host is unknown,the exception is thrown.
java.lang
3.1.2.UNCHECKED EXCEPTIONS / RUNTIME EXEPTIONS
An unchecked exception is an exception that occurs at run time, also called as Runtime
Exceptions. Runtime exceptions are ignored at the time of compilation.
object
Unchecked Exception is divided into following types,
i) Arithmetic expectation
ii) ArrayIndexOutOfBounds Exception
iii) NegativeArraySize Exception throwable
iv) IllegalState Exception
v) NullPointer Exception
i) Arithmetic expectation
error exception
If divide by zero occurred,then the exception is thrown.
ii) ArrayIndexOutOfBounds Exception
compile runtime checked unchecked own
DEPARTMENT
error OF CSE error Page 123
exception exception exception
IO classNotFound IllegalAccess
Object Oriented Programming 2019
Output
C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Division by zero
Completed
⮚ Exception handling means it detects and report the exception in the program and handles
the exception.
⮚ It is the error handling mechanism in java.
There are four task in the exception handling process.
1. Try the exception
The exception is created here and finds the exception.
2. Throw the exception
Informs that the exception has been occurred.
3. Catch the exception
Receive the exception information.
4. Handle the exception
Take the corrective action.
try
i) Try Block
The try block contains
throw exception causing statement. It is implemented by the keyword ‘try’. It
must be followed by either catch or finally block. If an exception occurs it is thrown
Syntax
try catch
{
statement1;
statement2; // exception causing statement
statement3; handle
}
ii) Throw Block
The ‘throw’ keyword is used to throw an exception.When exception is raised in try block,then it
is thrown to catch block.
Syntax
throw(Exception);
catch(Exception e)
{
statement1;
statement2; // exception handling statement
}
Program:
//Exceptiondemo.java
class Exceptiondemo
{
public static void main(String args[])
{
int a =10,b=0,c;
try
{
c = a/b;
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
System.out.println("completed.");
}
}
Output
C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Division by zero
Completed
iv) Multiple catchblock
In some situation,different exception occurs in the single try block. To handle such situation, we
use the multiple catch block. When the exception is thrown ,the exception handler search for the
appropriate block. If the match is found,the exception is displayed.when no match is found,the
program is terminated.
Syntax
try
{
……….
……….
}
catch(Exception e)
{
………..
………..
}
catch(Exception e)
{
………..
………..
}
Program:
//Exceptiondemo.java
class Exceptiondemo
{
public static void main(String args[])
{
int a[2]={10,20};
int c;
try
{
c = a[2]/10;
}
catch (ArithmeticException e)
{
System.out.println("Divide by zero.");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index error");
}
System.out.println("completed.");
}
}
Output
C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Array index error
Completed
v) Throwing exception
Throwing exception is done by two methods.
1. Using throw
2. Using throws
Using throw
● It is used to throw exception explicitly.
● It is declared by the keyword ‘throw’
● ‘throw’ is used within method
Program:
//Exceptiondemo.java
class Exceptiondemo
{
public static void main(String args[])
{
int a =10,b=0,c;
if(b==0)
{
throw new ArithmeticException(“divide by zero”);
}
System.out.println("completed.");
}
}
Output
C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Exception in thread:java.lang.ArithmeticException:divide by zero
at ExceptionThrow.fun(ExceptionThrow.java:7)
at ExceptionThrow.fun(ExceptionThrow.java:17)
Using throws
When method wants to throw exception,’throws’ keyword is used.
Syntax
methodname(parameterlist)throws Exception
{
……………
}
Program:
//Exceptiondemo.java
class Exceptiondemo
{
void fun(int a,int b) throws ArithmeticException
{
int c;
try
{
c=a/b;
}
catch(Arithmetic Exception e)
{
System.out.println("uncaught Exception." +e);
}
}
public static void main(String args[])
{
int a=5;
int b=10;
fun(a,b);
}
}
Output
C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Uncaught Exception : java.lang
.ArithmeticException:divide by zero
throw throws
Java throw keyword is used explicitly to Java throws keyword is used to declare an
throw an exception. exception.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method signature.
we cannot throw multiple exceptions. We can declare multiple exceptions.
iv) finallyblock
A finally block of code always executes, irrespective of occurrence of an Exception. The finally
block follows a try block or a catch block. finally block statement is also called as cleanup code.
The finally block is to free the resources.
Syntax
try
…………
// Catch block
// Catch block
finally
Program:
//Exceptiondemo.java
class Exceptiondemo
{
public static void main(String args[])
{
int a =10,b=0,c;
try
{
c = a/b;
}
catch (ArithmeticException e)
{
System.out.println("Division by zero.");
}
finally
{
System.out.println("completed.");
}
}
}
Output
C:\javac Exceptiondemo.java
C:\java Exceptiondemo
Division by zero
Completed
Nested try
Try blocks embedded within another try block is nested try.
Syntax
try
………..
try
……….
NoSuchFieldException It is thrown when a class does not contain the field (or
variable) specified.
EOFException If the EndOfFile is reached,the exception is thrown..
FileNotFoundException If the file is not found,the exception is thrown.
UnknownHostException It is thrown when a thread is waiting, sleeping, or doing
some processing, and it is interrupted./if the host is
unknown,the exception is thrown.
Arithmetic Exception It is thrown when an exceptional condition has
occurred in an arithmetic operation.eg.divide by zero.
Program:
Refer page no:
3.4 CREATING OWN EXCEPTIONS (USER DEFINED EXCEPTIONS)
We can create our own exceptions in java and throws that exception using ‘throw’ keyword.
Syntax
class ownException extends Exception
{
………..
}
throw new OwnException();
Example:
class MyException extends Exception
{
…………….
}
throw new MyException();
Program:
import java.lang.Exception;
class MyException extends Exception
{
int a;
MyException(int b)
{
a=b;
}
public String toString()
{
return(“Exception number=” +a);
}
}
class Exceptiondemo
{
public static void main(String args[])
{
try
{
throw new MyException(2);
}
catch(MyException e)
{
System.out.println(e);
}
}
}
Output
C:\javac ownexceptiondemo.java
C:\java ownexceptiondemo
Exception number=2
Explanation
In the above program, MyException is the user defined exception.In the try block,throw the
MyException with the value 2.so,as to get the value of 2.when the exception is thrown, the catch
block gets executed.so we get the output message ‘Exception number=2’
3.5 STACK TRACE ELEMENTS
Stack Trace Element is created to represent the specific execution point.
Syntax
StackTraceElement(String classname, String methodname, String filename,
int linenumber);
where,
StackTraceElement -- represents the StackTraceElement
Classname -- represents the name of the class for the execution point.
methodname – represents the name of the method for the execution point.
filename – represents the name of the file for the execution point.
linenumber – represents the linenumber for the execution point. If linenumber is negative ,it
denotes information is unavailable.
Methods
1. String getclassName()
It returns the classname which is represented by StackTraceElement.
2. String getfileName()
It returns the filename which is represented by StackTraceElement.
3. int getLineNumber()
It returns the linenumber which is represented by StackTraceElement.
4. int hashcode()
It returns the hashcode of the StackTraceElement.
5. String toString()
It returns the string which is represented by StackTraceElement.
6. boolean equals(object obj)
It returns the true if the object and the StackTraceElement represent the same execution point.
Program:
//StackTracedemo.java
public class StackTracedemo
{
public static void main(String[] args)
{
try
{
throw new RuntimeException("go"); //raising an runtime exception
}
catch(RuntimeException e)
{
System.out.println("Printing stack trace:");
final StackTraceElement[] s = e.getStackTrace();
System.out.println(s.getFileName() + ":" + s.getLineNumber());
}
}
}
Output:
C:\javac StackTracedemo.java
C:\java StackTracedemo
Printing stack trace:
StackTracedemo.java:5
3.6 INPUT / OUTPUT BASICS (STREAMS)
Java I/O (Input and Output) is used to process the input and produce the output. Java uses the
concept of stream to make I/O operation fast. All the classes required for input and output
operations are declared in java.io package.
Stream is a channel on which data flow from sender to receiver.
⮚ A stream can also be defined as a sequence of data.
⮚ The InputStream is used to read data from a source
⮚ OutputStream is used for writing data to a destination.
Types Of Streams
Java supports two types of streams. They are,
1. Byte Stream
2. Character Stream
Streams
1. Byte Stream : It is used for handling input and output of 8 bit bytes. The frequently used
classes are FileInputStream and FileOutputStream.
2. Character Stream : It is used for handling input and output of characters. Character stream
uses 16 bit Unicode. The frequently used classes are FileReader and FileWriter.
Byte Stream
3.6.1 BYTE STREAMS Character Stream
⮚ Byte stream is used for reading and writing bytes.
⮚ Byte stream is the abstract class.
⮚ There are two kinds of byte stream classes:
a. InputStream classes
b. Input Stream
OutputStream classes.Output Stream Reader Stream Writer Stream
i) InputStream
⮚ InputStream class is an abstract class.
⮚ The InputStrearn class is the superclass for all byte-oriented input stream classes.
⮚ All the methods of this class throw an IOException.
⮚ The InputStrearn class cannot be instantiated hence, its subclasses are used.
Input Streams
The InputStream classes are
Class Description
BufferedInputStream contains methods to read bytes from the buffer (memory area)
Buffered Input Stream Sequence Input Stream
ByteArrayInputStream contains methods to read bytes from a byte array
DataInputStream contains methods to read primitive data types
FileInputStream contains methods to read bytes from a file
Data Input Stream Object Input Stream
ObjectInputStream contains methods to read bytes from the object.
PipedInputStream contains methods to read from the pipe.
SequenceInputStream contains methods to concatenate multiple input streams and then read
from the combined stream.
Methods in the InputStream
1.read()
It is used to read the byte.
2.read(byte b[])
It is used to read the byte from the array b.
3.read(byte b[],int n,int m)
It read the m bytes starting from nth byte from b.
4.close()
It is used to close the InputStream.
ii) OutputStream
⮚ OutputStream class is an abstract class.
⮚ The OutputStrearn class is the superclass for all byte-oriented output stream classes.
⮚ All the methods of this class throw an IOException.
Output Streams
The Output Stream classes are
Class Description
BufferedOutputStream Contains methods to write bytes to the buffer.
ByteArrayOutputStream
Buffered Output Stream Contains methods to write bytes into a byte array Output Stream
Sequence
DataOutputStream Contains methods to write primitive data types
FileOutputStream Contains methods to write bytes to a file
Data Output Stream Object Output Stream
ObjectOutputStream Contains methods to write bytes to the object.
PipedOutputStream Contains methods to write to a pipe.
SequenceOutputStream Contains methods to write bytes to the multiple output stream.
Piped Output Stream
Byte Array Output Stream
Methods in the OutputStream
1.write() File Output Stream
It is used to write the byte.
2.write(byte b[])
It is used to write the byte from the array b.
3.write(byte b[],int n,int m)
It write the m bytes starting from nth byte from b.
4.close()
It is used to close the InputStream.
3.6.2 CHARACTER STREAMS
⮚ Character Stream is used for inputing and outputting character.
⮚ There are two kinds of character stream classes:
a. ReaderStream
b. WriterStream
a.Reader Stream
⮚ Reader Stream classes are used to read 16-bit unicode characters from the input stream.
DEPARTMENT OF CSE Page 136
Object Oriented Programming 2019
⮚ The Reader class is the superclass for all character-oriented input stream classes.
⮚ All the methods of this class throw an IOException.
Reader Stream
The Reader Stream classes are
Reader class Description
BufferedReader contains methods to read characters from the buffer
CharArray Reader contains methods to read characters from the CharArray
Buffered Reader
InputStreamReader contains methods to read the character fromPipe
theReader
InputStream
File Reader contains methods to read the character from a file
String Reader contains methods to read the character from the string
Filter Reader
Char Array Reader contains methods to read the character fromReader
Pushback the filter
Pipe Reader contains methods to read the character from the pipe
Pushback Reader contains methods to pushing back character
Methods in the ReaderStream
1.read() String Reader
Input Stream Reader
It is used to read the character.
2.read(char b[])
It is used to read the array of characters from b. Reader
Filter
3.read(char b[],int n,int m)
File Reader
It read the m characters from array b starting from nth character.
4.close()
It is used to close the ReaderStream.
b.Writer Stream
⮚ Writer classes are used to write 16-bit Unicode characters onto an outputstream.
⮚ The Writer class is the superclass for all character-oriented output stream classes .
⮚ All the methods of this class throw an IOException
Writer Stream
The Writer Stream classes are
Writer class Description
BufferedWriter contains methods to write characters onto the buffer
Buffered Writer
CharArray Writer contains methods to write characters ontoPipe
the Writer
CharArray
OutputStreamWriter contains methods to write characters onto the OutputStream
File Writer contains methods to write the character onto a file
Char Array Writer Print Writer
String Writer contains methods to write the character onto the string
Filter Writer contains methods to write the character onto the filter
Pipe Writer String Writer
contains methods to write the character onto the pipe
Output Stream Writer
Print Writer contains print( ) and println( ) methods to write the characters
Methods in the WriterStream Filter Writer
File Writer
DEPARTMENT OF CSE Page 137
Object Oriented Programming 2019
1.write()
It is used to write the character.
2. write(char b[])
It writes the array of characters to b.
3. write(char b[],int n,int m)
It write the m characters starting from nth character into b.
4.close()
It is used to close the WriterStream.
3.7 READING AND WRITING CONSOLE
⮚ In java, system is a class defined in java.lang and in,out,err are the variables of the class
system.
⮚ system.out is an object used for standard OutputStream and system.in and system.err are
the objects for the Standard InputStream and err.
3.7.1 Reading Console : Input
Reads the input from the keyboard using two methods
1. Using BufferedReader
2. Using Scanner
1) Using BufferedReader
System.in is used to read some characters from the console.
Syntax
BufferedReader objectname=new BufferedReader(new InputStreamReader(system.in));
Steps:
i.Import the java.io package
ii.Create the instance for BufferedReader
Syntax
BufferedReader objectname=new BufferedReader(new InputStreamReader(system.in));
iii.Use the read method to read the character string
Reading the character
Program:
//readchardemo.java
import java.io.*;
class readchardemo
{
public static void main( String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char c;
System.out.println("Enter character: ");
c = (char)br.read(); //Reading character
System.out.println(“character=”+c);
}
}
Output
C:\javac readchardemo.java
C:\java readchardemo
Enter character:k
character=k
Reading the string
Program:
//readstringdemo.java
import java.io.*;
class readstringdemo
{
public static void main( String args[])throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
System.out.println("Enter String: ");
s = br.readLine();
System.out.println(“String=”+s);
}
}
Output
C:\javac readstringdemo.java
C:\java readstringdemo
Enter String:object oriented
String= object oriented
2).Using Scanner
The scanner is a class defined in java.util package
Steps:
i.Import the java.util package
ii.Create the instance for the Scanner class
Syntax
Scanner obj=new Scanner(system.in);
iii.Use the next() method to read the input.
Reading the character
Program:
//readchardemo.java
import java.io.*;
class readchardemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
char c;
System.out.println("Enter character: ");
c = (char)sc.next(); //Reading character
System.out.println(“character=”+c);
}
}
Output
C:\javac readchardemo.java
C:\java readchardemo
Enter character:k
character=k
Reading the string
Program:
//readstringdemo.java
import java.io.*;
class readstringdemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
String s;
System.out.println("Enter String: ");
s = sc.next();
System.out.println(“String=”+s);
}
}
Output
C:\javac readstringdemo.java
C:\java readstringdemo
Enter String:object oriented
String= object oriented
Reading the Integer
Program:
//readintdemo.java
import java.io.*;
class readintdemo
{
public static void main( String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
int i;
System.out.println("Enter integer: ");
i=sc.nextInt();
System.out.println(“Integer=”+i);
}
}
Output
C:\javac readintdemo.java
C:\java readintdemo
Enter integer:10
Integer= 10
3.7.2 Writing Console : Output
There are three methods to write console output.
1. System.out.write()
2. System.out.print() and System.out.println()
3. Using PrintWriter class
1.System.out.write()
writing the integer
Program:
writeintdemo.java
class writeintdemo
{
public static void main(String args[])throws IOException
{
int a=5;
System.out.write("a="+a);
}
}
Output
C:\javac writeintdemo.java
C:\java writeintdemo
a=5
2.System.out.println()
Program:
//printlndemo.java
class printlndemo
{
public static void main(String args[])throws IOException
{
int a=5;
System.out.println("a="+a);
}
}
Output
C:\javac printlndemo.java
C:\java printlndemo
a=5
3.Using PrintWriter class
Program:
//writeintdemo.java
class writeintdemo
{
public static void main(String args[])throws IOException
{
int a=5;
PrintWriter pw=new PrintWriter(System.out,true);
pw.write(a);
}
}
Output
C:\javac writeintdemo.java
C:\java writeintdemo
5
3.8 READING AND WRITING FILES
⮚ Java provides the method to read and write bytes from and to a file.
⮚ Java contains two classes for reading/writing files.They are
1. FileInputStream
2. FileOutputStream
3.8.1.FILE
Input INPUTSTREAM
File File Input
FileInput stream is used for reading data from the files.
Two common constructors Stream
i) FileInputStream(filename)
ii) FileInputStream(fileobj) Program
i) fileInputStream(filename)
Syntax
InputStream f = new FileInputStream("filename ");
OutputOF
DEPARTMENT File
CSE Page 142
File Output
Stream
Object Oriented Programming 2019
ii) fileInputStream(fileobj)
Syntax
InputStream f = new FileInputStream(f);
Methods in the FileInputStream
1.int read()
It reads the byte from the file.
It returns the total number of bytes for reading.
2.int read(byte b[])
It reads the byte from the array b.
3.int read(byte b[],int n,int m)
It reads m bytes from array b starting from nth byte.
4.int available()
It returns the number of bytes that are available for reading.
5.void reset()
It reset the pointer to the beginning of the file.
6.int mark(int n)
It place the pointer to the nth byte.
7.void close()
It closes the FileInputStream.
3.8.2.FILEOUTPUTSTREAM
FileOutputStream is used to create a file and write data into it.
Two common constructors
i) FileOutputStream(filename)
ii) FileOutputStream(fileobj)
i) FileOutputStream(filename)
Syntax
OutputStream f = new FileOutputStream("filename");
ii) FileOutputStream(fileobj)
Syntax
OutputStream f = new FileOutputStream(f);
Methods in the FileOutputStream
1.int write()
● It writes the byte to the file.
● It returns the total number of bytes for writing.
2.int write(byte b[])
It writes the byte to the array b.
3.int write(byte b[],int n,int m)
It writes m bytes starting from nth byte to b.
4.flush()
It is used for clearing the file.
5.close()
It closes the FileOutputStream
Program for copying the file into another file
Program: copyfiledemo.java
import java.io.*;
class copyfiledemo
{
public static void main(String args[])throws IOException
{
File f1=new file(“input.txt”);
File f2=new file(“output.txt”);
byte b;
try
{
FileInputStream fis = new FileInputStream("f1");
FileOutputStream fos = new FileOutputStream("f2");
do
{
b=(byte)fis.read();
fos.write(b);
}while(b!=-1);
}
catch (filenotfoundException e)
{
System.out.println("file is not found");
}
finally
{
System.out.println("end of program");
fis.close();
fos.close();
}
}
}
Output
C:\type input.txt
object oriented
C:\type output.txt
C:\javac copyfiledemo.java
C:\java copyfiledemo
end of program
C:\type output.txt
object oriented
java
PART A (2 Marks with Answers)
1.Define runtime exception. (nov/dec2018)
An unchecked exception is an exception that occurs at run time, also called as Runtime
Exceptions.Runtime exceptions are ignored at the time of compilation.
i) Arithmetic expectation
ii) ArrayIndexOutOfBounds Exception
{
…………
}
catch (ExceptionType1 e1)
{
// Catch block
}
catch (ExceptionType2 e2)
{
// Catch block
}
finally
{
// The finally block always executes.
}
11. What is the use of Stack Trace Element?
It is created to represent the specific execution point.
Syntax
StackTraceElement(String classname, String methodname, String filename,
int linenumber);
where,
StackTraceElement -- represents the StackTraceElement
Classname -- represents the name of the class for the execution point.
methodname – represents the name of the method for the execution point.
filename – represents the name of the file for the execution point.
linenumber – represents the linenumber for the execution point. If linenumber is negative ,it
denotes information is unavailable
12. What are the methods in StackTrace Element
7. String getclassName()
It returns the classname which is represented by StackTraceElement.
8. String getfileName()
It returns the filename which is represented by StackTraceElement.
9. int getLineNumber()
It returns the linenumber which is represented by StackTraceElement.
10. int hashcode()
It returns the hashcode of the StackTraceElement.
11. String toString()
It returns the string which is represented by StackTraceElement.
12. boolean equals(object obj)
It returns the true if the object and the StackTraceElement represent the same execution point.
13. Define Stream. What are the types.
Stream is a channel on which data flow from sender to receiver.
⮚ A stream can also be defined as a sequence of data.
⮚ The InputStream is used to read data from a source
⮚ OutputStream is used for writing data to a destination.
16. How read and write operation from the console is performed in java?
● Reads the input from the keyboard using two methods
3. Using BufferedReader
4. Using Scanner
● There are three methods to write console output.
4. System.out.write()
5. System.out.print() and System.out.println()
6. Using PrintWriter class
17. What are input and output streams?
An I/O Stream represents an input source or an output destination. A stream can represent many
different kinds of sources and destinations, including disk files, devices, other programs, and
memory arrays.
18. How the user create their own exceptions?
We can create our own exceptions in java and throws that exception using ‘throw’ keyword.
Syntax
class ownException extends Exception
{
………..
}
throw new OwnException();
Example:
class MyException extends Exception
{
…………….
}
throw new MyException();
3.Explain briefly about user defined exceptions and the concept of throwing and catching
exception in java with examples.
4. Describe the stack trace elements with an example.
5.Summarize the concept of streams and stream classes and their classification
6.Differentiate byte stream and character stream with necessary examples.
7.Explain how to handle arithmetic exception by giving a suitable example.
8.Explain the importance of try - catch block with example
9.Evaluate a try block that is likely to generate three types of exception and then incorporate
necessary catch blocks and handle them appropriately.
10.Write programs to illustrate arithmetic exception, ArrayIndexOutOfBounds Exception and
NumberFormat Exception.
2. Develop the Java program to concatenate the two files and produce the output in the
third file.
3. How does InputStream.read() method work? Can you give me some sample code?
4. Deduce a Java program that reads a file name from the user, displays information about
whether the file exists, whether the file is readable, or writable, the type of file and the length of
the file in bytes.
5. Why only read() methods in ByteArrayInputStream does not throw IOException?
6. Write a calculator program using exceptions and functions.
7. Write a program to receive the name of a file within a text field and then displays its
contents within a text area.
ADDITIONAL PROGRAMS
1.write a program to accept 5 numbers from the user and display it.
Program:
numberdemo.java
import java.io.*;
class numberdemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
int i=1,n;
System.out.println("Enter number: ");
while(i<=5)
{
n=sc.nextInt();
System.out.println(“number=”+n);
i++;
}
}
}
Output
C:\javac numberdemo.java
C:\java numberdemo
Enter number:5 10 15 20 25
number= 5
number= 10
number= 15
number= 20
number= 25
2. write a program to accept 7 characters from the user and display it.
Program:
chardemo.java
import java.io.*;
class chardemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
char c;
int i=1;
System.out.println("Enter character: ");
while(i<=7)
{
c = (char)sc.next(); //Reading character
System.out.println(“character=”+c);
i++;
}
}
}
Output
C:\javac chardemo.java
C:\java chardemo
Enter character:a b c d e f g
character=a
character=b
character=c
character=d
character=e
character=f
character=g
3. write a program to accept 5 employee name from the user and display it.
Program:
employeedemo.java
import java.io.*;
class employeedemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
String s;
int i=1;
System.out.println("Enter employee name: ");
while(i<=5)
{
s = sc.next();
System.out.println(“employee name=”+s);
i++;
}
}
}
Output
C:\javac employeedemo.java
C:\java employeedemo
Enter employee name:abi binu ravi raghu rahul
employee name= abi
employee name= binu
employee name= ravi
employee name= raghu
4. write a program to accept 3 marks from the user and find the total,average and display
it.
Program:
markdemo.java
import java.io.*;
class markdemo
{
public static void main(String args[])throws IOException
{
Scanner sc=new Scanner(system.in);
int m1,m2,m3;
int total;
float average;
System.out.println("Enter mark1: ");
m1=sc.nextInt();
System.out.println("Enter mark2: ");
m2=sc.nextInt();
System.out.println("Enter mark3: ");
m3=sc.nextInt();
total= m1+m2+m3;
average=total/3;
System.out.println("Total="+total);
System.out.println("Average="+average);
}
}
Output
C:\javac markdemo.java
C:\java markdemo
Enter mark1:90
Enter mark2:80
Enter mark3:100
Total=270
Average=90
CHAPTER IV
Waiting state
● When one thread is waiting for another thread, it is in the waiting state.
● When the condition is fulfilled, waiting thread is moved to the runnable state.
Timed Waiting State
● When thread is waiting for time interval, it is in the Timed waiting state.
● After the time interval,timed waiting thread is moved to the runnable state.
Blocked State
● When the thread is waiting for input and output, it is in the blocked state.
● After getting the input and output resources,blocked thread is moved to the runnable state.
Terminated State:
● When the thread successfully completes the execution, it is moved to the Terminated State.
4.3 CREATING THREADS / IMPLEMENTING THREADS
Thread is th light weight process. Threads does not require separate memory address for
its execution.
Threads are independent, concurrent execution through a program, and each thread has its own
stack.
Threads can be created in two ways
1. Extending ‘Thread’ class.
2. Implementing Runnable interface.
DEPARTMENT OF CSE
Thread Class Page 159 Runnable interface.
Object Oriented Programming 2019
run Once the thread is started,it executes the thread / Entry point for the thread
getName Used to get the name of the thread /To obtain thread’s name
{
System.out.println("Thread B is created ");
}
}
class C extends Thread
{
public void run()
{
System.out.println("Thread C is created ");
}
}
class threaddemo
{
public static void main(String args[])
{
A a=new A();
B b=new B();
C c=new C();
a.start();
b.start();
c.start();
}
}
Output:
C:\javac threaddemo.java
C:\java threaddemo
Thread A is created
Thread B is created
Thread C is created
4.3.2 Implementing Runnable Interface:
Threads can be created by implementing runnable interface.
Steps:
i) Declare the class by implementing runnable interface.
Example: class mythread implements Runnable
{
………….// mythread code
}
ii) Implements the run() method.
Example: class mythread implements Runnable
{
Public void run()
{
………
}
}
iii) Create the thread object and call the start() method.
Example: mythread mt=new mythread();
Thread t=new Thread(mt);
mt.start();
Program
// threaddemo.java
class A implements Runnable
{
Public void run()
{
System.out.println("Thread A is created ");
}
class B implements Runnable
{
Thread A is created
Thread B is created
Thread C is created
4.4 SYNCHRONIZING THREADS
The process of ensuring one access at a time by one thread is called as synchronization.
Synchronization is based on monitor.monitor is used as a mutually exclusive lock or mutex.
When one thread owns this monitor at a time, then other threads cannot access the
resources.They have to be in waiting state.
Methods of synchronization:
Synchronization can be achieved by two ways.
1. Using synchronized method.
2. Using synchronized block or statements.
4.4.1 Synchronized Method
Synchronization can be achieved using synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
Here, we use the synchronized keyword infront of the method name
Syntax:
synchronized returntype methodname()
{
statement1;
statement2;
………….
statementn;
}
Program
//threaddemo.java
class test
{
synchronized void display(int n)
{
System.out.println(“TABLE:”+n);
for(int i=1;i<=10;i++)
{
System.out.println(n*i);
}
System.out.println(“end of table”);
}
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("Exception occurred");
}
}
class A extends Thread
{
test t1;
A(test t)
{
t1=t;
}
public void run()
{
t1.display(2);
}
}
class B extends Thread
{
test t2;
B(test t)
{
t2=t;
}
public void run()
{
t2.display(10);
}
}
class threaddemo
{
public static void main(String args[])
{
test ts = new test();
A a=new A(ts);
B b=new B(ts);
a.start();
b.start();
}
}
Output:
C:\javac threaddemo.java
C:\java threaddemo
TABLE:2
2 4 6 8 10 12 14 16 18 20
end of table
TABLE:10
10 20 30 40 50 60 70 80 90 100
end of table
4.4.2 Synchronized Block
Synchronization can be achieved using synchronized block.
⮚ Synchronized block acquires a lock in the object only between parentheses after the
synchronized keyword.
⮚ This means that no other thread can acquire a lock on the locked object until the
synchronized block exits.
⮚ But other threads can access the rest of the code of the method.
⮚ Here, we create the block of code and write synchronized keyword infront of Block.
Syntax:
synchronized (object reference)
{
statement1;
………….
statementn;
}
Program
//threaddemo.java
class test
{
void display(int n)
{
synchronized(this)
{
System.out.println(“TABLE:”+n);
for(int i=1;i<=10;i++)
{
System.out.println(n*i);
}
System.out.println(“end of table”);
}
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("Exception occurred");
}
}
class A extends Thread
{
test t1;
A(test t)
{
t1=t;
}
public void run()
{
t1.display(2);
}
}
class B extends Thread
{
test t2;
B(test t)
{
t2=t;
}
public void run()
{
t2.display(10);
}
}
class threaddemo
{
public static void main(String args[])
{
test ts = new test();
A a=new A(ts);
B b=new B(ts);
a.start();
b.start();
}
}
Output:
C:\javac threaddemo.java
C:\java threaddemo
TABLE:2
2 4 6 8 10 12 14 16 18 20
end of table
TABLE:10
10 20 30 40 50 60 70 80 90 100
end of table
4.5 INTER-THREAD COMMUNICATION
Inter-thread communication or Co-operation is all about allowing synchronized threads to
communicate with each other. Two or more threads can communicate with each other by
exchanging the messages. This mechanism is called Inter-thread communication.
Inter-thread communication can be achieved by using three methods
1. wait()
2. notify()
3. notifyAll()
i.wait()
The calling thread can be sent into the sleeping mode.
Syntax: wait();
ii.notify()
If the particular thread is in sleeping mode,then that thread can be resumed using the notify
cal. It resume the thread that is in sleeping state.
syntax:
public final void notify()
3.notifyAll()
It resume all the threads that are in the sleeping mode.
syntax:
public final void notifyAll()
Example.
The explanation of the below diagram is as follows:
1. Threads enter to acquire lock.
2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object. Otherwise it
releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state (runnable
state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor state of the
object.
Flag=false flag=false
Produce no 1 Sleeping Mode
Flag=true
Notify()
Sleeping Mode
myclass
flag=false
Program val
//interthreaddemo.java
class myclass get()
{ put()
int val;
boolean flag=false;
A B
synchronized int get()
{ get()
if(flag=false)
put()
{
try
{
wait(); InterThread
}
catch(Exception e)
{ A().start();
System.out.println("Exception occurred");
B().start();
}
}
System.out.println("consumer consuming:"+val);
flag=false;
notify();
return val;
}
synchronized void put()
{
if(flag=true)
{
try
{
wait();
}
catch(Exception e)
{
System.out.println("Exception occurred");
}
}
this.val=val;
System.out.println("producer producing:"+val);
flag=true;
notify();
}
class Producer extends Thread
{
myclass m1;
producer(myclass t)
{
m1=t;
}
public void run()
{
for(int i=0;i<=10;i++)
{
m1.put(i);
}
}
}
class consumer extends Thread
{
myclass m1;
consumer(myclass t)
{
m2=t;
}
public void run()
{
for(int i=0;i<=10;i++)
{
m2.get(i);
}
}
}
class interthreaddemo
{
public static void main(String args[])
{
myclass m = new myclass();
producer p=new producer(m1);
consumer c=new consumer(m2);
p.start();
c.start();
}
}
Output:
C:\javac interthreaddemo.java
C:\java interthreaddemo
producer producing:0
consumer producing:0
producer producing:1
consumer producing:1
producer producing:2
consumer producing:2
producer producing:3
consumer producing:3
producer producing:4
consumer producing:4
producer producing:5
consumer producing:5
producer producing:6
consumer producing:6
producer producing:7
consumer producing:7
producer producing:8
consumer producing:8
producer producing:9
consumer producing:9
producer producing:10
consumer producing:10
4.6 DAEMON THREADS
Daemon thread is a low priority thread that runs in background to perform tasks such as garbage
collection. Daemon thread in java is also called as service provider thread which provides services
to the user thread.
Methods for Java Daemon thread
Method Description
ThreadGroup(ThreadGroup parent, String creates a thread group with given parent group and
name) name.
Methods used in ThreadGroup class
Method Description
thread list
java.lang.ThreadGroup[name=colours,maxpri=10]
Thread[red,3,Parent ThreadGroup]
Thread[yellow,3,Parent ThreadGroup]
Thread[blue,3,Parent ThreadGroup]
4.8 GENERIC PROGRAMMING
Generic Programming is a mechanism for creating general model for different datatypes.
generic programming
this.a = a;
}
T get()
{
return a;
}
}
class genericclassdemo
{
public static void main (String[] args)
{
GenericClass< Integer> gc1 = new GenericClass<Integer>(10); //instance of Integer type Gen
Class.
System.out.println(“integer=”+gc1.get());
GenericClass< float> gc2 = new GenericClass<float>(10.5);
System.out.println(“float=”+gc2.get());
GenericClass< String> gc3 = new GenericClass<String>("Hello"); //instance of String type Gen
Class.
System.out.println(“string=”+gc3.get()); }
}
Output:
C:\javac genericclassdemo.java
C:\java genericclassdemo
integer=10
float=10.5
string=Hello
4.8.2 GENERIC METHODS
⮚ Generic Method can accept any type of argument like generic class.
⮚ Genric method enables the programmer to specify the general method for the methods of
different datatypes.
Syntax for a generic method
<type-parameter> returntype methodname (parameters)
{
...........
}
where, <> brackets 🡪method of generic type with type parameter T.
T -🡪 anydatatype (like String, Integer, Student etc.).
Program
Finding Maximum Number Using Generic Method
maxdemo.java
class maxdemo
{
public static<T extends comparable> T maximum(T x,T y,T z)
{
T max;
if(y.CompareTo(max)>0)
max=y;
if(z.CompareTo(max)>0)
max=z;
return max;
}
public static void main(String args[])
{
System.out.println(“maximum(2,5,4)=”+maximum(2,5,4));
System.out.println(“maximum(10.5,5.6,7.3)=”+maximum(10.5,5.6,7.3));
System.out.println(“maximum(“pear”,”apple”,”mango”)=”+maximum(“pear”,”apple”,”mango”)
);
}
}
Output:
C:\javac maxdemo.java
C:\java maxdemo
maximum(2,5,4)=5
maximum(10.5,5.6,7.3)=10.5
maximum(“pear”,”apple”,”mango”)=pear
4.9 BOUNDED TYPES
Using the bounded types, we can create the generic class of specific derived datatypes.
Example:
If we want to create the genric class for only numbers(int,double,float,long),then we use the
bounded type”numbers”
Syntax for declaring bounded types:
class classname <T extends superclass>
{
}
Program
//boundedclassdemo.java
class boundedClass <T extends Number>
{
T a;
boundedClass(T a)
{
this.a = a;
}
T get()
{
return a;
}
}
class boundedclassdemo
{
● wait(): This method is inherited from Object class. This method makes current thread to
wait until another thread invokes the notify() or the notifyAll() for this object.
ADDITIONAL PROGRAMS
1.write the java program to create two threads named x and y.Thread x display the
number from 1 to 10.Thread y display the number from 11 to 20.
Program
threaddemo.java
class X extends Thread
{
Public void run()
{
int i;
for(i=1;i<=10;i++)
System.out.println(i);
}
class Y extends Thread
{
y.start();
}
}
Output:
C:\javac threaddemo.java
C:\java threaddemo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2.write a program to print numbers from 1 to 10 lone by line after every 10 seconds.
Program
threaddemo.java
class X extends Thread
{
Public void run()
{
for(i=1;i<=10;i++)
System.out.println(i);
Thread.sleep(10000);
}
}
class threaddemo
{
public static void main(String args[])
{
X x=new X();
x.start();
}
}
Output:
C:\javac threaddemo.java
C:\java threaddemo
1
2
3
4
5
6
7
8
9
10
CHAPTER V
color, fonts, and images – Basics of event handling – event handlers – adapter classes
Boxes.
Graphical User Interface (GUI) offers user interaction with these graphical components. The
graphical components include text box, buttons, labels, radio buttons, list items and so on. We
need to import java.net package for using these components. These classes are arranged in
hierarchical manner which is recognized as AWT hierarchy. The hierarchy component classes are,
i) Component
A component is an object having a graphical representation that can be displayed on the screen
and that can interact with the user. The Component class is the abstract superclass of all user
interface elements that are displayed on the screen. A Component object remembers current text
font, foreground and background color.
Examples: buttons, checkboxes, and scrollbars
ii) Container
The Container class is the subclass of Component. The container object is a component that can
contain other AWT components. It is responsible for managing the layout and placement of
graphical components in the container.
iii) Window
The class Window is a top level window with no border and no menu bar. The default layout for
a window is Border Layout. It decides the layout of the window.
iv) Panel
The class Panel is the derived from the container class. So it is a simplest container class. It
provides space in which an application can attach any other component, including other panels. It
is just similar to window without any border and without any menu bar, title bar.
v) Frame
A Frame is a top-level window with a title and a border. It supports the common window events
such as window open, close, activate and deactivate.
vi) Dialog
A Dialog is a top-level window with a title and a border that is typically used to take some form
of input from the user.
vii) Canvas
A Canvas component represents a blank rectangular area of the screen onto which the
application can draw or from which the application can trap input events from the user. An
application must subclass the Canvas class in order to get useful functionality such as creating a
custom component.
5.1.1 FRAMES
A Frame is a top-level window with a title and a border. Frame encapsulates window. It and has
a title bar, menu bar, borders, and resizing corners. In Java, the Frame is a standard window.
The Frame can be displayed using the Frame class. The Frames has standard minimize, maximize
and close buttons.
Frame Constructor
● Frame()
Constructs a new instance of Frame that is initially invisible
● Frame(String title)
This creates the new instance of frame which has some title.
Methods of Frame class
Methods Description
String getTitle() Gets the title of the frame.
void Sets the background color of this window.
setBackground(Color bgColor)
void Sets whether this frame is resizable by the user.
setResizable(boolean resizable)
5.2 COMPONENTS
A component is an object with a graphical representation that can be displayed on the screen and
that can interact with the user. There are various graphical components that can be placed on the
frame.
Various components for designing user interfaces are,
1. Label
2. Buttons
3. Canvas
4. Scroll bars
5. Text Components
6. Checkbox
7. Choices
8. List Panels
9. Dialogs
i) LABELS:
Labels are the components which hold the text. They allow us to add a text description to a point
on the application. The Label can be Left aligned, right aligned or it can be centered.
Syntax:
Label labelname = new Label (String);
Label labelname = new Label (String, Label.style);
Example:
Label labelname = new Label ("This is the label text", Label.CENTER);
The above declaration makes the text centered.
Program:
//FrameDemo.java
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame fr=new Frame(“Java AWT Frame”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Label L1=new Label(“WELCOME”);
fr.add(L1);
}
}
Output:
javac FrameDemo.java
java FrameDemo
ii) BUTTONS
Buttons are called as push buttons. This component contains a text (or a label) .It generates an
event when that label is pressed.
Syntax:
Button buttonname = new Button (label/text);
Button buttonname[] = new Button[size];;
Program:
//ButtonDemo.java
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame fr=new Frame(“Button Example”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Buttton b1 =new Button(“click Here”);
fr.add(b1);
}
}
Output:
javac ButtonDemo.java
java ButtonDemo
iii) CANVAS
Canvas is a special area created on the frame. Canvas is a blank rectangular area which is used for
drawing the graphical components such as oval, rectangle, line and so on.
Syntax:
Canvas Canvasname = new Canvas();
Methods Description
void setSize(intwidth, int height) This method sets the size of the canvas for given width
and height.
void setBackground(Color c) Sets the background color of the canvas.
void setForeground(Color c) Sets method sets the color of the text.
Program:
// CanvasDemo.java
import java.awt.*;
class CanvasDemo
{
public static void main(String[] args)
{
Frame fr=new Frame(“Canvas Example”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Canvas c1 = new Canvas();
c1.setSize(100,100);
c1.setBackground (Color.GRAY);
fr.add(c1);
}
}
Output:
javac CanvasDemo.java
java CanvasDemo
iv) SCROLLBARS:
Scrollbar can be represented by the slider widgets. There are two styles of scrollbars . They are,
● Horizontal scrollbar
● Vertical scrollbar.
Syntax:
Scrollbar obj= new Scrollbar(Scrollbar.style);
Program:
//ScrollbarDemo.java
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame fr=new Frame(“Scrollbar Example”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Scrollbar s=new Scrollbar(Scrollbar.Vertical);
fr.add(s);
}
}
Output:
javac ScrollbarDemo.java
java ScrollbarDemo
java TextFieldDemo
Text Area
The Text Area is used to handle multi-line text.
Syntax
TextAre area= new TextArea(int n, int m);
where n is the number of lines and m is the number of characters.
Program:
//TextAreaDemo.java
import java.awt.*;
class TextAreaDemo
{
public static void main(String args[])
{
Frame f= new Frame("TextArea Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
TextArea area=new TextArea("Welcome to javatpoint");
f.add(area);
}
}
Output:
javac TextAreaDemo.java
java TextAreaDemo
v) CHECK BOX:
A checkbox is again a label which is displayed as a pushbutton. This pushbutton can either be
checked or unchecked. Therefore, the state of the checkbox is either true or false.
Syntax
Checkbox checkboxname = new Checkbox();
Checkbox checkboxname = new Checkbox(String);
Program:
//CheckboxDemo.java
import java.awt.*;
class CheckboxDemo
{
public static void main(String args[])
{
Frame f= new Frame("Checkbox Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
Checkbox box1 = new Checkbox("C++");
Checkbox box2 = new Checkbox("Java", true);
f.add(box1);
f.add(box2);
}
}
Output:
javac CheckboxDemo.java
vii) CHOICES:
Choice class is used to show popup menu of choices. Choice selected by user is shown on the top
of the menu.
Syntax
Choice choicename = new Choice();
Program:
//ChoiceDemo.java
import java.awt.*;
class ChoiceDemo
{
public static void main(String args[])
{
Frame f= new Frame("Choice Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
Choice c=new Choice();
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
}
}
Output:
javac ChoiceDemo.java.
java ChoiceDemo
java ListDemo
Program:
//LineDemo.java
import java.awt.*;
class LineDemo extends Canvas
{
LineDemo()
{
setSize(100,100);
setBackground (Color.WHITE);
}
public static void main(String[] args)
{
Frame fr=new Frame();
fr.setSize(300,300);
fr.setVisible(true);
LineDemo L1=new LineDemo();
fr.add(L1);
}
public void paint( Grpahics g)
{
g.drawLine(0,0,200,100);
g.drawLine(0,100,100,0);
}
}
Output:
javac LineDemo.java.
java LineDemo
5.3.2 RECTANGLES
In Java, we can draw two type of rectangles:
● Normal rectangle
● Rectangle with round corners.
Syntax
void drawRect(int top,int left,int width,int height)
void drawRoundRect(int top, int left,int width,int height, int xdimeter, int ydimeter)
void fillRect(int top, int left, int width,int height)
void fillRound(int top,int left, int width, int height, int xdiameter, int ydiameter)
Example: g.drawRect (20 , 20 , 50 , 30 )
Figure Rectangle
Program:
// RectangleDemo.java
import java.awt.*;
class RectangleDemo extends Canvas
{
RectangleDemo()
{
setSize(100,100);
setBackground (Color.WHITE);
}
public static void main(String[] args)
{
Frame fr=new Frame();
fr.setSize(300,300);
fr.setVisible(true);
RectangleDemo r1=new RectangleDemo();
fr.add(r1);
}
public void paint( Grpahics g)
{
g.drawRect(10,10,50,50);
g.drawRoundRect(70,30,50,30,10,10);
}
}
Output:
javac RectangleDemo.java.
java RectangleDemo
5.3.3 OVAL
drawOval()method can be used to draw ellipses or circles.
Syntax
drawOval( int top, int left, int width, int height)
fillOval(int top, int left, int width, int height)
Figure Ellipse
Program:
// ovalDemo.java
import java.awt.*;
class ovalDemo extends Canvas
{
ovalDemo()
{
setSize(100,100);
setBackground (Color.WHITE);
}
public static void main(String[] args)
{
Frame fr=new Frame();
fr.setSize(300,300);
fr.setVisible(true);
ovalDemo L1=new ovalDemo();
fr.add(L1);
}
public void paint( Grpahics g)
{
g.drawOval(10,10,50,50);
g.fillOval(200,10,70,100);
}
}
Output:
javac ovalDemo.java.
java ovalDemo
5.3.4 ARCS
An arc can be drawn using the drawArc () method.
Synatx:
void drawArc (int top, int left, int width, int height, int angle1, int angle2)
void fillArc (int top, int left, int width, int height, int angle1, int angle2)
where,
angle1 is the starting angle of the arc (in degrees)
angle2 is the number of degrees (angular distance) around the arc (in degrees)
Example:
fillArc(20,20,100,100,180,180);
drawArc(140,20,100,100,100,0,90);
fillArc(20,140,100,100,360,270);
drawArc(140,140,100,100,180,270);
Program:
// ArcDemo.java
import java.awt.*;
class ArcDemo extends Canvas
{
ArcDemo()
{
setSize(100,100);
setBackground (Color.WHITE);
}
public static void main(String[] args)
{
Frame fr=new Frame();
fr.setSize(300,300);
fr.setVisible(true);
ArcDemo L1=new ArcDemo ();
fr.add(L1);
}
public void paint( Grpahics g)
{
g.fillArc(20,20,100,100,180,180);
g.drawArc(140,20,100,100,100,0,90);
}
}
Output:
javac ArcDemo.java.
java ArcDemo
5.3.5 POLYGANS
A polygon is a closed figure with many lines joined one to another. The ending point of one line
is the starting point to another line and finally the last point is joins with the first point.
Syntax
drawPolygon(xpoints, ypoints, num);
Where,
● num represents the count of points
● xpoints represents the array of x-coordinates.
● ypoints represents the array of y-coordinates.
Example:
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
Program:
// polygonDemo.java
import java.awt.*;
class polygonDemo extends Canvas
{
polygonDemo()
{
setSize(100,100);
setBackground (Color.WHITE);
}
public static void main(String[] args)
{
Frame fr=new Frame();
fr.setSize(300,300);
fr.setVisible(true);
polygonDemo L1=new polygonDemo();
fr.add(L1);
}
public void paint( Grpahics g)
{
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
}
}
Output:
javac polygonDemo.java.
java polygonDemo
5.4 APPLET
Applets are small Java applications that can be accessed on an Internet server, transported over
Internet, and can be automatically installed and run as a part of a web document.
Applet is a predefined class in java.applet package used to design distributed application. It is a
client side technology. Applets are run on web browser.
Advantage of Applet
● Applets are supported by most web browsers.
● Applets works on client side so less response time.
● Secured: No access to the local machine and can only access the server it came from.
● Easy to develop applet, just extends applet class.
● To run applets, it requires the Java plug-in at client side.
● Android, do not run Java applets.
● Some applets require a specific JRE. If it required new JRE then it takes more time to
download new JRE.
5.4.1LIFE CYCLE OF AN APPLET
Syntax
public void paint(Graphics g)
{
…..
}
4. Idle State –Stop ()
In this method the applet becomes temporarily inactive. An applet can come any number of times
into this method in its life cycle and can go back to the active state (paint() method). It is equivalent
to the blocked state of the thread.
Syntax
public void stop()
{
…..
}
{
}
public void paint(Graphics g)
{
g.setColor(Color.RED);
g.drawString("Hello World", 50, 100);
}
}
Output:
5.5.2. FONTS
The Font class provides a method of specifying and using fonts. The Font class constructor
constructs font objects using the font's name, style (PLAIN, BOLD, ITALIC, or BOLD +
ITALIC), and font size.
Class : Font
Syntax:
Font obj = new Font(fontname,fontstyle,fontsize);
Font Style
Constant Description
Font.BOLD It makes the font style bold.
Font.ITALIC It makes the font style Italic.
Font.PLAIN It makes the font style plain.
Example:
Font obj= new Font("Arial",Font.BOLD,18);
Methods:
Method Description
setFont() Set the font to string
String getFamily() Returns the family name of this Font.
int getStyle() Returns the style of this Font.
boolean isBold() Indicates whether or not this Font object's style is BOLD
boolean isItalic() Indicates whether or not this Font object's style is ITALIC.
boolean isPlain() Indicates whether or not this Font object's style is PLAIN.
static Font getFont(String nm) Returns a Font object fom the system properties list.
Program:
//fontdemo.java
import java.applet.*;
import java.awt.*;
/*
<APPLET CODE ="fontdemo" WIDTH=300 HEIGHT=200>
</APPLET>
*/
class fontdemo extends Applet
{
public void init()
{
Font f=new Font("Arial",Font.ITALIC,20);
setFont(f);
}
public void paint(Graphics g)
{
g.drawString(“Welcome to java”,4,20);
}
}
Output:
5.5.3 IMAGES
Applet is mostly used in games and animation. For this purpose image is required to be displayed.
The image can be displayed in applet using drawImage() method of Graphics class.
Class : Image
Syntax:
Image obj = getImage(URL u,String image);
Example:
Image obj = getImage (getDocumentBase(),”myimg.jpg);
Methods:
drawImage()
Program:
// imagedemo.java
/*
<APPLET CODE=JavaExampleImageUseInApplet.class WIDTH=520 HEIGHT=170
></APPLET>
*/
import java.awt.*;
import java.applet.*;
class imagedemo extends Applet
{
public void init()
{
Image img = getImage(getDocumentBase(),"Koala.jpg");
}
public void paint(Graphics gr)
{
gr.drawImage(img,45,15,this);
}
}
Output:
5. 6 EVENT HANDLING
Event: Change in the state of an object is known as event i.e. event describes the change in state
of source. Events are generated as result of user interaction with the graphical user interface
components. For example, clicking on a button, moving the mouse, entering a character through
keyboard, selecting an item from list, scrolling the page are the activities that causes an event to
happen.
Event Handling
Event Handling is the mechanism that controls the event and decides what should happen if an
event occurs. This mechanism has the code which is known as event handler that is executed when
an event occurs.
Delegation Event Model
Java Uses the Delegation Event Model to handle the events. This model defines the standard
mechanism to generate and handle the events.
● Events : An event is a change in state of an object.
● Events Source : Event source is an object that generates an event.
● Listeners : A listener is an object that listens to the event. A listener gets notified when
an event occurs.
Steps involved in event handling
● The User clicks the button and the event is generated.
● Now the object of concerned event class is created automatically and information about the
source and the event get populated with in same object.
● Event object is forwarded to the method of registered listener class.
● The method is now get executed and returns.
Methods
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
ix) MouseListener
This interface deals with five of the mouse events.
Methods
void mouseClicked(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
x) MouseMotionListener
This interface deals with two of the mouse events.
Methods
void mouseMoved(MouseEvent me)
void mouseDragged(MouseEvent me)
xi) MouseWheelListener
This interface deals with the mouse wheel event.
Methods
void mouseWheelMoved(MouseWheelEvent mwe)
xii) TextListener
This interface deals with the text events.
Methods
void textValueChanged(TextEvent te)
xiii) WindowFocusListener
This interface deals with the window focus events.
Methods
void windowGainedFocus(WindowEvent we)
void windowLostFocus(WindowEvent we)
xiv) WindowListener
This interface deals with seven of the window events.
Methods
void windowActivated(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowIconified(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowOpened(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
Program:
//AdapterExample.java
import java.awt.*;
import java.awt.event.*;
import java.applet*;
/*
<APPLET CODE=JavaExampleImageUseInApplet.class WIDTH=520 HEIGHT=170
></APPLET>
*/
class AdapterExample
{
public void init()
{
addMouseListener(new adapter1(this);
addMouseMotionListener(new adapter2(this);
}
}
class adapter1 extends MouseAdpter
{
Test obj;
adapter1(Test obj)
{
this.obj=obj;
}
void mouseClicked(MouseEvent m)
{
Obj.showStatus(“Mouse clicked”);
}
}
class adapter2 extends MouseMotionAdpter
{
Test obj;
Adapter2(Test obj)
{
this.obj=obj;
}
void mouseMoved(MouseEvent m)
{
Obj.showStatus(“Mouse moved”);
}
}
Output:
javac AdapterExample.java
appletviwer AdapterExample.java
5.6.2ADAPTER CLASSES
An adapter class provides the default implementation of all methods in an event listener
interface. Adapter classes are very useful when you want to process only few of the events that are
handled by a particular event listener interface.
Adapter Class Listener Interface
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
WindowAdapter
WindowAdapter class implements the WindowListener interface and it contains 7 empty
implementation.
public interface windowListener
{
void windowActivated(WindowEvent we);
void windowDeactivated(WindowEvent we);
void windowIconified(WindowEvent we);
void windowDeiconified(WindowEvent we);
void windowOpened(WindowEvent we);
void windowClosed(WindowEvent we);
Program:
Refer Pageno:
5.6.3 ACTIONS
ActionEvent is generated when button is pressed, menu-item is selected, list-item is double
clicked. It implements ActionListener interface.
ActionListener
This interface defines the method actionPerformed() which is invoked when ActionEvent occurs.
Methods
void actionPerformed(ActionEvent ae)
Program:
// actiondemo.java
/*
The graphics programming in Java is supported by the AWT package. The AWT stands for
Abstract Window Toolkit.
The AWT is an API which contains a large number of classes which helps to include various
graphical components in the Java program, for creating user interfaces and for painting graphics
and images.
Event: Change in the state of an object is known as event i.e. event describes the change in state
of source. Events are generated as result of user interaction with the graphical user interface
components
Methods
void actionPerformed(ActionEvent ae)
ii) AdjustmentListener
This interface defines the method adjustmentValueChanged() which is invoked when
AdjustmentEvent occurs.
Methods
void adjustmentValueChanged(AdjustmentEvent ae)
iii) ComponentListener
This interface deals with the component events.
Methods
void componentResized(ComponentEvent ce)
void componentMoved(ComponentEvent ce)
void componentShown(ComponentEvent ce)
Methods
void itemStateChanged(ItemEvent ie)
vii) KeyListener
This interface deals with the key events.
Methods
void keyPressed(KeyEvent ke)
void keyReleased(KeyEvent ke)
void keyTyped(KeyEvent ke)
ix) MouseListener
This interface deals with five of the mouse events.
Methods
void mouseClicked(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
x) MouseMotionListener
This interface deals with two of the mouse events.
Methods
void mouseMoved(MouseEvent me)
void mouseDragged(MouseEvent me)
xi) MouseWheelListener
This interface deals with the mouse wheel event.
Methods
void mouseWheelMoved(MouseWheelEvent mwe)
xii) TextListener
This interface deals with the text events.
Methods
void textValueChanged(TextEvent te)
xiii) WindowFocusListener
Limitation of AWT
1. AWT supports limited number of GUI components.
2. Components of AWT are heavy weight components.
3. AWT occupies more memory space.
4. It is not portable.
5.9 LAYOUT MANAGEMENT
LayoutManagers are used to arrange components in a particular manner. LayoutManager is an
interface that is implemented by all the classes of layout managers. There are nine types of layout
managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
i) Java BorderLayout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
1. BorderLayout.NORTH
2. BorderLayout. SOUTH
3. BorderLayout.EAST
4. BorderLayout.WEST
5. BorderLayout.CENTER
Synatx:
BorderLayout(): creates a border layout but with no gaps between the components.
JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal and vertical
gaps between the components.
Program:
import java.awt.*;
import javax.swing.*;
public class BorderDemo
{
BorderDemo()
{
JFrame f =new JFrame();
JButton b1=new JButton("UP");;
JButton b2=new JButton("DOWN");;
JButton b3=new JButton("RIGHT");;
JButton b4=new JButton("LEFT");;
JButton b5=new JButton("MIDDLE");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
DEPARTMENT OF CSE Page 228
Object Oriented Programming 2019
{
BorderDemo b= new BorderDemo();
}
}
Output:
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and columns
but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the given
rows and columns alongwith given horizontal and vertical gaps.
program
import java.awt.*;
import javax.swing.*;
public class GridDemo
{
GridDmo()
{
Jframe f =new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.setLayout(new GridLayout(2,4));
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
GridDemo g= new GridDemo();
}
}
Output:
1. FlowLayout.LEFT
2. FlowLayout.RIGHT
3. FlowLayout.CENTER
4. FlowLayout.LEADING
5. FlowLayout.TRAILING
1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit horizontal
and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.
Program:
//FrameDemo.java
import java.awt.*;
class FrameDemo
{
public static void main(String[] args)
{
Frame fr=new Frame(“Java AWT Frame”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
Label L1=new Label(“WELCOME”);
fr.add(L1);
}
}
Output:
javac FrameDemo.java
java FrameDemo
1. BoxLayout.X_AXIS
2. BoxLayout.Y_AXIS
3. BoxLayout.LINE_AXIS
4. BoxLayout.PAGE_AXIS
BoxLayout(Container c, int axis): creates a box layout that arranges the components with the given
axis.
v) Java CardLayout
The CardLayout class manages the components in such a manner that only one component is
visible at a time. It treats each component as a card that is why it is known as CardLayout.
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical
gap.
● public void next(Container parent): is used to flip to the next card of the given container.
● public void previous(Container parent): is used to flip to the previous card of the given
container.
● public void first(Container parent): is used to flip to the first card of the given container.
● public void last(Container parent): is used to flip to the last card of the given container.
● public void show(Container parent, String name): is used to flip to the specified card
with the given name.
Program:
public class CardDemo extends JFrame implements ActionListener
{
CardDemo()
DEPARTMENT OF CSE Page 232
Object Oriented Programming 2019
{
Container c=getContentPane();
CardLayout card =new CardLayout(40,30);
c.setLayout(card);
JButton b1=new JButton("Rose");
JButton b2=new JButton("Jasmine");
JButton b3=new JButton("Lilly");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);
c.add("b",b2);
c.add("c",b3);
}
public void actionPerformed(ActionEvent e)
{
card.next(c);
}
public static void main(String[] args)
{
CardDemo cl=new CardDemo();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
gbc.gridwidth = 2;
this.add(new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
vii) GroupLayout
GroupLayout groups its components and places them in a Container hierarchically. The
grouping is done by instances of the Group class. Group is an abstract class and two concrete
classes which implement this Group class are SequentialGroup and ParallelGroup.
SequentialGroup positions its child sequentially one after another where as ParallelGroup aligns
its child on top of each other.
The GroupLayout class provides methods such as createParallelGroup() and
createSequentialGroup() to create groups.
Program:
import java.awt.Container;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import static javax.swing.GroupLayout.Alignment.*;
public class GroupE2
{
public static void main(String[] args)
{
JFrame frame = new JFrame("GroupLayoutExample");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Container myPanel = frame.getContentPane();
GroupLayout groupLayout = new GroupLayout(myPanel);
groupLayout.setAutoCreateGaps(true);
groupLayout.setAutoCreateContainerGaps(true);
myPanel.setLayout(groupLayout);
JButton b1 = new JButton("Button One");
JButton b2 = new JButton("Button Two");
JButton b3 = new JButton("Button Three");
groupLayout.setHorizontalGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(LEADING).addComponent(b1).addComponent(b3
)) .addGroup(groupLayout.createParallelGroup(TRAILING).addComponent(b2)));
groupLayout.setVerticalGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(BASELINE).addComponent(b1).addComponent(b
2)).addGroup(groupLayout.createParallelGroup(BASELINE).addComponent(b3)));
frame.pack();
frame.setVisible(true);
}
}
Output:
f.add(t1);
f.add(t2);
}
}
Output
javac TextFieldDemo.java
java TextFieldDemo
Program:
//TextAreaDemo.java
import java.awt.*;
import java.swing.*;
class TextAreaDemo
{
public static void main(String args[])
{
JFrame f= new JFrame("TextArea Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
JTextArea area=new JTextArea("Welcome to javatpoint");
f.add(area);
}
}
Output:
javac TextAreaDemo.java
java TextAreaDemo
DEPARTMENT OF CSE Page 238
Object Oriented Programming 2019
5.10.3 BUTTONS
Buttons are called as push buttons. This component contains a text (or a label) .It generates an
event when that label is pressed.
Syntax:
JButton buttonname = new JButton (label/text);
jButton buttonname[] = new JButton[size];;
Program:
//ButtonDemo.java
import java.awt.*;
import java.swing.*;
class FrameDemo
{
public static void main(String[] args)
{
JFrame fr=new JFrame(“Button Example”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
JButtton b1 =new JButton(“click Here”);
fr.add(b1);
}
}
Output:
javac ButtonDemo.java
java ButtonDemo
5.10.6 SCROLLBARS:
JScrollbar can be represented by the slider widgets. There are two styles of scrollbars . They are,
● Horizontal scrollbar
● Vertical scrollbar.
Syntax:
JScrollbar obj= new Scrollbar(Scrollbar.style);
Program:
//ScrollbarDemo.java
import java.awt.*;
import java.swing.*;
class ScrollbarDemo
{
public static void main(String[] args)
{
JFrame fr=new JFrame(“Scrollbar Example”);
fr.setSize(300,300);
fr.setVisible(true);
fr.setLayout(new FlowLayout());
JScrollbar s=new JScrollbar(Scrollbar.Vertical);
fr.add(s);
}
}
Output:
javac ScrollbarDemo.java
java ScrollbarDemo
5.10.7 CHOICES:
Choice class is used to show popup menu of choices. Choice selected by user is shown on the top
of the menu.
Syntax
JChoice choicename = new JChoice();
Program:
//ChoiceDemo.java
import java.awt.*;
import java.swing.*;
class ChoiceDemo
{
public static void main(String args[])
{
JFrame f= new JFrame("Choice Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
JChoice c=new JChoice();
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
c.add("Item 4");
c.add("Item 5");
f.add(c);
}
}
Output:
javac ChoiceDemo.java.
java ChoiceDemo
5.10.8 LIST :
List is a collection of many items. By double clicking the desired item we can select it. It is similar
to the Choice component, except it shows multiple items at a time and user is allowed to select
either one or multiple items at a time
Syntax
JList listname =new JList();
Program:
//ListDemo.java
import java.awt.*;
import java.swing.*;
class ListDemo
{
public static void main(String args[])
{
JFrame f= new JFrame("List Example");
f.setSize(400,400);
f.setLayout(new FlowLayout());
f.setVisible(true);
JList L1=new JList(5);
L1.add("Item 1");
L1.add("Item 2");
L1.add("Item 3");
L1.add("Item 4");
L1.add("Item 5");
f.add(L1);
}
}
Output:
javac ListDemo.java.
java ListDemo
5.10. 9 JWINDOW
The JWindow class is used to create a window which does not have any toolbar, border or window
management buttons. This type of window is usually used to display messages like welcome
messages, Copyright information, etc. Commonly used Constructors:
Constructor Description
JWindow() Creates a window with no specified
owner.
JWindow(Frame owner) Creates a window with the specified
owner frame.
Program:
import java.awt.*;
import javax.swing.*;
public class Message
{
public static void displayMessage(int timeDuration)
{
JWindow msg =new JWindow();
JPanel panel= (JPanel)msg.getContentPane();
int width = 350, height = 150;
int x = 50, y = 50;
msg.setBounds(x, y, width, height);
panel.setBorder(BorderFactory.createLineBorder(Color.red, 5));
msg.setVisible(true);
}
public static void main(String args[])
{
displayMessage(8000);
System.exit(0);
}
Output:
Constructor Description
JMenu() Constructs a new JMenu with no text.
JMenu(Action a) Constructs a menu whose properties are taken from the
Action supplied.
JMenu(String s) Constructs a new JMenu with the supplied string as its
text.
JMenu(String s, boolea Constructs a new JMenu with the supplied string as its
text and specified as a tear-off menu or not.
Constructor in JMenuBar:
Constructor Description
JMenuBar() Creates a new menu bar.
The following code creates two JMenu: File and Help, and add them to the JMenuBar:
menuBar.add(fileMenu);
menuBar.add(helpMenu);
The following code creates menu items to the menu:
JMenuItem newMenuItem = new JMenuItem("New");
The following code add menu items and a separator to the menu:
fileMenu.add(newMenuItem);
fileMenu.add(openMenuItem);
fileMenu.addSeparator();
fileMenu.add(exitMenuItem);
Program:
import javax.swing.*;
public class MenuExample
{
MenuExample()
{
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
Menu menu=new JMenu("File Menu");
JMenu submenu=new JMenu("Print");
JMenuItem i1=new JMenuItem("New");
JMenuItem i2=new JMenuItem("Open");
JMenuItem i3=new JMenuItem("Save");
JMenuItem i4=new JMenuItem("Save As");
JMenuItem i5=new JMenuItem("Print");
JMenuItem i6=new JMenuItem("Quick Print");
JMenuItem i7=new JMenuItem("Print Preview");
menu.add(i1);
DEPARTMENT OF CSE Page 247
Object Oriented Programming 2019
menu.add(i2);
menu.add(i3);
menu.add(i4);
submenu.add(i5);
submenu.add(i6);
submenu.add(i7);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
MenuExample m= new MenuExample();
}
}
Output:
5.10.11JAVA JDIALOG
❖ The JDialog control represents a top level window with a border and a title used to take
some form of input from the user.
❖ It inherits the Dialog class.
Program:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DialogExample
{
private static JDialog d;
DialogExample()
{
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
JButton b = new JButton ("Click Me");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
}
d.add( new JLabel ("Click this button to proceed"));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
Output:
5. What is a layout manager and what are different types of layout managers available in
java AWT?
A layout manager is an object that is used to organize components in a container. The different
layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout and
GridBagLayout.
6. What is an event and what are the models available for event handling?
An event is an event object that describes a state of change in a source. In other words, event occurs
when an action is generated, like pressing button, clicking mouse, selecting a list.
There are two types of models for handling events and they are:
a) event-inheritance model and
b) event-delegation model
about specific types of events. Second, it must implement methods to receive and process these
notifications.
1. Code a java program to implement the following: create four check boxes. The initial state of first box
should be in checked state. The status of each checkbox should be displayed. When we change the state of
a checkbox, the status should be displayed.
2. Recommend a Java swing with one button and adding it on the JFrame object inside the main() method.
3. i.Write a program to use setBounds() method.(8)
ii. Create a program use of BorderLayout (7)
4. Which method do you use to enable and disable components such as JButtons? What class is it defined
in? (15)
5. Write a program for a simple calculator using swing (15)
6. i. Infer JList and JComboBox with an example(7)
ii. Compare check boxes and radio buttons with an example(6)
ADDITIONAL PROGRAMS
1.write a java program to create arithmetic calculator.
import java.util.Scanner;
public class JavaProgram
{
public static void main(String args[])
{
float a, b, res;
char choice, ch;
Scanner scan = new Scanner(System.in);
do
{
System.out.print("1. Addition\n");
System.out.print("2. Subtraction\n");
System.out.print("3. Multiplication\n");
System.out.print("4. Division\n");
System.out.print("5. Exit\n\n");
System.out.print("Enter Your Choice : ");
choice = scan.next().charAt(0);
switch(choice)
{
case '1' :
System.out.print("Enter Two Number : ");
a = scan.nextFloat();
b = scan.nextFloat();
res = a + b;
System.out.print("Result = " + res);
break;
case '2' :
f.add(p);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b1)
{
s3 = tf.getText();
s4 = "0";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b2)
{
s3 = tf.getText();
s4 = "1";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b3)
{
s3 = tf.getText();
s4 = "2";
s5 = s3+s4;
tf.setText(s5);
}if(e.getSource()==b4)
{
s3 = tf.getText();
s4 = "3";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b5)
{
s3 = tf.getText();
s4 = "4";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b6)
{
s3 = tf.getText();
s4 = "5";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b7)
{
s3 = tf.getText();
s4 = "6";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b8)
{
s3 = tf.getText();
s4 = "7";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b9)
{
s3 = tf.getText();
s4 = "8";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b10)
{
s3 = tf.getText();
s4 = "9";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b11)
{
s1 = tf.getText();
tf.setText("");
c=1;
}
if(e.getSource()==b12)
{
s1 = tf.getText();
tf.setText("");
c=2;
}
if(e.getSource()==b13)
{
s1 = tf.getText();
tf.setText("");
c=3;
}
if(e.getSource()==b14)
{
s1 = tf.getText();
tf.setText("");
c=4;
}
if(e.getSource()==b15)
{
s1 = tf.getText();
tf.setText("");
c=5;
}
if(e.getSource()==b16)
{
s2 = tf.getText();
if(c==1)
{
n = Integer.parseInt(s1)+Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==2)
{
n = Integer.parseInt(s1)-Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==3)
{
n = Integer.parseInt(s1)*Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
if(c==4)
{
try
{
int p=Integer.parseInt(s2);
if(p!=0)
{
n = Integer.parseInt(s1)/Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
tf.setText("infinite");
}
catch(Exception i){}
}
if(c==5)
{
n = Integer.parseInt(s1)%Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
}
if(e.getSource()==b17)
{
tf.setText("");
}
}
public static void main(String[] abc)
{
calculator v = new calculator();
}
}
Output:
C:>javac calculator.java
C:>java calculator
{
addKeyListener(this); //use keyListener to monitor key events
}
public void keyPressed(KeyEvent k) // invoked when any key is pressed down
{
showStatus(“KeyPressed”);
}
public void keyReleased(KeyEvent k)
{
showStatus(“KeyRealesed”);
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}
Test1.html
<html>
<body>
<applet code=”Test.class” width=”400” height=”300”>
</applet>
</body>
</html>
Sample Output:
(OR)
b. Evaluate a Java program to find a smallest number in the given array by creating one dimensional
array and two dimensional array using new operator.
(OR)
b. Develop a Java program to implement the following Create four check boxes. The initial state of the
first box should be in checked state. The status of each check box should be displayed. When we change
the state of a check box, the status should be displayed and updated