0% found this document useful (0 votes)
198 views200 pages

OOP in Java Notes

Uploaded by

Abhay Dhakal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
198 views200 pages

OOP in Java Notes

Uploaded by

Abhay Dhakal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 200

Course Contents:

Unit 1: Introduction to Java [2 hours]

Definition, History of Java, The internet and Java‘s Place in IT, Applications and Applets,
Java Virtual Machine, Byte Code – not an executable code, Procedure-oriented vs. Object
Oriented programming, Compiling and Running a Simple Program, Setting up your
Computer for Java Environment, Writing a Program, Compiling, Interpreting and
Running the Program, Handling common errors.

Unit 2: Tokens, Expressions and Control Structures [5 hours]

Primitive Data Types: Integers, Floating-Point types, Characters, Booleans, User-Defined


Data Types, Declarations, Constants, Identifiers, Literals, Type Conversion and Casting,
Variables: Variable Definition and Assignment, Default Variable Initializations:
Command Line Arguments, Arrays of Primitive Data Types, Comment Syntax, Garbage
Collection, Expressions.

Using Operators: Arithmetic, Bitwise, Relational, Logical, Assignment, Conditional,


Shift, Ternary, Auto-increment and auto-decrement: Using control statements (Branching:
if, switch; Looping: while, do-while, for; Jumping statements: break, continue and
return).

Unit 3: Object Oriented Programming Concepts [9 hours]

Fundamentals of Classes: A simple class, Creating Class Instances, Adding Methods to a


class, Calling functions/Methods; Abstraction, Encapsulation, Using ‗this‘ keyword,
Constructors, Default constructors, parameterized constructors, More on Methods:
passing by value, by reference, access control, methods that return values, polymorphism
and method overloading, recursion; Nested and inner classes.

Unit 4: Inheritance and Packaging [3 hours]

Inheritance: Using ‗extends‘ keyword, Sub classes and Superclasses, super keyword
usage, Overriding methods, Dynamic Method Dispatch; The object class, Abstract and
final classes.

Packages: Defining a package, importing a Package: Access control; Interface,


Implementing and applying interface.

Unit 5: Handling Error/Exceptions [2 hours]

Basic Exceptions, Proper use of Exceptions, User Defined Exceptions, Catching


Exceptions: try, catch; Throwing and re-throwing: throw, throws; Cleaning up using the
finally clause.

Unit 6: Handling Strings [2 hours]

Creation, Concatenation and Conversion of a string, Changing Case, Character


Extraction, String Comparison, Searching Strings, Modifying Strings, String buffer.

Unit 7: Threads [3 hours]

Create/Instantiate/Start New Threads: Extending java.lang.Thread, Implementing


java.lang.Runnable interface; Understand Thread Execution, Thread Priorities,
Synchronization, Inter-Thread Communication, Deadlock.

Unit 8: I/O and Streams [2 hours]

Java.io package, Files and directories, streams: Byte streams and character
streams:Reading/Writing console Input/Output, Reading and Writing Files, The
serialization Interface, Serialization and Deserialization.

Unit 9: Understanding Core Packages [3 hours]

Using java.lang Package: java.lang.Math, Wrapper classes and associated methods


(Number, Double, Float; Integer, Byte; Short, Long; Character, Boolean); Using java.util
package: Core classes (Vector, Stack, Dictionary, Hashtable, Enumerations, Random
Number Generation).

Unit 10: Holding Collection of Data [3 hours]

Arrays and Collection Classes/Interface, Map/List/Set implementation: Map Interface,


List Interface, Set Interface.

Collection Classes: Array List, Linked List, Hash Set and Tree set; Accessing
Collections/Use of an Iterator, Comparator.
Unit 11: Java Applications [8 hours]

About AWT and Swing, About JFrame (a top level window in swing), swing components
(JLabel, About text components like JTextField, JButton, Event Handling in Swing
Applications, Layout Management using FlowLayout, Border Layout, Grid Layout,
Using JPanel, Choice Components like JCheckBox, JRadioButton, Borders Components,
JComboBox and its events, JList and its events with MVC patterns, Key and Mouse
Event Handling, Menus in Swing, JTextArea, Dialog boxes in Swing, JTable for
Displaying data in tabular form, MDI using JDesktopPane and JInternalFrame, Using
IDE like netbeans: JBuilder for building java applications using Drag and Drop), Adapter
classes.

Unit 12: Introduction to Java Applets [1 hour]

Definition, applet lifecycle methods, build a simple applet, using applet viewer, adding
controls: animation concepts.

Unit 13: Database Programming using JDBC [2 hours]

Using Connection, Statement and ResultSet interfaces for manipulating data with the
database.

Text Books:

1. Java: How to program, Deitiel & Deitel, 9t Edition.


2. Java: The Complete Reference, Herbert Schildt, 7th edition.
Unit 1: Introduction to Java [2 hours]
Definition, History of Java, The internet and Java‟s Place in IT, Applications and
Applets, Java Virtual Machine, Byte Code – not an executable code, Procedure-oriented
vs. Object Oriented programming, Compiling and Running a Simple Program, Setting up
your Computer for Java Environment, Writing a Program, Compiling, Interpreting and
Running the Program, Handling common errors.

Basic Concept of OOP Paradigm:

The major objective of OOP is to eliminate some of the flaws encountered in the
procedural approach (in C- programming). OOP treat data as a critical element in the
program development. It ties data more closely to the functions that operate on it and
protects it from unintentional modification by other functions. OOP allows us to
decompose a problem into a number of entities called objects and build data and
functions/methods. The combination of data and functions/methods make up an object as
seen in figure;

Figure 1: Object = Data + Functions/Methods

Definition:

Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems'
Java platform (Java 1.0 [J2SE]).
The latest release of the Java Standard Edition is Java SE 8. With the advancement of
Java and its widespread popularity, multiple configurations were built to suit various
types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile
Applications.

The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java
is guaranteed to be Write Once, Run Anywhere.

Java is:
Object Oriented: In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
Platform Independent: Unlike many other programming languages including C and
C++, when Java is compiled, it is not compiled into platform specific machine, rather
into platform independent byte code. This byte code is distributed over the web and
interpreted by the Virtual Machine (JVM) on whichever platform it is being run on.
Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP
Java, it would be easy to master.
Secure: With Java's secure feature it enables to develop virus-free, tamper-free
(unauthorized access) systems. Authentication techniques are based on public-key
encryption.
Architecture-neutral: Java compiler generates an architecture-neutral object file format,
which makes the compiled code executable on many processors, with the presence of
Java runtime system.
Portable: Being architecture-neutral and having no implementation dependent aspects of
the specification makes Java portable.
Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
Multithreaded: With Java's multithreaded feature it is possible to write programs that
can perform many tasks simultaneously. This design feature allows the developers to
construct interactive applications that can run smoothly.
Interpreted: Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and light-weight process.
High Performance: With the use of Just-In-Time compilers, Java enables high
performance.
Distributed: Java is designed for the distributed environment of the internet.
Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
History of Java:
James Gosling initiated Java language project in June 1991 for use in one of his many set-
top box projects. The language, initially called ‗Oak‘ after an oak tree that stood outside
Gosling's office, also went by the name ‗Green‘ and ended up later being renamed as
Java, from a list of random words.

Sun released the first public implementation as Java 1.0 in 1995. It promised Write
Once, Run Anywhere (WORA), providing no-cost run-times on popular platforms.

On 13 November, 2006, Sun released much of Java as free and open source software
under the terms of the GNU General Public License (GPL).

On 8 May, 2007, Sun finished the process, making all of Java's core code free and open-
source, aside from a small portion of code to which Sun did not hold the copyright.

The internet and Java’s place on it:

Java was developed by Sun Microsystems and is a multithreaded object-oriented


programming language. It is a new programming language with complete functionality
like that of C++. At this point, Java's place is on the World Wide Web. Probably the most
important things that Java brings to the Web are the capacity for more interactivity on the
Internet through multimedia and animation. In order to view Java applets on the Net, you
must have a Java-compliant browser. The Internet Explorer (as of version 3.0) and
Netscape Navigator (as of version 2.0) are two prominent browsers on the Net that
support Java.

Application and Applet:

A Java program can be classified into two types, one is an Application and another is an
Applet.

Application:

1. An application is a stand-alone java program that runs with the support of a virtual
machine in a client or server-side.
2. A java application is designed to perform a specific function to run on any Java-
compatible virtual machine regardless of the computer architecture.
3. An application is either executed for the user or for some other application program.
4. Examples of java applications include database programs, development tools, word
processors, text and image editing programs, spreadsheets, web browsers, etc.
Example:

public class Demo {


public static void main(String args[]) {
System.out.println(“Welcome to Third Semester”);
}
}
Applet:

1. An applet is specifically designed to be executed within an HTML web document


using an external API.
2. They are basically small programs, more like the web version of an application that
requires a Java plugin to run on the client browser.
3. Applets run on the client-side and are generally used for internet computing.
4. When we see an HTML page with an applet in a Java-enabled web browser, the
applet code gets transferred to the system and is finally run by the Java-enabled
virtual machine on the browser.
Example:

import java.awt.*;
import java.applet.*;
public class AppletDemo extends Applet{
public void paint(Graphics g) {
g.drawString("Welcome to TutorialsPoint", 50, 50);
}
}
/* <applet code="AppletDemo.class" width="300" height="300">
<applet>*/

Java Technology:

1. JDK (Java Development Kit): Necessary for the development of Java


Applications. JDK bundle includes Java Compiler and Interpreter.
a. Java Compiler : It is a javac tool/command that reads the source code and
change the source code into byte code.
b. Java Interpreter : It is java command to interpret the .class file that have
been compiled by java compiler, which is responsible for running the java
application.
2. JRE (Java Runtime Environment) : It includes JVM, core libraries and other
additional components to run java application.
3. JVM (Java Virtual Machine): JVM is a program that runs pre-compiled java
programs i.e. bytecode file and produces output.

JDK
JRE, Jar, Debugging tools, etc.

JRE
Java, libraries, etc

JVM

JIT(Just In Time Compiler)


Optimization
Features of Java:

Java is Simple, Object-Oriented, Distributed, Interpreted, Robust, Secure,


Architecture-neutral, Portable, High-performance, Multi-threaded and Dynamic
Language.

Overview of Java Language:

 Implementing a Java program

 Creating the program

 Compiling the program

 Running the program

Creating the program

class Test

public static void main(String args[])

System.out.print(―Hello!‖);

System.out.println(―Welcome to the world of Java!‖);

System.out.println(―Let us learn Java‖);

- Save as: Test.java


- What is the output? (Guess)

JDK (Java Development Kit):

The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment
(JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation
generator (javadoc) and other tools needed in Java development.

Note: Installation of recent JDK for the full execution of Java Programs.

Setting Path in Java to run programs in command mode

 Select Start -> Computer -> System Properties -> Advanced system settings ->
Environment Variables -> System variables -> PATH. ...
 Prepend C:\Program Files\Java\jdk1.6.0_27\bin; to the beginning of the PATH
variable.
 Click OK three times.
OR
 In Command Mode:
 Go to the directory where the java programs are located.
 Then, set path=%path%;C:\Program Files\Java\ jdk1.6.0_27\bin.
 C:\Workspace> javac yourfilename.java(compilation)
 C:\Workspace> java yourfilename(Execution/Run)

Compiling the program:

Command -> Javac Test.java

(Move to the directory)

Running the Program:

 Java Test (Name of .class file)


 The output is:
Hello!Welcome to the world of Java
Let us learn Java

ByteCode:

 The key that allows Java to solve both the security and the portability problems is
that the output of a Java Compiler is not an executable code, rather it is a
bytecode.

 Bytecode is a highly optimized set of instructions designed to be executed by the


Java runtime system, which is called the Java Virtual Machine (JVM). It is an
interpreter for bytecode.

 In the Java programming language, all source code is first written in plain text
files ending with the .java extension. Those source files are then compiled into
.class files by the javac compiler. A .class file does not contain code that is native
to your processor; it instead contains bytecode—the language of the JVM.

 The Java VM is available on many different operating systems, therefore the same
.class files are capable of running on Microsoft Windows, the Solaris™ Operating
System (Solaris OS), Linux, or Mac OS.
Java Architecture:
Source Code

Java Compiler

Bytecode

Windows Linux Macintosh


interpreter[JVM] interpreter[JVM] interpreter[JVM]

Machine Code Machine Code Machine Code

Windows Computer Linux Computer Macintosh Computer

Figure 2: Implementation of Java Programs

Handling Common Errors:

Errors in the very beginning of programming in java can be at compiling time such as;
1. If environment is not set up properly.
2. If the name of a source file during compilation is provided incorrect.
3. If the name of a class file during execution provided wrong (This may happen
when we give the name of a class different from a file name).

Difference Between OOP and POP


Sno Key Object Oriented Programming Procedural Oriented
(OOP) Programming (POP)
1 Definition Object-oriented Programming is a On other hand Procedural Oriented
programming language that uses Programming is a programming
classes and objects to create models language that follows a step-by-
based on the real world step approach to break down a task
environment. In OOPs it makes it into a collection of variables and
easy to maintain and modify routines (or subroutines) through a
existing code as new objects are sequence of instructions. Each step
created inheriting characteristics is carried out in order in a
from existing ones. systematic manner so that a
computer can understand what to
do.

2 Approach In OOPs concept of objects and On other hand in case of POP the
classes is introduced and hence the the main program is divided into
program is divided into small small parts based on the functions
chunks called objects which are and is treated as separate program
instances of classes. for individual smaller program.

3 Access In OOPs access modifiers are On other hand no such modifiers


modifiers introduced namely as Private, are introduced in POP.
Public and Protected.

4 Security Due to abstraction in OOPs data On other hand POP is less secure
hiding is possible and hence it is as compare to OOPs.
more secure than POP.

5 Complexity In OOPs new data objects can be On other hand there is no simple
created easily from existing objects process to add data in POP at least
making object-oriented programs not without revising the whole
easy to modify program.
Unit 2: Tokens, Expressions and Control Structures [5 hours]
Primitive Data Types: Integers, Floating-Point types, Characters, Booleans, User-Defined
Data Types, Declarations, Constants, Identifiers, Literals, Type Conversion and Casting,
Variables: Variable Definition and Assignment, Default Variable Initializations:
Command Line Arguments, Arrays of Primitive Data Types, Comment Syntax, Garbage
Collection, Expressions.

Using Operators: Arithmetic, Bitwise, Relational, Logical, Assignment, Conditional,


Shift, Ternary, Auto-increment and auto-decrement.

Using control statements (Branching: if, switch; Looping: while, do-while, for; Jumping
statements: break, continue and return).

Primitive Data Types:

A primitive data type specifies the size and type of variable values, and it has no
additional methods.

There are eight primitive data types in Java:

Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 bytes Stores whole numbers from -32,768 to 32,767

int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal


digits

double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal


digits

boolean 1 bit Stores true or false values

char 2 bytes Stores a single character/letter or ASCII values, range 232767


to -32768
Example illustrating all above primitive data types:

public class primitivedatatypes {


public static void main(String[] args) {
byte b = 24;
short s = 5000;
int i = 50000;
long l = -12332252626L;
float f = 1234.56f;
double d = -42937737.9d;
boolean t = false;
char c = 'H';
String st = "Harendra";

System.out.println("The value of byte = " + b);


System.out.println("The value of short = " + s);
System.out.println("The value of int = " + i);
System.out.println("The value of long = " + l);
System.out.println("The value of float = " + f);
System.out.println("The value of double = " + d);
System.out.println("The value of boolean = " + t);
System.out.println("The value of char = " + c);
System.out.println("The value of string = " + st);
}
}

Output:

The value of byte = 24


The value of short = 5000
The value of int = 50000
The value of long = -12332252626
The value of float = 1234.56
The value of double = -4.29377379E7
The value of boolean = false
The value of char = H
The value of string = Harendra

User Defined Data Types:


User defined data types are those which are developed by programmers by making use of
appropriate features of the language.

User defined data types related variables allows us to store multiple values either of same
type or different type or both. This is a data type whose variable can hold more than one
value of dissimilar type, in java it is achieved using class concept.
Note: In java both derived and user defined data type combined name as reference data
type.

In C language, user defined data types can be developed by using struct, union, enum etc.
In java programming user defined datatype can be developed by using the features of
classes and interfaces.

Declarations of user defined data types


Example: class

class Student{ //user defined data type


public static void main(String[] args){
Student st=new Student();
}
}

Example: interface
interface StudentInterface{ //user defined data type
void DisplayName();
}
class Student implements StudentInterface{
void DisplayName(){
System.out.println(―My name is XYZ‖);
}
public static void main(String[] args){
Student st=new Student();
st. DisplayName();
}
}

Constants:
A constant is a variable whose value cannot change once it has been assigned. Java
doesn't have built-in support for constants.
A constant can make our program more easily read and understood by others. In addition,
a constant is cached by the JVM as well as our application, so using a constant can
improve performance.
To define a variable as a constant, we just need to add the keyword ―final‖ in front of the
variable declaration.
Syntax
final float pi = 3.14f;

Literals:

A literal is a source code representation of a fixed value. They are represented directly in
the code without any computation.
Literals can be assigned to any primitive type variable.
Example
byte a = 68;
char a = 'A'

Java Basic Syntax:

When we consider a Java program, it can be defined as a collection of objects that


communicate via invoking each other's methods. Let us now briefly look into what do
class, object, methods, and instance variables mean.

Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behavior such as wagging their tail, barking, eating. An object is an
instance of a class.
Class - A class can be defined as a template/blueprint that describes the behavior/state
that the object of its type supports.
Methods - A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are
executed.
Instance Variables - Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables.
Let us look at a simple code that will print the words Hello World.
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}

Let's look at how to save the file, compile, and run the program. Please follow the
subsequent steps:

Open notepad and add the code as above.


Save the file as: MyFirstJavaProgram.java.
 Open a command prompt window and go to the directory where you saved the
class. Assume it's C:\.
 Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. If
there are no errors in your code, the command prompt will take you to the next
line (Assumption : The path variable is set).

Now, type ' java MyFirstJavaProgram ' to run your program.


You will be able to see ' Hello World ' printed on the window.

C:\> javac MyFirstJavaProgram.java


C:\> java MyFirstJavaProgram
Hello World

Some rules for Java Programming Language;


About Java programs, it is very important to keep in mind the following points.
Case Sensitivity- Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.
Class Names - For all class names the first letter should be in Upper Case.
If several words are used to form a name of the class, each inner word's first letter
should be in Upper Case.
Example: class MyFirstJavaClass
Method Names - All method names should start with a Lower Case letter.
If several words are used to form the name of the method, then each inner word's
first letter should be in Upper Case.
Example: public void myMethodName()
Program File Name - Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is
case sensitive) and append '.java' to the end of the name (if the file name and the
class name do not match, your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should
be saved as 'MyFirstJavaProgram.java'
public static void main(String args[]) - Java program processing starts from the main()
method which is a mandatory part of every Java program.

Java Identifiers

All Java components require names. Names used for classes, variables, and methods are
called identifiers.
In Java, there are several points to remember about identifiers. They are as follows:
1. All identifiers should begin with a letter (A to Z or a to z), currency character ($)
or an underscore (_).
2. After the first character, identifiers can have any combination of characters.
3. A key word cannot be used as an identifier.
4. Most importantly, identifiers are case sensitive.
Examples of legal identifiers: age, $salary, _value, __1_value.
Examples of illegal identifiers: 123abc, -salary.
Java Modifiers

Like other languages, it is possible to modify classes, methods, etc., by using modifiers.
There are two categories of modifiers:
Access Modifiers: default, public , protected, private
Non-access Modifiers: final, abstract, strictfp
We will be looking into more details about modifiers in the next section.
Java Variables

Following are the types of variables in Java:


Local Variables
Class Variables (Static Variables)
Instance Variables (Non-static Variables)

Java Arrays

Arrays are objects that store multiple variables of the same type. However, an array itself
is an object on the heap. We will look into how to declare, construct, and initialize in the
upcoming chapters.

Command Line Argument

public static void main(String args[])

- args is declared as an array of strings known as string objects. Any arguments provided
in the command line at the time of execution are passed to the array args as its elements.

E.g.
class CommandLine{
public static void main(String args[ ]){
int count, i=0;
String str;
count=args.length;
System.out.println(“Number of arguments=“+count);
while(i<count){
str=args[i];
i=i+1;
System.out.println(i+”:”+”Java is”+str+”!\n”);
}
}
}
Input is called command line argument

Commandline: java CommandLine Simple Object Oriented Distributed Robust


Secure Portable Multithreaded Dynamic
Output: Can you guess the output??

Java Keywords

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

abstract assert boolean break


byte case catch char
class const continue default
do double else enum
extends final finally float
for goto if implements
import instanceof int interface
long native new package
private protected public return
short static strictfp super
switch synchronized this throw
throws transient try void
volatile while

Comments in Java

Java supports single-line and multi-line comments very similar to C and C++. All
characters available inside any comment are ignored by Java compiler.
public class MyFirstJavaProgram{
public static void main(String[] args){
// This is an example of single line comment
/* This is also an example of single line comment. */
System.out.println("Hello World");
}
}
Java Type Conversion and Casting
Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

 Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double

 Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte

Widening Casting

Widening casting is done automatically when passing a smaller size type to a larger size
type:

Example
public class casting {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}
Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses in front of
the value:

Example
class Main {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78


System.out.println(myInt); // Outputs 9
}
}
Variables in Java:
Variables are containers for storing data values.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by double
quotes
 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by
single quotes
 boolean - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Syntax
data_type variable = value;

Where type is one of Java's types (such as int or String), and variable is the name of the
variable (such as x or name). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

Example
String name=”harendra”;

int num=56;

System.out.println(name);

System.out.println(num);

num =34;//num is overridden with new value

System.out.println(num);

The general rules for constructing names for variables (unique identifiers) are:

 Names can contain letters, digits, underscores, and dollar signs


 Names must begin with a letter
 Names should start with a lowercase letter and it cannot contain whitespace
 Names can also begin with $ and _ (but we will not use it in this tutorial)
 Names are case sensitive ("myVar" and "myvar" are different variables)
 Reserved words (like Java keywords, such as int or boolean) cannot be used as
names.
Arrays of Primitive Data Types

An array is a collection of similar data types. Array is a container object that hold values
of homogenous type. It is also known as static data structure because size of an array
must be specified at the time of its declaration.

An array can be either primitive or reference type. It gets memory in heap area. Index of
array starts from zero to size-1.

Array Declaration

Syntax :

datatype[] identifier;
or
datatype identifier[];

Both are valid syntax for array declaration. But the former is more readable.

Example :

int[] arr;
char[] arr;
short[] arr;
long[] arr;
int[][] arr; //two dimensional array.

Initialization of Array

new operator is used to initialize an array.

Example :

int[] arr = new int[10]; //10 is the size of array.


or
int[] arr = {10,20,30,40,50};

Accessing array element

As mention ealier array index starts from 0. To access nth element of an array. Syntax;
arrayname[n-1];

Example : To access 4th element of a given array

int[] arr={10,20,30,40};
System.out.println("Element at 4th place"+arr[3]);

The above code will print the 4th element of array arr on console.

foreach or enhanced for loop

J2SE 5 introduces special type of for loop called enhanced for loop to access elements of
array. Using enhanced for loop you can access complete array sequentially without using
index of array. Let us see an example of enhanced for loop.

class Arraydemo
{
public static void main(String[] args)
{
int[] arr={10,20,30,40};
for(int x:arr)
{
System.out.println(x);
}
}
}

Implementation: One Dimensional Array


public class NumberSorting
{
public static void main(String[] args) {
int[] number = {55, 40, 80, 65, 71};
int n=number.length;
System.out.println("The given list is as shown below\n");
for(int i=0;i<n;i++)
{
System.out.println(" " + number[i]);
}
//Sorting begins from here
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
if(number[i]<number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
} //Sorting ends

System.out.println("The descending orderlist is shown below.");


for (int item : number) //use of enhanced for loop
{
System.out.println(" " + item);
}
System.out.println(" ");
}
}

Two dimensional array:


public class MulTable {
final static int ROWS = 20;
final static int COLUMNS = 20;
public static void main(String[] args) {
int product[][] = new int[ROWS][COLUMNS];
int row, column;
System.out.println("******MULTIPLICATION TABLE**********");
System.out.println(" ");
for(int i=10; i<ROWS; i++){
for(int j=10; j<COLUMNS; j++){
product[i][j]=i*j;
System.out.print(" " +product[i][j]);
}
System.out.println(" ");
}
}
}

Java Garbage Collection

In java, garbage means unreferenced objects.

Garbage Collection is process of reclaiming the runtime unused memory automatically. In


other words, it is a way to destroy the unused objects.

To do so, we were using free() function in C language and delete() in C++. But, in java it
is performed automatically. So, java provides better memory management.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the
unreferenced objects from heap memory.
o It is automatically done by the garbage collector (a part of JVM) so we don't
need to make extra efforts.

Expressions
Expressions are constructed from operands and operators. The operators of an
expression indicate which operations to apply to the operands. The order of
evaluation of operators in an expression is determined by
the precedence and associativity of the operators.

Operators in Java
Operator in Java is a symbol which is used to perform operations. For example: +, -, *, /
etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence

Operator Category Precedence


Type

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%


additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=


>>>=

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --


class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}

Output:
10
12
12
10

Java Unary Operator Example: ~ and !


class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}

Output:

-11
9
false
true

Java Arithmetic Operators

Java arithmatic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

Java Arithmetic Operator Example


class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}

Output:
15
5
50
2
0

Java Arithmetic Operator Example: Expression


class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}

Output:

21

Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.

Java Left Shift Operator Example


class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}

Output:

40
80
80
240

Java Right Shift Operator

The Java right shift operator >> is used to move left operands value to right by the
number of bits specified by the right operand.

Java Right Shift Operator Example


class OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}

Output:

2
5
2

Java Shift Operator Example: >> vs >>>


class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}

Output:

5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check second condition if first condition is false. It
checks second condition only if first one is true.

The bitwise & operator always checks both conditions whether first condition is true or
false.

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}
Output:
false
false

Java AND Operator Example: Logical && vs Bitwise &


class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}}

Output:

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check second condition if first condition is true. It checks
second condition only if first one is false.

The bitwise | operator always checks both conditions whether first condition is true or
false.

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}

Output:

true
true
true
10
true
11

Java Ternary Operator

Java Ternary operator is used as one liner replacement for if-then-else statement and used
a lot in Java programming. it is the only conditional operator which takes three operands.

Java Ternary Operator Example


class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}

Output:

Another Example:

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}

Output:

Java Assignment Operator

Java assignment operator is one of the most common operator. It is used to assign the
value on its right to the operand on its left.

Java Assignment Operator Example


class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}

Output:

14
16

Java Assignment Operator Example


class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}

Output:
13
9
18
9

Java Assignment Operator Example: Adding short


class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 becomes int
System.out.println(a);
}}

Output:

Compile time error

After type cast:

class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is becomes int converted to short
System.out.println(a);
}}

Output:
20

Control Statements:
Decision making and branching.
 If statement
Syntax:
 if(test expression){statement-block}
 If statement implemented in different forms:
 Simple if statement
 if(test expression){statement-block}
 If…….else statement
 if(test expression){statement-block}
 else{statement-block}
 Nested if statement
 if(test expression){
 if(condition){statement-block}
 statement-block}
 Else if ladder
 if(test expression){statement-block 1}
 else if(test expression){statement-block 2}
 else if(test expression){statement-block 3}
 else{default-statement-block}

 Switch statement
Syntax:
Switch(expression){
Case value-1:
Block-1
Break;
Case value-2:
Block-2
Break;
…………………..
…………………..
Default:
Default-block
Break;
}

Implementation:
import java.util.Scanner;

public class SwitchDemo {


public static void main(String[] args) {
int month;
String monthString;
System.out.println("Enter the born month");
Scanner input=new Scanner(System.in);
month=input.nextInt();
switch (month) {
case 1: monthString = "January"; break;
case 2: monthString = "February"; break;
case 3: monthString = "March"; break;
case 4: monthString = "April"; break;
case 5: monthString = "May"; break;
case 6: monthString = "June"; break;
case 7: monthString = "July"; break;
case 8: monthString = "August"; break;
case 9: monthString = "September"; break;
case 10: monthString = "October"; break;
case 11: monthString = "November"; break;
case 12: monthString = "December"; break;
default: monthString = "Invalid month"; break;
}
System.out.println("Your Born Month is"+monthString);
}
}

 Conditional operator statement


Syntax:
 Conditional expression?expression1:expression2
 Example: if else condition can also be used using ?: operator.
if(x==1){person=―male‖;}
else{person=―female‖;}
Conditional expression
person=(x==1)?‖male‖:‖female‖;

 Decision making and looping


o While statements

class WhileDemo {
public static void main(String[] args){
int count = 1;
while (count < 11){
System.out.println("Count is: " + count);
count++;
}
}
}

o Do while statements

Syntax:
do { statement(s) }
while (expression);
Example:
class DoWhileDemo {
public static void main(String[] args){
int count = 1;
do {
System.out.println("Count is: " + count);
count++;
} while (count < 11);
}
}
o For statement
class ForDemo {
public static void main(String[] args){
int i;
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
int length=numbers.length;
for (i=0;i< : numbers<length;i++) {
System.out.println("Count is: " + numbers[i]);
}
}
}

o Enhanced for loop


class EnhancedForDemo {
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}

Java Break

You have already seen the break statement used in an earlier chapter of this tutorial. It
was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

Example

for (int i = 0; i < 10; i++) {

if (i == 4) { //exits the whole loop on condition meet

break;

System.out.println(i);

Java Continue

The continue statement breaks one iteration (in the loop), if a specified condition occurs,
and continues with the next iteration in the loop.
This example skips the value of 4:

Example

for (int i = 0; i < 10; i++) {

if (i == 4) { //skips the single iteration

continue;

System.out.println(i);

Java return:

The return statement can also be used to jump out of a loop.

for (int i = 0; i < 10; i++) {


if (i == 4) {
return;
}
System.out.println(i);
}
Unit 3: Object Oriented Programming Concepts [9 hours]
Fundamentals of Classes: A simple class, Creating Class Instances, Adding Methods to a
class, Calling functions/Methods; Abstraction, Encapsulation, Using „this‟ keyword,
Constructors, Default constructors, parameterized constructors, More on Methods:
passing by value, by reference, access control, methods that return values, polymorphism
and method overloading, recursion; Nested and inner classes.

Fundamental of classes:
A class is a template for an object, and an object is an instance of a class. Because an
object is an instance of a class, the two words object and instance used interchangeably.
A class is declared by use of the class keyword. The classes that have been used up to
this point are actually very limited examples of its complete form. Classes can (and
usually do) get much more complex. A simplified general form of a class definition is
shown here:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
} // ...
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class
are called members of the class. In most classes, the instance variables are acted upon
and accessed by the methods defined for that class. Thus, as a general rule, it is the
methods that determine how a class‘ data can be used.
Variables defined within a class are called instance variables because each instance of
the class (that is, each object of the class) contains its own copy of these variables.
Thus, the data for one object is separate and unique from the data for another. All
methods have the same general form as main( ), which we have been using thus far.
However, most methods will not be specified as static or public. Notice that the general
form of a class does not specify a main( ) method. Java classes do not need to have a
main( ) method.

Defining a class:
Class classname [extends superclassname]{
[fields declarations;]
[method declarations;]
}
Field declarations:
Class Rectangle{
int length;
int width;
}
Method Declarations:
type methodname(parameter-list){
method-body;
}
void getData(int x, int y){
length=x;
width=y;
}
Creating objects:
Rectangle rect;
rect=new Rectangle();
Accessing class members:
rect.length=12;
rect.width=23;

Applications of Class, Objects and Methods


public class Rectangle {
int length, width; //declarations of variables
void getData(int x, int y)
{
length = x;
width = y;
}

int rectArea()
{
int area = length*width;
return area;
}
}

public class RectArea {


public static void main(String[] args) {
int area1, area2, len,bre;

//Using Variables only


Rectangle rect1= new Rectangle();
System.out.println("Enter length and breadth");
Scanner in = new Scanner(System.in);
len=in.nextInt();
bre=in.nextInt();
rect1.length=len;
rect1.width=bre;
area1=rect1.length*rect1.width;
System.out.println("The area is"+area1);

//Using Methods only


Rectangle rect2= new Rectangle();
rect2.getData(len,bre);
area2 = rect2.rectArea();
System.out.println("The area is "+area2);
}
}

Descriptions:
In the above example, we can see two different classes Rectangle and RectArea.
Rectangle has member variables (length and breadth of integer type) declared and
member functions getData() i.e. void type and rectArea() i.e. return type defined inside
Rectangle class.
Another class RectArea has a main method and inside main method the instances
(objects) of class Rectangle are created i.e. rect1 and rect2. Using these objects the
members are accessed from different class RectArea using dot operator. (e.g.
rect1.length). This is how the member variables and member methods are accessed by
using the objects of a particular class in different class.

Abstraction:
As per dictionary, abstraction is the quality of dealing with ideas rather than events. For
example, when you consider the case of e-mail, complex details such as what happens as
soon as you send an e-mail, the protocol your e-mail server uses are hidden from the
user. Therefore, to send an e-mail you just need to type the content, mention the address
of the receiver, and click send.
Likewise in Object-oriented programming, abstraction is a process of hiding the
implementation details from the user, only the functionality will be provided to the user.
In other words, the user will have the information on what the object does instead of how
it does it.
In Java, abstraction is achieved using Abstract classes and interfaces.

Abstract Class

A class which contains the abstract keyword in its declaration is known as abstract
class.
 Abstract classes may or may not contain abstract methods, i.e., methods without
body ( public void get(); )
 But, if a class has at least one abstract method, then the class must be declared
abstract.
 If a class is declared abstract, it cannot be instantiated.
 To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
 If you inherit an abstract class, you have to provide implementations to all the
abstract methods in it.
Example:
public abstract class Room //abstract is used to restrict object creation
{
int length, breadth;
Room(int length, int breadth)
{
this.length=length;
this.breadth=breadth;
}
int getArea(){
return length*breadth;
}
}

//... this is a derived class ......

class Bedroom extends Room


{
int height;
Bedroom(int x, int y, int z)
{
super(x, y);
height=z;
}

int getVolume(){
return length*breadth*height;
}
}

public class RoomMain


{
public static void main(String[] args)
{
//Room r = new Room(25,27); we can not create an object no need of this
Bedroom room = new Bedroom(24,12,35);
int area=room.getArea();
int volume=room.getVolume();
System.out.println("The area is"+area);
System.out.println("The volume of a room is"+volume);
}
}
Abstract Methods

If you want a class to contain a particular method but you want the actual
implementation of that method to be determined by child classes, you can declare the
method in the parent class as an abstract.
 abstract keyword is used to declare the method as abstract.
 You have to place the abstract keyword before the method name in the method
declaration.
 An abstract method contains a method signature, but no method body.
 Instead of curly braces, an abstract method will have a semi colon (;) at the end.
Following is an example of the abstract method.
Example
public abstract class Employee {
private String name;
private String address;
private int number;

public abstract double computePay();


// Remainder of class definition
}
Declaring a method as abstract has two consequences −
 The class containing it must be declared as abstract.
 Any class inheriting the current class must either override the abstract method or
declare itself as abstract.
public class Salary extends Employee {
private String name;
private String address;
private int number;

public abstract double computePay();


OR
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}

Encapsulation:
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting
on the data (methods) together as a single unit. In encapsulation, the variables of a class
will be hidden from other classes, and can be accessed only through the methods of their
current class. Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
 Declare the variables of a class as private.
 Provide public setter and getter methods to modify and view the variables values.

Example
Following is an example that demonstrates how to achieve Encapsulation in Java −
/* File name : EncapTest.java */
public class EncapTest {
private String name;
private String idNum;
private int age;

public int getAge() {


return age;
}

public String getName() {


return name;
}

public String getIdNum() {


return idNum;
}

public void setAge( int newAge) {


age = newAge;
}

public void setName(String newName) {


name = newName;
}

public void setIdNum( String newId) {


idNum = newId;
}
}
The public setXXX() and getXXX() methods are the access points of the instance
variables of the EncapTest class. Normally, these methods are referred as getters and
setters. Therefore, any class that wants to access the variables should access them
through these getters and setters.
The variables of the EncapTest class can be accessed using the following program −
/* File name : RunEncap.java */

public class RunEncap {


public static void main(String args[]) {
EncapTest encap = new EncapTest();
encap.setName("James");
encap.setAge(20);
encap.setIdNum("12343ms");

System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());


}
}
This will produce the following result −

Output
Name : James Age : 20

Benefits of Encapsulation

 The fields of a class can be made read-only or write-only.


 A class can have total control over what is stored in its fields.

Using ‘this’ keyword

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this can be used to refer current class instance variable.


2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
1. this: to refer current class instance variable

The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.

class Student{
int rn;
String name;
float fees;
Student(int rn,String name,float fees){
this.rn=rn;
this.name=name;
this.fees=fees;
}
void display(){ System.out.println(rn+" "+name+" "+fees); }
}
class TestMain{
public static void main(String args[]){
Student s1=new Student(111,"harendra",5000f);
Student s2=new Student(112,"mahesh",6000f);
s1.display();
s2.display();
}}

2. this: to invoke current class method

You may invoke the method of the current class by using the this keyword. If you don't
use the this keyword, compiler automatically adds this keyword while invoking the
method. Let's see the example

class ThisMethod{
void m(){System.out.println("hello m");}
void n(){
System.out.println("hello n");
//m();//same as this.m()
this.m();
}
}
class TestMain{
public static void main(String args[]){
ThisMethod a=new ThisMethod ();
a.n();
}}

3. this() : to invoke current class constructor

The this() constructor call can be used to invoke the current class constructor. It is used to
reuse the constructor. In other words, it is used for constructor chaining.

Calling default constructor from parameterized constructor:

class ThisConstructor{
ThisConstructor (){System.out.println("hello a");}
ThisConstructor (int x){
this(); //it calls the ThisConstructor() constructor
System.out.println(x);
}
}
class TestMain{
public static void main(String args[]){
ThisConstructor a=new ThisConstructor (10);
}}

OR

Calling parameterized constructor from default constructor:

Class ThisParamCons{
A(){
this(5);
System.out.println("hello a");
}
A(int x){
System.out.println(x);
}
}
class TestMain{
public static void main(String args[]){
ThisParamCons a=new ThisParamCons ();
}}

OR

Using this for re-using constructor

The this() constructor call should be used to reuse the constructor from the constructor. It
maintains the chain between the constructors i.e. it is used for constructor chaining. Let's
see the example given below that displays the actual use of this keyword.

class Student{
int rollno;
String name,course;
float fee;
Student(int rollno,String name,String course){
this.rollno=rollno;
this.name=name;
this.course=course;
}
Student(int rollno,String name,String course,float fee){
this(rollno,name,course);//reusing constructor
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
}
class TestMain{
public static void main(String args[]){
Student s1=new Student(111,"ram","java");
Student s2=new Student(112,"shyam","java",6000f);
s1.display();
s2.display();
}}
4) this: to pass as an argument in the method

The this keyword can also be passed as an argument in the method. It is mainly used in
the event handling(studied later). Let's see the example:

class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this); //this refers to the current class
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}

5) this: to pass as argument in the constructor call

We can pass the ‗this‘ keyword in the constructor also. It is useful if we have to use one
object in multiple classes. Let's see the example:

class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}

class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}

6) this keyword can be used to return current class instance


We can return this keyword as an statement from the method. In such case, return type of
the method must be the class type (non-primitive). Let's see the example:

class A{
A getA(){//not a constructor
return this;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
A a=new A().getA();//a contains the class variable
a.msg();
//new A().getA().msg();
}
}

Constructors
A constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of constructor call, memory for the object is allocated in
the memory.

Every time an object is created using the new() keyword, at least one constructor is
called.

It calls a default constructor if there is no constructor available in the class. In such case,
Java compiler provides a default constructor by default if not provided by the user.

There are two types of constructors in Java: no-arg constructor (default constructor),
and parameterized constructor.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Default constructors
A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


<class_name>(){}
Example of default constructor

//Java Program to create and call a default constructor


class Student{
//creating a default constructor
Student(){
System.out.println("Student is created");
}
public static void main(String args[]){
//calling a default constructor
Student s=new Student();
}
}

Parameterized constructors
A constructor which has a specific number of parameters is called a parameterized
constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects.


However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that has two parameters.
We can have any number of parameters in the constructor. We can have more than one
constructors as well.

//Java Program to demonstrate the use of the parameterized constructor.


class Student{
int id;
String name;
//creating a parameterized constructor
Student(int i, String n){
id = i;
name = n;
}
//method to display the values
void display(){
System.out.println(id+" "+name);
}

public static void main(String args[]){


//creating objects and passing values
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Private Constructor:
Private constructor restricts the object creation outside the class but we can create objects
of a class inside the same class.
Example:

public class Test1 {

// create private constructor


private Test1() {
System.out.println("This is a private constructor.");
}

// create a public static method


public static void instanceMethod() {

// create an instance of Test class


Test1 obj = new Test1();
}
}

class Main {

public static void main(String[] args) {


//we can not create objects of a class having private constructors outside class
// Test1 obj = new Test1();
// call the instanceMethod()
Test1.instanceMethod();
}
}

More on Methods: passing by value, by reference, access control, methods that return
values, polymorphism and method overloading, recursion; Nested and inner classes.

Passing by values and passing by reference

There is only call by value in java, not call by reference. If we call a method passing a
value, it is known as call by value. The changes being done in the called method, is not
affected in the calling method.

Example of call by value in java


In case of call by value original value is not changed. Let's take a simple example:

class Operation{
int data=50;
void change(int data){
data=data+100;//changes will be in the local variable only
}
public static void main(String args[]){
Operation op=new Operation();
System.out.println("before change "+op.data);
op.change(500);
System.out.println("after change "+op.data);
}
}

Output:before change 50
after change 50
Another Example of call by value in java
In case of call by reference original value is changed if we made changes in the called
method. If we pass object in place of any primitive value, original value will be changed.
In this example we are passing object as a value. Let's take a simple example:
class Operation2{
int data=50;

void change(Operation2 op){


op.data=op.data+100;//changes will be in the instance variable
}

public static void main(String args[]){


Operation2 op=new Operation2();
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
Output:before change 50
after change 150

Access Control / Access Modifiers

1. Private access modifier


2. Role of private constructor
3. Default access modifier
4. Protected access modifier
5. Public access modifier
6. Access Modifier with Method Overriding

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.

There are four types of Java access modifiers:


1. Private: The access level of a private modifier is only within the class. It cannot
be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.

Methods that return values


Methods are nothing, they are basically functions and we already know how return type
functions work. A method that returns or throws some values (integer, string, float,
object, array, etc) after it is being called from any part of a program is called a return type
method.
Example:to find the minimum number among two numbers

public class MinumumNum {

public static void main(String[] args) {


int a = 11;
int b = 6;
int c = minMethod(a, b);
System.out.println("Minimum Value = " + c);
}

/** returns the minimum of two numbers */


public static int minMethod(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;

return min;
}
}

Polymorphism and method overloading


Polymorphism means "many forms", and it occurs when we have many classes that are
related to each other by inheritance. Polymorphism uses those methods to perform
different tasks. This allows us to perform a single action in different ways.
For example, think of a superclass called Animal that has a method
called animalSound(). Subclasses of Animals could be Pigs, Cats, Dogs, Birds - And they
also have their own implementation of an animal sound (the pig oinks, and the cat
meows, etc.):
Method Overriding
class Animal {
public void animalSound() {
System.out.println("The animal makes a sound");
}
}

class Pig extends Animal {


public void animalSound() {
System.out.println("The pig says: wee wee");
}
}

class Dog extends Animal {


public void animalSound() {
System.out.println("The dog says: bow wow");
}
}

Method Overloading
Method overloading is the process of defining more methods of same names with
different number of parameters or different data type.
Example:
public class ClassRoom {
int length;
int breadth;

void getData(int a, int b)


{
length=a;
breadth=b;
}
void getData (int x){
length=breadth=x;
}

int area()
{
return length*breadth;
}
}

public class ClassRoomMain {


public static void main(String[] args) {
ClassRoom room1 = new ClassRoom();
room1.getData(20,30);
int areaR =room1.area();
System.out.println("The area of rectangle is "+areaR);

ClassRoom room2=new ClassRoom();


room2.getData(50);
int areaS=room2.area();
System.out.println("The area of square is”+areaS);
}
}

Recursion
Recursion in java is a process in which a method calls itself continuously. A method in
java that calls itself is called recursive method.

It makes the code compact but complex to understand.

Syntax:

returntype methodname(){
//code to be executed
methodname();//calling same method
}

Java Recursion Example 1: Infinite times

public class RecursionExample1 {


static void p(){
System.out.println("hello");
p();
}

public static void main(String[] args) {


p();
}
}

Output:

hello
hello
...
java.lang.StackOverflowError

Java Recursion Example 2: Finite times

public class RecursionExample2 {


static int count=0;
static void p(){
count++;
if(count<=5){
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args) {
p();
}
}

Output:

hello 1
hello 2
hello 3
hello 4
hello 5

Java Recursion Example 3: Factorial Number

public class RecursionExample3 {


static int factorial(int n){
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
public static void main(String[] args) {
System.out.println("Factorial of 5 is: "+factorial(5));
}
}

Output:

Factorial of 5 is: 120

Working of above program:

factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120

Java Recursion Example 4: Fibonacci Series

public class RecursionExample4 {


static int n1=0,n2=1,n3=0;
static void printFibo(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibo(count-1);
}
}
public static void main(String[] args) {
int count=15;
System.out.print(n1+" "+n2);//printing 0 and 1 as n1 and n2 are static
printFibo(count-2);//n-2 because 2 numbers are already printed
}
}

Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Nested and inner classes.


Java inner class or nested class is a class which is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it can
be more readable and maintainable.

Additionally, it can access all the members of outer class including private data members
and methods.

Syntax of Inner class


class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}

Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.

3) Code Optimization: It requires less code to write.

Difference between nested class and inner class in Java

Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes

There are two types of nested class non-static and static nested classes. The non-static
nested classes are also known as inner classes.

o Non-static nested class (inner class)


1. Member inner class
2. Anonymous inner class
3. Local inner class
o Static nested class
1. Java Member inner class

A non-static class that is created inside a class but outside a method is called member
inner class.

Syntax:

class Outer{
//code
class Inner{
//code
}
}

Java Member inner class example

In this example, we are creating msg() method in member inner class that is accessing the
private data member of outer class.

class TestMemberOuter{
private int data=30;
class Inner{ //defined outside the main method
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}

2. Anonymous inner class

An inner class declared without a class name is known as an anonymous inner class.
In case of anonymous inner classes, we declare and instantiate them at the same time.
Generally, they are used whenever you need to override the method of a class or an
interface. The syntax of an anonymous inner class is as follows −
Syntax
AnonymousInner an_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};

The following program shows how to override the method of a class using
anonymous inner class.
Example
abstract class AnonymousInner {
public abstract void mymethod();
}

public class Outer_class {

public static void main(String args[]) {


AnonymousInner inner = new AnonymousInner() {
public void mymethod() {
System.out.println("This is an example of anonymous inner class");
}
};
inner.mymethod();
}
}

3. Local inner class


In Java, we can write a class within a method and this will be a local type. Like local
variables, the scope of the inner class is restricted within the method.
A method-local inner class can be instantiated only within the method where the inner
class is defined. The following program shows how to use a method-local inner class.
Example

public class Outerclass {


// instance method of the outer class
void my_Method() {
int num = 23;
// method-local inner class
class MethodInner_Demo {
public void print() {
System.out.println("This is method inner class "+num);
}
} // end of inner class
// Accessing the inner class
MethodInner_Demo inner = new MethodInner_Demo();
inner.print();
}
public static void main(String args[]) {
Outerclass outer = new Outerclass();
outer.my_Method();
}
}

Static Nested Class

A static inner class is a nested class which is a static member of the outer class. It can be
accessed without instantiating the outer class, using other static members. Just like static
members, a static nested class does not have access to the instance variables and methods
of the outer class. The syntax of static nested class is as follows −
Syntax
class MyOuter {
static class Nested_Demo {
}
}
Instantiating a static nested class is a bit different from instantiating an inner class. The
following program shows how to use a static nested class.
Example
public class Outer {
static class Nested_Demo { //static nested class
public void my_method() {
System.out.println("This is my nested class");
}
}

public static void main(String args[]) {


//no need to instantiate Outer class
Outer.Nested_Demo nested = new Outer.Nested_Demo();
nested.my_method();
}
}
Unit 4: Inheritance and Packaging [3 hours]
Inheritance: Using „extends‟ keyword, Sub classes and Superclasses, super keyword
usage, Overriding methods, Dynamic Method Dispatch;

The object class, Abstract and final classes.

Packages: Defining a package, importing a Package: Access control; Interface,


Implementing and applying interface.

Inheritance:
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented
programming system).

The idea behind inheritance in Java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and
fields of the parent class. Moreover, you can add new methods and fields in your current
class also.
Inheritance represents the IS-A relationship which is also known as a parent-
child relationship.

Why use inheritance in java?


 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also
called a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you
to reuse the fields and methods of the existing class when you create a new class. You
can use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass or


base, and the new class is called child or subclass or derived.

Example of Super class and Sub class:

//Super class
class Employee{
float salary=40000;
}
//Sub class
class Programmer extends Employee{ //salary is already inherited to this class
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

METHOD OVERRIDING

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has
been declared by one of its parent class, it is known as method overriding.

//.....Base Class.......
public class OverrideSuper{
int x;
public OverrideSuper(int x) //Constructor
{
this.x=x;
}
void display()
{
System.out.println("Super x= "+x);
}
}

//----Derived class--------------
public class OverrideSub extends OverrideSuper
{
int y;
public OverrideSub(int x, int y)
{
super(x); //This value of x is for base class‟s variable
this.y=y;
}
void display()//overriding the method display of base class
{
System.out.println("Super x= " +x);
System.out.println("Sub y = " +y);
}
}

public class OverrideMain


{
public static void main(String[] args)
{
OverrideSub sub = new OverrideSub(100,200);
sub.display();
}
}

Types of Inheritance:
Inheritance is the process of deriving all the properties of base class or parent class or
super class to a derived class or child class or sub class. Properties may include variables
and methods. There are three types of inheritances in java and the most important thing is
multiple inheritances is not compatible in java, we generally use interfaces to achieve
multiple inheritance. The types of inheritances are given as follows;

SINGLE INHERITANCE

When a class inherits another class, it is known as a single inheritance. In the example
given below, BedRoom class inherits the Room class, so there is the single inheritance.
Super keyword is used to initialize the variables of base class in derived class.

Example:
//... this is a base class ......
public class Room
{
int length, breadth;
Room(int length, int breadth)
{
this.length=length;
this.breadth=breadth;
}
int roomArea(){
return length*breadth;
}
}

//... this is a derived class ......

class Bedroom extends Room


{
int height;
Bedroom(int x, int y, int z)
{
super(x, y);
height=z;
}

int roomVolume(){
return length*breadth*height;
}
}
public class RoomMain
{
public static void main(String[] args)
{
Bedroom room = new Bedroom(24,12,35);
int area=room.roomArea();
int volume=room.roomVolume();
System.out.println("The area is"+area);
System.out.println("The volume of a room is"+volume);
}
}

MULTILEVEL INHERITANCE

When there is a chain of inheritance, it is known as multilevel inheritance. As we can see,


in example below, Car is the base class and Maruti inherits Car, similarly, Maruti800
inherits Maruti, there is a levelwise inheritance. It implies Maruti800 has all the
properties of Car and Maruti and itself.

Example:
//... this is a base class ......
public class Car
{
Car()
{
System.out.println(("This is a Class Car");
}
Public void vehicleType(){
System.out.println(("Vehicle Type: Car");
}
}

public class Maruti extends Car


{
Maruti()
{
System.out.println(("This is a Class Maruti");
}
public void brand(){
System.out.println(("Brand: Maruti");
}

public void speed(){


System.out.println("Max: 90kmph");
}
}

public class Maruti800 extends Maruti


{
Maruti800()
{
System.out.println(("Maruti model:800");
}
public void speed(){
System.out.println("Max: 90kmph");
}
}

public class CarMain


{
public static void main(String[] args)
{
Maruti800 car = new Maruti800();
car.vehicleType();
car.speed();
car.brand();
}
}

HIERARCHICAL INHERITANCE
When two or more classes inherits a single class, it is known as hierarchical inheritance.
In the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

Example:
class Animal{
int legs=4;
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
System.out.println("I have”+c.legs+” legs.");
//c.bark(); //Compile Time Error
Dog d=new Dog();
d.bark();
d.eat();
System.out.println("I have”+d.legs+” legs.");
}
}

Dynamic method dispatch


It is the mechanism in which a call to an overridden method is resolved at run time
instead of compile time. This is an important concept because of how Java implements
run-time polymorphism.

Java uses the principle of „a superclass reference variable can refer to a subclass
object‟ to resolve calls to overridden methods at run time. When a superclass reference is
used to call an overridden method, Java determines which version of the method to
execute based on the type of the object being referred to at the time call.

In other words, it is the type of object being referred to that determines which version of
an overridden method will be executed.

Example:

// Implementing Dynamic Method Dispatch

class Apple
{
void display()
{
System.out.println("Inside Apple's display method");
}
}

class Banana extends Apple


{
void display() // overriding display()
{
System.out.println("Inside Banana's display method");
}
}

class Cherry extends Apple


{
void display() // overriding display()
{
System.out.println("Inside Cherry's display method");
}
}

class Fruits_Dispatch
{
public static void main(String args[])
{
Apple a = new Apple(); // object of Apple
Banana b = new Banana(); // object of Banana
Cherry c = new Cherry(); // object of Cherry

Apple ref; // taking a reference of Apple

//Dynamic dispatches
ref = a; // ref refers to a object in Apple
ref.display(); // calling Apple's version of display()

ref = b; // ref refers to a object in Banana


ref.display(); // calling Banana's version of display()

ref = c; // ref refers to a object in Cherry


ref.display(); // calling Cherry's version of display()
}
}

Note: Upcasting: When Parent class reference variable refers to Child class object, it is
known as Upcasting.

The object class


The Object class is the parent class of all the classes in java by default. In other words, it
is the topmost class of java.

Example:

public class objectclass {


public static void main(String[] args) {
CheckObject(12);
CheckObject(23.54f);
CheckObject("harendra");
CheckObject(23.4567d);
}
public static void CheckObject(Object ob) {
if (ob instanceof Integer) {
System.out.println(ob + " is an integer");
} else if (ob instanceof Float) {
System.out.println(ob + " is a float");
} else if (ob instanceof String) {
System.out.println(ob + " is a String");
} else {
System.out.println(ob + " is of " + ob.getClass().getName());
}
}
}

Abstract and final classes


A class which is declared with the abstract keyword is known as an abstract class in Java.
It can have abstract and non-abstract methods (method with the body).

o An abstract class must be declared with an abstract keyword.


o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of
the method.

A method which is declared as abstract and does not have implementation is known as an
abstract method.

syntax of abstract method


abstract void printStatus();//no method body and abstract

Example of abstract class:


abstract class Bank{ //abstract class
abstract int getRateOfInterest(); //abstract method
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}

class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}

Final classes:
The final modifier for finalizing the implementations of classes, methods, and variables.
The main purpose of using a class being declared as final is to prevent the class from
being subclassed. If a class is marked as final then no class can inherit any feature from
the final class.
You cannot extend a final class. If you try it gives you a compile time error.

Example
final class Super {
private int data = 30;
}
public class Sub extends Super{
public static void main(String args[]){
}
}
Output
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
at newJavaExamples.Sub.main(Sub.java:9)

Final variable:
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; //compile time error
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class

Final methods:
If you make any method as final, you cannot override it.

Example of final method


class Bike{
final void run(){System.out.println("running");} //final method
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");} //compile time error
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}

Can Final method be inherited?

Ans) Yes, final method is inherited but you cannot override it. For Example:

class Bike{
final void run(){System.out.println("running...");} //final method
}
class Honda extends Bike{
public static void main(String args[]){
new Honda2().run(); //run method is inherited
}
}

Blank or uninitialized final variable


A final variable that is not initialized at the time of declaration is known as blank final
variable.

If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.

Example of blank final variable


class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}

It can be initialized only in constructor.

class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
Student(){
PAN_CARD_NUMBER=‖10023N‖;
}
public static void main(String[] args){
System.out.println(―The pan card number is‖+ PAN_CARD_NUMBER);
}
}
OR
Initialize inside static block as;

class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
static{PAN_CARD_NUMBER=‖10023N‖;}

public static void main(String[] args){


System.out.println(―The pan card number is‖+ PAN_CARD_NUMBER);
}
}

Packages: Defining a package, importing a Package: Access control;


Interface, Implementing and applying interface.
Packages
• Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub
packages.
• Many implementations of Java use a hierarchical file system to manage source and class
files.
• It is easy to organize class files into packages.
• All we need to do is put related class files in the same directory, give the directory a name
that relates to the purpose of the classes, and add a line to the top of each class file that
declares the package name, which is the same as the directory name where they reside.
• For example: java.lang, java.io, java.util etc.

Advantages of using a package


• Reusability: Reusability of code is one of the most important requirements in the
software industry. Reusability saves time, effort and also ensures consistency. A class
once developed can be reused by any number of programs wishing to incorporate the
class in that particular program.
• Easy to locate the files.
• In real life situation there may arise scenarios where we need to define files of the same
name. This may lead to ―name-space collisions‖. Packages are a way of avoiding ―name-
space collisions‖.

Types of packages
• User defined package: The package we create is called user-defined package.
• Built-in package: The already defined package like java.io.*, java.lang.* etc are known as
built-in packages.
• Note: a package hierarchy must be reflected through the file system.
– E.g. package java.awt.image-> needs to be stored in java\awt\image.

Defining and importing a Package


• This statement should be used in the beginning of the program to include that program in
that particular package.
package <package name>;
• Package p1; //user-defined
• E.g.
– Import java.util.*; //system defined or built in packages

Access Control / Modifiers

Example of access modifier in packages


Before implementing different access modifiers, we must create two different packages
PackageOne and PackageTwo .
package PackageOne;
public class ProtectionLevel {
int number=1;
public int numberPublic=4;
private int numberPrivate=2;
protected int numberProtected=3;

public ProtectionLevel(){
System.out.println("Protection level in same class");
System.out.println("number="+number);
System.out.println("Public number="+numberPublic);
System.out.println("Private number="+numberPrivate);
System.out.println("Protected number="+numberProtected);
}
}

Note: Access modifiers (public, private, protected and no modifier) in same class are
accessible.

package PackageOne;
public class DerivedP extends ProtectionLevel{
DerivedP(){
System.out.println("Constructer derived from Protectionlevel: private does not work");

System.out.println("number="+number);
System.out.println("Public number="+numberPublic);
//System.out.println("Private number="+numberPrivate);
System.out.println("Protected number="+numberProtected);
}
}
Note: Access modifiers (public, protected and no modifier) in derived class are
accessible but private data are not accessible.

package PackageOne;
public class PackageSameAccess {
public PackageSameAccess() {
ProtectionLevel pl = new ProtectionLevel();
System.out.println("Protection level at the same package: private does not
work");
System.out.println("number="+pl.number);
System.out.println("Public number="+pl.numberPublic);
//System.out.println("Private number="+pl.numberPrivate);
System.out.println("Protected number="+pl.numberProtected);
}
}
Note: Access modifiers (public, protected and no modifier) in same package class are
accessible but private data are not accessible.

package PackageOne;
public class DemoPackage {
public static void main(String[] args) {
ProtectionLevel pl= new ProtectionLevel();
DerivedP dp= new DerivedP();
PackageSameAccess psa=new PackageSameAccess();
}
}
Note: We can run above class for the output.

Protection level in different packages.

package PackageTwo;
public class ProtectionLevel2 extends PackageOne.ProtectionLevel{
public ProtectionLevel2() {
System.out.println("Derived from other package constructor");
//System.out.println("number="+number);//no modifier
System.out.println("Public number="+numberPublic);
//System.out.println("Private number="+numberPrivate);
System.out.println("Protected number="+numberProtected);
}
}
Note: Access modifiers (public, protected) in different package derived class are
accessible but private and no modifier data are not accessible.

package PackageTwo;
public class PackageOtherProtection {
public PackageOtherProtection() {
PackageOne.ProtectionLevel p1pl=new PackageOne.ProtectionLevel();
System.out.println("Protection level from other package class instantiation");
//System.out.println("number="+p1pl.number);
System.out.println("Public number="+p1pl.numberPublic);
//System.out.println("Private number="+p1pl.numberPrivate);
//System.out.println("Protected number="+p1pl.numberProtected);
}
}
Note: Access modifiers (public) in different package class (instantiation) are accessible
but private, protected and no modifier data are not accessible.

package PackageTwo;
public class DemoPackage2 {
public static void main(String[] args) {
ProtectionLevel2 p2 = new ProtectionLevel2();
PackageOtherProtection pop = new PackageOtherProtection();
}
}

Note: Execute main method for output.

Interface, Implementing and applying interface.


Interface:
 Interface looks like class but it is not a class. An interface can have methods and
variables just like the class but the methods declared in interface are by default abstract
(only method signature, no body). Also, the variables declared in an interface are
public, static & final by default.
 Java programming language does not support multiple inheritances, using interfaces we
can achieve this as a class can implement more than one interfaces, however it cannot
extend more than one classes.
 All methods in an interface are implicitly public and abstract.

Properties of Interface /Implementing interfaces and applying


1.We can‘t instantiate an interface in java.
2.‗implements‘ keyword is used by classes to implement an interface.
3.While providing implementation in class of any method of an interface, it needs to be
mentioned as public(method must be public).
4. Class implementing any interface must implement all the methods, otherwise the class
should be declared as ―abstract‖.
5. Interface cannot be declared as private, protected.
6.All the interface methods are by default abstract and public.
7.Variables declared in interface are public, static and final by default.

8.Interface variables must be initialized at the time of declaration otherwise compiler will
through an error.

9.Inside any implementation class, you cannot change the variables declared in interface
because by default, they are public, static and final.

10. Any interface can extend any interface but cannot implement it. Class implements
interface and interface extends interface.

11. A class can implement any number of interfaces.


12. If there are two or more same methods in two interfaces and a class implements both
interfaces, implementation of the method once is enough.
13. A class cannot implement two interfaces that have methods with same name but
different return type as shown aside.
14. Variable names conflicts can be resolved by interface name as shown below;
Unit 5: Handling Error/Exceptions [2 hours]
Basic Exceptions, Proper use of Exceptions, User Defined Exceptions, Catching
Exceptions: try, catch; Throwing and re-throwing: throw, throws; Cleaning up using the
finally clause.

Exception:

 An exception is an indication of a problem occurs during the program execution.

 The name ―exception‖ implies that the problem occurs infrequently.

 With exception handling the program continue executing after dealing with a
problem.

Overview:

Perform Task
If the preceding task did not execute correctly
Perform error processing
Perform next task
If the preceding task did not execute correctly
Perform error processing
…………….
This pseudo code begins by performing a task; then tests whether it executed correctly. If
not, we perform error processing. Otherwise, we continue with the next task. Although
this types of error handling works but difficult to read, modify, maintain and debug-
especially in large applications.

Exception Handling:
The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.
errors such as ClassNotFoundException, IOException, SQLException,
RemoteException, etc.

Advantage of Exception Handling


To maintain the normal flow of the application, an exception normally disrupts the
normal flow of the application that is why we use exception handling

Types of Java Exceptions


Two types of exceptions: checked and unchecked

Checked Exception
Checked exceptions are checked at compile-time.
e.g. IOException, SQLException etc

Unchecked Exception
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc
Blocks used for handling exceptions:

try{
Block of codes
}
catch(type of exception)
{
exception handler for try block of codes
}

Here, the exception occurred in the ‗try‘ block is caught by ‗catch‘ block.
Throw:
The "throw" keyword is used to throw an exception.
Throws:
• The "throws" keyword is used to declare exceptions.
• It doesn't throw an exception.
• It specifies that there may appear an exception in the method.
• It is always used with method signature.

Example: Divide by zero and Input Mismatch without exception handling

class DivideByZeroNoExceptionHandling
{
public static int quotient(int numerator, int denominator)
{
return numerator/denominator;
}
public static void main(Strings args[])
{
Scanner input= new Scanner(System.in);
System.out.println(“Please enter an integer numerator:”);
int numerator=input.nextInt();
System.out.println(“Please enter an integer denominator:”);
int denominator=input.nextInt();
int result = quotient(numerator, denominator);
System.out.println(“Result is :”+result);
}
}

Output:
Please enter an integer numerator: 20
Please enter an integer numerator:hello
It gives InputMismatchException

Output:
Please enter an integer numerator: 20
Please enter an integer numerator:0
It gives ArithmeticException
Handling mismatch and divide by zero exceptions:
import java.util.InputMismatchException;
import java.util.Scanner;

class ExceptionHandling
{
public static int quotient(int numerator, int denominator)
{
return numerator/denominator;
}
public static void main(String args[]){
Scanner input= new Scanner(System.in);
boolean continueloop=true; //determines if more input is needed
do{
try{
System.out.println("Please enter an integer numerator:");
int numerator=input.nextInt();
System.out.println("Please enter an integer denominator:");
int denominator=input.nextInt();
int result = quotient(numerator, denominator);
System.out.println("Result is :"+result);
continueloop=false;
} //end try

catch(InputMismatchException ex){
System.err.println("Exception is:" + ex);
input.nextLine();
System.out.println("You must enter integer.Please try again:");
}
catch(ArithmeticException arEx) {
System.err.println("Exception is:" + arEx);
System.out.println("Zero is an invalid denominator.Please try again:");
}
}while(continueloop); //end do……while
}
}
Output:
Please enter an integer numerator:
30
Please enter an integer denominator:
hello
Exception is:java.util.InputMismatchException
You must enter integer.Please try again:
Please enter an integer numerator:
23
Please enter an integer denominator:
0
Exception is:java.lang.ArithmeticException: /
by zero
Zero is an invalid denominator.Please try again:
Please enter an integer numerator:

Note: Exception handling does not stop the execution of a program, means the whole
program is executed. In above example, we can easily see the program is not stopped
however the exceptions arisen. It continues till we supply the correct values i.e. both
numerator and denominator must be integer values.

Finally Block:

Java guarantees that the final block will execute whether or not an exception is thrown in
the corresponding try block.

 Java also guarantees that the finally block executes if a try block exits by using a
return, break or continue statement.

 But, the finally block will not execute if the application exits early from a try
block by calling method System.exit.

try
{
Main block of code to check the exception
resource used statements
}
catch(AKindofException e)
{
exception handling statements
}
catch(AotherKindofException e)
{
exception handling statements
}
finally
{
statements
resource released statements
always executes
}

Description:
Since, finally block always executes, it typically contains resource-release code. Suppose
a resource is allocated in a try block. If no exception occurs, the catch blocks are skipped
and control proceeds to the finally block, which frees the resource.

Whether there is exception occurs or not, finally block is responsible to release the
resource.
Throwing exceptions using throw statement:
 ―throw‖ statement is used to send exceptions to the next block. E.g. in the
example before; the method throwException throws a new exception generated
using Exception class.
 throw new Exception() ;=> indicates that an exception is occurred.
 Re-throwing statements:
 Exceptions are re-thrown from catch blocks, if these types of exceptions can not
be processed or can be partially processed.
 ―throw‖ keyword is used to pass the exceptions from the current block to the next
block.
 E.g. throw ex; => in the previous program.
Stack Unwinding:
When an exception is thrown but not caught in a particular scope, the method called stack
unwind.
Example:
import java.util.Scanner;
public class StackUnwinding {
public static void main(String[] args) {
try{
throwException();
}
catch(Exception ex){
System.err.println("Exception handled in main");
}
}
//Demonstrate try...catch...finally blocks
public static void throwException() throws Exception //throws used to inherit
{
try{
//System.out.println("Method throw exception");
Scanner input= new Scanner(System.in);
System.out.println("Enter the value of number1");
int number1=input.nextInt();
System.out.println("Enter the value of number2");
int number2=input.nextInt();
int result=number1/number2;
System.out.println("The value after dividing is"+result);
throw new Exception(); //generate system exception
}
catch(RuntimeException e){
System.err.println("Exception handled in method
throwException");
}
finally{
System.err.println("Finally is always executed.");
}
}
}
Note:
Exception thrown from try block does not match the RuntimeException, so catch block is
not executed. The condition is called Stack Unwinding.

Creating own exceptions / Custom Exceptions:


public class OwnExceptions extends Exception {
public OwnExceptions(String msg) {
super(msg); //Message sent to Exception class
}
}

public class OwnExceptionmain {


static void EmployeeAge(int age) throws OwnExceptions
{
if(age<0) {
throw new OwnExceptions("Age less than zero Exception");
}
else {
System.out.println("Valid Input");
}
}
public static void main(String[] args) {
try {
EmployeeAge(-2);
}
catch(OwnExceptions ex) {
ex.printStackTrace();
}
}
}

A user can create custom exceptions by extending the class from Exception class.
Exception is a super class for all kinds of exceptions, so whenever a class extends
Exception class it becomes the exception.

Cleaning up using the finally clause.

The ‗finally‘ block is generally used to free the resources such as closing files in file
handling, closing connections in database, closing sockets in network programming, etc.
We will learn in the respective sections how finally block is used to free the resources.
Unit 6: Handling Strings [2 hours]
Creation, Concatenation and Conversion of a string, Changing Case, Character
Extraction, String Comparison, Searching Strings, Modifying Strings, String buffer.

Strings Manipulation
 String manipulation is the most common part in many java programs. String
represents the sequence of characters. The easiest way to represent the sequence of
characters in java is by using character array;
 char charArray[ ] = new char[4];
 char[0]=‗j‘;
 char[1]=‗a‘;
 char[2]=‗v‘;
 char[3]=‗a‘;
 Using String class;
String stringname = new String(―Java‖);

String Methods used in Java Programming Languages


Method Call Task Performed
S2 = s1.toLowerCase; Converts the string s1 to all lowercase.
S2 = s1.toUpperCase; Converts the string s1 to all uppercase.
S2=s1.replace(‗x‘, ‗y‘); Replaces all appearances of x to y.
S2 = s1.trim(); Removes white spaces at the beginning and end of the string.
S1.equals(s2); Check whether s1 is equal to s2. (Same string).
S1.equalsIgnoreCase(s1); Checks whether s1 equals to s2, whatever the case is.
S1.length; Length of a string.
S1.CharAt(n); Gives the nth character of s1.
S1.compareTo(s2); Returns negative if s1<s2, positive if s1>s2, and zero if s1=s2.
S1.concat(s2); Join s1 string to s2 string.
S1.substring(n); Gives substring starting from nth character.
S1.substring(n, m); Gives substring starting from nth character up to mth character(exculding mth).
p.ToString(); Makes p object a string type.
S1.getChars(a,b,c,d); Retrieves substring from any string.
S1.getBytes(); extract characters from String object and then convert the characters in a byte
array.
S1.toCharArray(); Converts the string object to character array.

1. s.length() Method
public class Example{
public static void main(String args[]{
String s1="hello";
String s2="whatsup";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}

2. s.toLowerCase() Method
public class StringLowerExample{
public static void main(String args[]){
String s1="HELLO HOW Are You?”;
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}
}

3. s.toUpperCase() Method
public class StringUpperExample{
public static void main(String args[]){
String s1="hello how are you";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}
}

4. s. replace () Method
public class ReplaceExample1{
public static void main(String args[]){
String s1="hello how are you";
String replaceString=s1.replace('h','t');
System.out.println(replaceString);
}
}

5. s.trim() Method
public class StringTrimExample{
public static void main(String args[]){
String s1=" hello ";
System.out.println(s1+"how are you"); // without trim()
System.out.println(s1.trim()+"how are you"); // with trim()
}
}

6. s1.equals(s2);
public class Equals{
public static void main(String args[]){
String s1="hello";
String s2="HELLO";
System.out.println(s1.equals(s2)); // returns true
System.out.println(s1.equals(s2)); // returns false
}
}

7. s1.equalsIgnoreCase(s2);
public class EqualsExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="hi";
System.out.println(s1.equalsIgnoreCase(s2)); // returns true
System.out.println(s1.equalsIgnoreCase(s3)); // returns false
}
}

8. s1.CharAt(n);
public class CharAtExample {
public static void main(String args[]) {
String str = "Welcome to string handling tutorial";
char ch1 = str.charAt(0);
char ch2 = str.charAt(5);
System.out.println("Character at 0 index is: "+ch1);
System.out.println("Character at 5th index is: "+ch2);
}
}
9. s1.compareTo(s2);
public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="hemlo";
String s4="flag";
System.out.println(s1.compareTo(s2)); // 0 because both are equal
System.out.println(s1.compareTo(s3)); //-1 because "l" is only one time lower
than "m"
System.out.println(s1.compareTo(s4)); // 2 because "h" is 2 times greater than "f"
}
}

10. s1.concat(s2);
public class ConcatExample{
public static void main(String args[]){
String s1="hello";
String s2=" how are you?";
s1=s1.concat(s2);
System.out.println(s1);
}
}

11. s1.substring(n); s1.substring(n, m);


public class SubStringExample{
public static void main(String args[]) {
String str= new String("quick brown fox jumps over the lazy dog");
System.out.println("Substring starting from index 15:");
System.out.println(str.substring(15));
System.out.println("Substring starting from index 15 and ending at 20:");
System.out.println(str.substring(15, 20));
}
}

12. s.ToString();
public class JavaCharacterToStringExample1 {
public static void main(String[] args) {
Character c1, c2;
c1 = new Character('r');
c2 = new Character('9');
String s1, s2;
s1 = c1.toString();
s2 = c2.toString();
System.out.println( s1 );
System.out.println( s2 );
}
}
13. s1.isEmpty()
public class IsEmptyExample{
public static void main(String args[]){
String s1="";
String s2="hello";
System.out.println(s1.isEmpty()); // true
System.out.println(s2.isEmpty()); // false
}
}

14. s1.getChars()

Syntax:
void getChars(int stringStart, int stringEnd, char arr[], int arrStart)

Here stringStart and stringEnd is the starting and ending index of the substring. arr is the
character array that will contain the substring. It will contain the characters starting
from stringStart to stringEnd-1. arrStart is the index inside arr at which substring will be
copied. The arr array should be large enough to store the substring.

public class temp


{
public static void main(String...s)
{
String str="Hello World";
char ch[]=new char[4]; //substring is of length 4 contains four letters
str.getChars(1,5,ch,0);
System.out.println(ch);
}
}
Output
ello

15. getBytes()
getBytes() extract characters from String object and then convert the characters in a
byte array. It has following syntax.

Example:
String str="Hello";
byte b[]=str.getBytes();

16. toCharArray()
It is an alternative of getChars() method. toCharArray() convert all the characters in a
String object into an array of characters. It is the best and easiest way to convert string
to character array.

Example:
class temp
{
public static void main(String[] args)
{
String str="Hello World";
char ch[]=str.toCharArray();
System.out.println(ch);
}
}
Unit 7: Threads [3 hours]
Create/Instantiate/Start New Threads: Extending java.lang.Thread, Implementing
java.lang.Runnable interface; Understand Thread Execution, Thread Priorities,
Synchronization, Inter-Thread Communication, Deadlock.

Concurrency / Multithreading:
 The human body can perform a great variety of operations concurrently
 Blood circulation, digestion, thinking, walking
 Likely, computers too can perform operations concurrently
 Java supports multithreaded programming.
 Multithreading in java is a process of executing multiple threads simultaneously.
 A multi-threaded program contains two or more parts that can run concurrently.
Each part of such program is called a thread, and each thread defines a separate
path of execution.
 A thread is a lightweight sub-process, the smallest unit of processing.
 we use multithreading than multiprocessing because threads use a shared memory
area.
 They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.
 Java Multithreading is mostly used in games, animation, etc.
 Advantages of Java Multithreading
o It doesn't block the user because threads are independent and you can
perform multiple operations at the same time.
o You can perform many operations together, so it saves time.
o Threads are independent, so it doesn't affect other threads if an exception
occurs in a single thread.

Life Cycle of a Thread:

1.New
2.Runnable
3.Running
4.Non-Runnable
(Blocked)
5.Terminated (Dead)

Thread States:

New and Runnable States:


A new thread begins its life cycle in the new state. It remains in this state until the
program starts the thread, which places it in the runnable state. A thread in the runnable
state is considered to be executing its task.

Blocked states(Non-Runnable):
A runnable thread transitions to the blocked state when it attempts to perform a task that
cannot be completed immediately and it must temporarily wait until that task completes.

Terminated state(Dead State):


A runnable thread enters the terminated state (a dead state), when it successfully
completes its task or otherwise terminated.
Creating a Thread:
There are two ways of creating a thread in java programming language;
1. By extending Thread Class
2. By implementing Runnable interface

1. By extending Thread Class:


Thread class provide constructors and methods to create and perform operations
on a thread. Thread class extends Object class
and implements Runnable interface.
If you are not extending the Thread class, your
class object would not be treated as a thread

class Multi extends Thread{ object. So you need to explicitely create


public void run(){ Thread class object. We are passing the object
System.out.println("thread is of your class that implements Runnable so that
running..."); your class run() method may execute.
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}

2. By implementing Runnable interface:

class Multithreading implements Runnable{


public void run(){
System.out.println("thread is running...through runnable interface");
}

public static void main(String args[]){


Multithreading m1=new Multithreading();
Thread t1 =new Thread(m1);
t1.start();
}
}

The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. Runnable interface have only one method named run().
public void run(): is used to perform action for a thread.

Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs
following tasks:
A new thread starts.
The thread moves from New state to the Runnable state.
When the thread gets a chance to execute, its target run() method will run.

Sleep Method of a Thread Class: It is used to wait some threads for certain time.

class TestSleepMethod1 extends Thread{


public void run(){
for(int i=1;i<5;i++){
try{Thread.sleep(5000);}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

t1.start();
t2.start();
}
}

Yield method of thread class:


The yield() method of thread class causes the currently executing thread object to
temporarily pause and allow other threads to execute.
Example:
package ThreadClass;

public class concurrency extends Thread { // Thread-0


public void run() {
Thread.yield(); //if we want execute main thread and stop thread-0.
for (int i = 0; i < 3; i++)
System.out.println(Thread.currentThread().getName() + " in control");
}

public static void main(String[] args) { // main thread


concurrency t1 = new concurrency();

t1.start();
//Thread.yield(); //if we want to stop main thread and give chance to
execute other threads

for (int i = 0; i < 3; i++) {


// Control passes to child thread
System.out.println(Thread.currentThread().getName() + " in under control");
}
}
}

In java 5, yield method uses sleep method internally. But, in java 6, yield method works
by providing the request for yielding to ThreadScheduler whether to accept or reject the
request. For example in above program there are two threads, Thread-0 and Main thread.
Thread-0 and Main thread executes concurrently. Yield is used to request the
ThreadScheduler to stop the current thread and give chance to another threads. E.g. If
Thread.yield() method is used inside the Thread-0, then Main thread executes fully (if
ThreadScheduler accepts the request otherwise the threads executes concurrently). The
output may vary in different execution of a program, which is due to the
ThreadScheduler. Similarly, if Thread.yield() method is used insidethe Main thread then
Thread-0 executes completely.

Stop method of Thread class:


The stop() method of thread class terminates the thread execution. Once a thread is
stopped, it cannot be restarted by start() method.
Example:
package ThreadClass;

public class JavaStopEx extends Thread


{
public void run()
{
for(int i=1; i<5; i++)
{
try
{
// thread to sleep for 500 milliseconds
sleep(2000);
System.out.println(Thread.currentThread().getName());
}catch(InterruptedException e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[])
{
// creating three threads
JavaStopEx t1=new JavaStopEx ();

JavaStopEx t3=new JavaStopEx ();


// call run() method
t1.start();

// stop t3 thread
t3.stop();
System.out.println("Thread t3 is stopped");
}
}

Concept of Multithreading/Concurrency via examples:

Program1: No multithreading used in the program below:


package ThreadClass;
class Good{
void display()
{
for (int i = 0; i < 5; i++) {
System.out.println("Good");
try{Thread.sleep(1000);}catch(Exception ex) {}
//5 second to print this loop
}
}
}

class Morning{
void display()
{
for (int i = 0; i < 5; i++) {
System.out.println("Morning");
try{Thread.sleep(1000);}catch(Exception ex) {}
//5 second to print this for loop
}
}
}
public class NoThread {
public static void main(String[] args) {
Good gd=new Good();
Morning mrg= new Morning();
gd.display();
mrg.display();
}

Use of Multithreading reference to above program.

Program 2: A multithreaded Program using Thread Class:


package ThreadClass;
class GoodHi extends Thread{
public void run()
{
for (int i = 0; i < 5; i++) {
System.out.println("Good");
try{Thread.sleep(1000);}catch(Exception ex) {}

}
}

class MorningHello extends Thread{


public void run()
{
for (int i = 0; i < 5; i++) {
System.out.println("Morning");
try{Thread.sleep(1000);}catch(Exception ex) {}

}
}
public class UseThreadClass {
public static void main(String[] args) {
GoodHi gd=new GoodHi();
MorningHello mrg= new MorningHello();
gd.start();
try{Thread.sleep(10);}catch(Exception ex) {}
mrg.start();
//Parallel execution of two different threads
}
}

Program 3: A multithreaded Program using Runnable Interface:


package ThreadClass;
class Hi implements Runnable{
public void run()
{
for (int i = 0; i < 5; i++) {
System.out.println("Good");
try{Thread.sleep(1000);}catch(Exception ex) {}
}
}
}
class Hello implements Runnable{
public void run()
{
for (int i = 0; i < 5; i++) {
System.out.println("Morning");
try{Thread.sleep(1000);}catch(Exception ex) {}
}
}
}
public class UseOfRunnableInterface {
public static void main(String[] args) {
Hi h=new Hi();
Hello he= new Hello();
Thread t1= new Thread(h);
Thread t2= new Thread(he);
t1.start();
try{Thread.sleep(10);}catch(Exception ex) {}
t2.start();
//Parallel execution of two different threads
}
}

Description:
In program 1, there is no multithreading used, so the program executes sequentially, the
time to execute the program is more because single thread (single processor) is used.

In program 2, there is a use of Thread class. In which, the start() method executes the
run() method of the thread class. Two different classes are extended from thread class and
objects of these classes are two different threads which executes parallel.

In program 2, there is a use of Runnable interface which contains only method i.e. run().
But we cannot call object using start() method directly, for this we have to pass the
objects(i.e runnable type) in the Thread class‘s constructor.

Thread Priorities:
Thread priority is used to schedule the running sequence of threads. The thread with the
same priority is given the same treatment by the Thread Scheduler or Java Scheduler.
Java permits us to set the priority of a Thread using setPriority() method as follows;

ThreadName.setPriority(intnumber);
The intNumber is an integer value to which the Thread‘s priority is set. The Thread class
defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants of any value between 1 and 10.
Default setting is NORM_PRIORITY.

Example:
package ThreadClass;

class ThreadPriority extends Thread {


public void run() {
System.out.println("running thread name is:" +
Thread.currentThread().getName());
System.out.println("running thread priority is:" +
Thread.currentThread().getPriority());

public static void main(String args[]) {


ThreadPriority m1 = new ThreadPriority();
ThreadPriority m2 = new ThreadPriority();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}

Output:
running thread name is:Thread-1
running thread priority is:10
running thread name is:Thread-0
running thread priority is:1

Synchronization:
Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
Java Synchronization is better option where we want to allow only one thread to access
the shared resource.
Synchronization can be used in ticketing systems or any booking systems, banking
transactions, etc. Without synchronization we can face the problems like data
inconsistency, Thread interference(one thread interfere other may cause deadlock).

Without using Synchronization


package ThreadClass;

class CSITBookSeat {

int csit_seats = 48;

public void bookSeat(int seats) {


if (csit_seats >= seats) {
System.out.println(seats + " seats books successfully");
csit_seats = csit_seats - seats;
System.out.println(csit_seats + " seats are available");
} else {
System.out.println("Seats are not vailable");
System.out.println(csit_seats + " seats are available");
}
}
}

public class SynchronizationDemo extends Thread {


static CSITBookSeat sd;
int seats;

public void run() {


sd.bookSeat(seats);
}

public static void main(String[] args) {


sd = new CSITBookSeat();

SynchronizationDemo cbs1 = new SynchronizationDemo();


cbs1.seats = 30;
cbs1.start();

SynchronizationDemo cbs2 = new SynchronizationDemo();


cbs2.seats = 30;
cbs2.start();
}
}

Output:
30 seats books successfully
30 seats books successfully
18 seats are available
-12 seats are available

In above program there is a problem of accessing the same resources at a time by


different threads. The output may be correct at any time if the threads executes at the
same time and bookSeat() method is called at the same time but when will it happens we
can not assume, for this we have to execute the program multiple times and wait for the
correct output at some time.

Concept of Lock in Java

Synchronization is built around an internal entity known as the lock or monitor. Every
object has an lock associated with it. By convention, a thread that needs consistent access
to an object's fields has to acquire the object's lock before accessing them, and then
release the lock when it's done with them.

Figure aside is an object which contains two areas


Non- Synchroni
1. Non-synchronized area
synchroni zed area
zed area
2. Synchronized area (contain methods)
o To access synchronized area of any object, there need
a lock to access the objects fields and methods.

1. Using synchronized method


So, to overcome inconsistency problem the term synchronization is used as follows.

package ThreadClass;

class CSITBookSeat {

int csit_seats = 48;

synchronized public void bookSeat(int seats) { //here method is made


synchronized
if (csit_seats >= seats) {
System.out.println(seats + " seats books successfully");
csit_seats = csit_seats - seats;
System.out.println(csit_seats + " seats are available");
} else {
System.out.println("Seats are not vailable");
System.out.println(csit_seats + " seats are available");
}
}
}

public class SynchronizationDemo extends Thread {


static CSITBookSeat cbs;
int seats;

public void run() {


cbs.bookSeat(seats);
}

public static void main(String[] args) {


cbs = new CSITBookSeat();

SynchronizationDemo ram = new SynchronizationDemo();


ram.seats = 30;
ram.start();

SynchronizationDemo hari = new SynchronizationDemo();


hari.seats = 28;
hari.start();
}
}

Output:
30 seats books successfully
18 seats are available
Seats are not vailable
18 seats are available

Or
28 seats books successfully
20 seats are available
Seats are not vailable
20 seats are available

2. Using synchronized block


Synchronized block can be used to perform synchronization on any specific resource of
the method.
Suppose you have 50 lines of code in your method, but you want to synchronize only 5
lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same as the
synchronized method.

Points to remember for Synchronized block


o Synchronized block is used to lock an object for any shared resource.
o Scope of synchronized block is smaller than the method.

Syntax to use synchronized block


synchronized (object reference expression) {
//code block
}

Example:
package ThreadClass;

class CSITBookSeat {
int csit_seats = 48;

public void bookSeat(int seats) {


System.out.println("I am also synchronized " +
Thread.currentThread().getName());
System.out.println("I am also synchronized " +
Thread.currentThread().getName());
System.out.println("I am also synchronized " +
Thread.currentThread().getName());
System.out.println("I am also synchronized " +
Thread.currentThread().getName());
System.out.println("I am also synchronized " +
Thread.currentThread().getName());
//here synchronized block is used to synchronize required portion
synchronized (this) { //this is a reference object of current class
if (csit_seats >= seats) {
System.out.println(seats + " seats books successfully");
csit_seats = csit_seats - seats;
System.out.println(csit_seats + " seats are available");
} else {
System.out.println("Seats are not vailable");
System.out.println(csit_seats + " seats are available");
}
}
System.out.println("I am also synchronized " +
Thread.currentThread().getName());
System.out.println("I am also synchronized " +
Thread.currentThread().getName());
System.out.println("I am also synchronized " +
Thread.currentThread().getName());
System.out.println("I am also synchronized " +
Thread.currentThread().getName());
System.out.println("I am also synchronized " +
Thread.currentThread().getName());
}
}

public class SynchronizationDemo extends Thread {


static CSITBookSeat sd;
int seats;

public void run() {


sd.bookSeat(seats);
}

public static void main(String[] args) {


sd = new CSITBookSeat();

SynchronizationDemo cbs1 = new SynchronizationDemo();


cbs1.seats = 30;
cbs1.start();

SynchronizationDemo cbs2 = new SynchronizationDemo();


cbs2.seats = 28;
cbs2.start();
}
}

Note: Synchronized block is used in that area of a program where there is a data
inconsistency problem occurred.

3. Static synchronization:

So far we have worked for only one object, what if we create more objects and execute
different object‘s thread, there seems the same inconcistence problem.
Example:
package ThreadClass;

class CSITSeatBook {

int csit_seats = 48;

synchronized public void bookSeat(int seats) {

if (csit_seats >= seats) {


System.out.println(seats + " seats books successfully");
csit_seats = csit_seats - seats;
System.out.println(csit_seats + " seats are available");
} else {
System.out.println("Seats are not vailable");
System.out.println(csit_seats + " seats are available");
}
}
}

class Mythread1 extends Thread {


CSITSeatBook b;
int seats;

Mythread1(CSITSeatBook b, int seats) {


this.b = b;
this.seats = seats;
}

public void run() {


b.bookSeat(seats);
}
}
class Mythread2 extends Thread {
CSITSeatBook b;
int seats;

Mythread2(CSITSeatBook b, int seats) {


this.b = b;
this.seats = seats;
}

public void run() {


b.bookSeat(seats);
}
}

public class StaticSynchronization {


public static void main(String[] args) {
CSITSeatBook b1 = new CSITSeatBook();
//it works fine for single object
Mythread1 t1=new Mythread1(b1, 35);
t1.start();
Mythread1 t2=new Mythread1(b1, 18);
t2.start();
//what if we again create an object and call threads

CSITSeatBook b2 = new CSITSeatBook();


Mythread1 t3=new Mythread1(b2, 8);
t3.start();
Mythread1 t4=new Mythread1(b2, 20);
t4.start();
}
}

In above example, both objects have 48 plus 48 seats each to access but the total seats
must be 48 for both objects. There occurs inconsistence, so to resolve this problem static
synchronization is used. Following example uses static synchronization;

package ThreadClass;

class CSITSeatBook {

static int csit_seats = 48;

static synchronized public void bookSeat(int seats) {

if (csit_seats >= seats) {


System.out.println(seats + " seats books successfully");
csit_seats = csit_seats - seats;
System.out.println(csit_seats + " seats are available");
} else {
System.out.println(seats + " seats are not vailable");
System.out.println(csit_seats + " seats are available");
}

}
}

class Mythread1 extends Thread {


CSITSeatBook b;
int seats;

Mythread1(CSITSeatBook b, int seats) {


this.b = b;
this.seats = seats;
}

public void run() {


b.bookSeat(seats);
}
}

class Mythread2 extends Thread {


CSITSeatBook b;
int seats;

Mythread2(CSITSeatBook b, int seats) {


this.b = b;
this.seats = seats;
}

public void run() {


b.bookSeat(seats);
}
}

public class StaticSynchronization {


public static void main(String[] args) {
CSITSeatBook b1 = new CSITSeatBook();
// it works fine for single object
Mythread1 t1 = new Mythread1(b1, 35);
t1.start();
Mythread1 t2 = new Mythread1(b1, 20);
t2.start();
// what if we again create an object and call threads

CSITSeatBook b2 = new CSITSeatBook();


Mythread2 t3 = new Mythread2(b2, 8);
t3.start();
Mythread2 t4 = new Mythread2(b2, 18);
t4.start();
}
}
Output:
35 seats books successfully
13 seats are available
18 seats are not vailable
13 seats are available
8 seats books successfully
5 seats are available
20 seats are not vailable
5 seats are available

Inter-Thread Communication
Inter thread communication is a mechanism in which a thread releases the lock and enter
into paused state and another thread acquires the lock and continue to execute. It is
implemented by following methods;
1. wait():- If any thread calls the wait() method, it causes the current thread to
release the lock and wait until another thread invokes the notify() or notifyAll()
method for this object, or specifies amount of time has elapsed.
Syntax:
public final void wait() throws InterruptedException {}- wait until object is
notified
public final void wait(long timeout) throws InterruptedException {}- waits for
the specified amount of time.
2. notify():- This method is used to wake up a single thread and releases the object
lock.
Syntax:
public final void notify(){}
3. notifyAll():- This method is used to wake up all threads that are in waiting state.
Syntax:
public final void notifyAll(){}

Note: to call wait(), notify() or notifyAll() method on any object, thread should
own the lock of that object. i.e. the thread should be inside synchronized area.

Example:
class TotalEarnings extends Thread {
int total = 0;

public void run() {


int totalSeats = 48;
for (int i = 0; i < totalSeats; i++) {
total = total + 120000;
}
}
}
public class TotalCalculations {

public static void main(String[] args) {


TotalEarnings te = new TotalEarnings();
te.start();
System.out.println("Total earnings = " + te.total+” rs”);
}
}

Note:
it gives inaccurate total value because run method takes some times to execute, so at that
time main thread executes and the value will be total=0. Main thread executes before
thread-0.

Solution of above problem:


To solve the above program, we are using the synchronized blocks in both main and
Thread-0 part. Following is the implementation part of this solution;

class TotalEarnings extends Thread {


int total = 0;

public void run() {


int totalSeats = 48;
synchronized (this) { //block inside Thread-0 thread
for (int i = 0; i < totalSeats; i++) {
total = total + 120000;
}
this.notify();//to notify main thread to execute and lock is released
}
}
}

public class TotalCalculations {

public static void main(String[] args) {


TotalEarnings te = new TotalEarnings();
te.start();
synchronized (te) { //block inside main thread
try {
te.wait();// waits main thread and lock is released
} catch (Exception ex) {
}
}
System.out.println("Total earnings = Rs." + te.total);
}
}

Output: Total earnings = Rs.5760000

Description:
In above program we can see there are two synchronized blocks, one inside main thread
and another inside thread-0 thread. This is the main reason to get the correct calculation
of the program.
There are basically two areas inside any object of a class, which are non-synchronized
and synchronized areas as shown in figure.

Here both threads will work on synchronized area;


Initially, the main thread will acquire lock, but when it Non- Synchroni
see te.wait() method it will release the lock and thread-0 synchroni zed area
will acquire the lock and start executing and calculate zed area
Lock L
total. As soon as the for loop ends or total is calculated,
thread-0 notify the waiting thread and release the lock
by using method this.notify();
Main Thread-0
Note: if we provide te.wait(1000), it will wait the main thread
for 1 second, thread-0 has to finish its task within 1 second because main thread start
executing as soon as the time elapsed.
 this.notify() will notify only one thread that has been waiting. But notifyAll() will
execute all methods that are in waiting list.

Deadlock:
Deadlock is a situation where two or more threads are blocked forever, waiting for each
other. It occurs in java when synchronized keyword causes the executing thread to block
waiting to get the lock, associated with the specified object.

Example:
class DeadlockOne extends Thread {
private Object object1;
private Object object2;

public DeadlockOne(Object object1, Object object2) {


this.object1 = object1;
this.object2 = object2;
}

public void run() {


synchronized (object1) {
try {
System.out.println("Acquire lock on object1, wait for object2");
sleep(10);
} catch (InterruptedException e) {
}
synchronized (object2) {
System.out.println("Acquire lock on object1 and object2");
}
}
}
}

class DeadlockTwo extends Thread {


private Object object1;
private Object object2;

public DeadlockTwo(Object object1, Object object2) {


this.object1 = object1;
this.object2 = object2;
}

public void run() {


synchronized (object1) {
try {
System.out.println("Acquire lock on object2, wait for object1");
sleep(10);
} catch (InterruptedException e) {
}
synchronized (object2) {
System.out.println("Acquire lock on object2 and object1");
}
}
}
}

public class DeadlockMain extends Thread {


public static void main(String[] args) {
Object object1 = new Object();
Object object2 = new Object();
DeadlockOne one = new DeadlockOne(object1, object2);
one.start();
DeadlockTwo two = new DeadlockTwo(object1, object2);
two.start();
}
}

Description:
The above program has a deadlock. There are two threads thread-0 and thread-1 and both
are acquiring the lock needed by both.
So to remove the deadlock condition, objects are provided in the same order in which
order they are required.
So, modify the partial code as follows;

public DeadlockTwo(Object object1, Object object2) {


this.object1 = object1;
this.object2 = object2;
}

public void run() {


synchronized (object2) {
try {
System.out.println("Acquire lock on object2, wait for object1");
sleep(10);
} catch (InterruptedException e) {
}
synchronized (object1) {
System.out.println("Acquire lock on object2 and object1");
}
}
}
}

After executing modified code, there will be no any deadlocks. Clear the console
terminal and execute fresh one.
Unit 8: I/O and Streams [2 hours]
Java.io package, Files and directories, streams: Byte streams and character
streams:Reading/Writing console Input/Output, Reading and Writing Files, The
serialization Interface, Serialization and Deserialization.

java.io package
This package provides for system input and output through data streams, serialization and
the file system. Unless otherwise noted, passing a null argument to a constructor or method
in any class or interface in this package will cause a NullPointerException to be thrown.
Some of the classes are as follows;
 BufferedInputStream
 BufferedOutputStream
 BufferedReader
 BufferedWriter
 DataInputStream
 DataOutputStream
 FileInputStream
 FileOutputStream
 FileReader
 FileWriter
 PrintStream
 PrintWriter
 InputStream
 OutputStream
 File
 And so on…

 Data stored in variables and arrays is temporary-it lost when a local variable goes
out of scope or when the program terminates. For long term retention of data, even
after the programs that create the data terminate, computers use files.
 So we use hard drive to save files, documents , etc. to use the data in future.

Data hierarchy

 Bits: The smallest data item in a computer can assume the value 0 or the value 1.
 Characters: characters are composed of bits. Digits, letters and special symbols are
known as characters.
 Fields: Fields are composed of characters or bytes. E.g. The uppercase and
lowercase letters can be used to represent a person‘s name(Harendra Raj Bist).
 Records and Files: Typically, several fields are composed of a record. E.g. record
for an employee might consist of the following fields;
 Employee identification number(int)
 Name(String)
 Address(String), etc.

Files and Streams


 File: A file is a collection of related records placed in a particular area on a disk.
 Streams: In file processing, the input refers to the flow of data into a program and
output means the flow of data out of a program. Java uses the concept of streams
to represent the ordered sequence of data, a common characteristics shared by all
input/output devices.
 Basically, stream in java is a path along which the data flows.

Stream Classes
 The java.io package contains a large number of stream classes that provide
capabilities for processing all types of data. These classes may be categorised into
two groups based on the data type on which they operate;
 Byte Stream classes that provide support for handling I/O operations on
bytes.
 Character Stream classes that provide support for managing I/O operations
on characters.
 This package includes definitions for stream classes, such as FileInputStream,
FileOutputStream, FileReader and FileWriter.

Java Stream Classes Hierarchy

Java Stream Classes

Byte Character
Stream Stream
Classes Classes

Input Stream Output Stream Reader Writer


Classes Classes Classes Classes

FileInputStrea FileOutputStre FileRead FileWrit


m Classes am Classes er er
Classes Classes

Byte Stream Classes


 Byte stream classes have been designed to provide functional features for creating and
manipulating streams and files for reading and writing bytes. Since the streams are
unidirectional, they can transmit bytes in only one direction and therefore, Java
provides two kinds of byte steam classes: Input stream classes and output stream
classes.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyBytes {


public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("C:\\Users\\Harendra\\Desktop\\test1.txt");
out = new FileOutputStream("C:\\Users\\Harendra\\Desktop\\test.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}

Character Stream Classes


 Reader stream classes:
 Reader stream classes are designed to read character from the files.
 Reader class is the base class for all other classes in this group.
 FileReader class is the sub-class for the Reader class.
 Writer Stream classes:
 Writer stream classes are designed to perform all output operations on files. Only
difference is that while output stream classes are designed to write bytes, the
writer stream classes are designed to write characters.
FileWriter class is the sub-class for the Writer Class.

Implementation of Character Stream classes


import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class CopyCharacters {


public static void main(String[] args) throws IOException {

FileReader inputStream = null;


FileWriter outputStream = null;

try {
inputStream = new FileReader("C:\\Users\\haren\\Desktop\\test.txt");
outputStream = new FileWriter("C:\\Users\\haren\\Desktop\\test1.txt");

int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
}
finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
public class CopyCharacters {
public static void main(String[] args) throws IOException {
BufferedReader inputStream = null;
BufferedWriter outputStream = null;
try {
inputStream = new BufferedReader(new
FileReader("C:\\Users\\haren\\Desktop\\test.txt"));
outputStream = new BufferedWriter(new
FileWriter("C:\\Users\\haren\\Desktop\\test1.txt"));
int c;
while ((c = inputStream.read()) != -1) {
outputStream.write(c);
}
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
}
}

Random Access File Class


 So far we have studied, the files that can be used either for ―read only‖ or for ―write
only‖ operations and not for both operation simultaneously.
 These files are read or written only sequentially and therefore are known as sequential
files.
 Here, RandomAccessFile class supported by the Java.io package allows us to create
files that can be used for reading and writing data with random access.
 A file can be created and opened for random access by giving a mode string as a
parameter to the constructor when we open the file. We can use one of the following
two mode strings;
 ―r‖ for read only
 ―rw‖ for reading and writing.

Read From a File


import java.io.File;
import java.util.Scanner;

public class ReadFile {


private Scanner x;
public void OpenFile(){
try{
x=new Scanner(new File("C:\\Users\\haren\\Desktop\\Harendra.txt"));
}
catch(Exception e){
System.out.println("Could not find the file");
}
}
public void ReadFile(){
while(x.hasNext()){
String a = x.next();
String b = x.next();
String c = x.next();
System.out.println(a+" "+ b+" " + c);
}
}
public void CloseFile(){
x.close();
}
}

Random Access from a File


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

try{
RandomAccessFile file = new
RandomAccessFile("C:\\Users\\haren\\Desktop\\test.txt","rw");
//Writing to the file
file.writeChars("X");
file.writeInt(100);
file.writeDouble(3.1424);
file.seek(0);

//Reading from the file


System.out.println(file.readChar());
System.out.println(file.readInt());
System.out.println(file.readDouble());
file.seek(2); //got to the second line
System.out.println(file.readInt());
//go to the end and append false to the file
file.seek(file.length());
file.writeBoolean(false);
file.seek(4);
System.out.println(file.readBoolean());
file.close();
}
catch(IOException ex){
System.out.println(ex);
}
}
}

public class ReadFileMain {


public static void main(String[] args) {
ReadFile file = new ReadFile();
file.OpenFile();
file.ReadFile();
file.CloseFile();
}
}

Reading and Writing Objects:

Java Object Serialization:

Before reading and writing an object to any file, first we need to understand about the
Serialization. It is a process of converting objects into writable byte stream. Once converted into a
byte stream, these objects can be written to a file. A java object is a serializable if its class or any
superclasses implement the java.io.Serializable interface.

Writing and Reading objects in java


The objects can be converted int byte stream using java.io.ObjectOutputStream class. In
order to enable writing of objects into a file it‘s necessary that the concerned class must
implements Serialiazable interface.
For serializing the object, we call the writeObject() method ObjectOutputStream, and for
deserialization we call the readObject() method of ObjectInputStream class.
We must have to implement the Serializable interface for serializing the object.

Example:
import java.io.Serializable;

public class Student implements Serializable {


String name;
int age;
String gender;
Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}

public String toString() {


return "Name: " + name + ", Age: " + age + ", Gender: " + gender;
}
}

Writing objects to a file and reading from a file


import java.io.*;

public class WriteToFile {


public static void main(String[] args) {
Student s1 = new Student("harendra", 18, "Male");
Student s2 = new Student("Surendra", 20, "Male");
File file = new File("harendra.txt");
try {
FileOutputStream f = new FileOutputStream(file);
ObjectOutputStream o = new ObjectOutputStream(f);

// writing objects to a file


o.writeObject(s1);
o.writeObject(s2);
o.close();
f.close();
System.out.println("Objects written to file successfully");
// reading objects from a file
FileInputStream fi = new FileInputStream(file);
ObjectInputStream oi = new ObjectInputStream(fi);

// Read objects
Student st1 = (Student) oi.readObject();
Student st2 = (Student) oi.readObject();

System.out.println("Student 1 -" + st1.toString());


System.out.println("Student 2 -" + st2.toString());
fi.close();
oi.close();
} catch (Exception ex) {
}
}
}
Deserialization
Deserialization is the process of reconstructing the object from the serialized state. It is
the reverse operation of serialization. Let's see an example where we are reading the data
from a deserialized object.
Example:
import java.io.*;

class deseriazable {
public static void main(String args[]) {
try {
// Creating stream to read the object
ObjectInputStream in = new ObjectInputStream(new FileInputStream("harendra.t
xt"));
Student s = (Student) in.readObject();//deserialization
// printing the data of the serialized object
System.out.println(s.name + " " + s.age + " " + s.gender);
// closing the stream
in.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Unit 9: Understanding Core Packages [3 hours]
Using java.lang Package: java.lang.Math, Wrapper classes and associated methods
(Number, Double, Float; Integer, Byte; Short, Long; Character, Boolean); Using
java.util package: Core classes (Vector, Stack, Dictionary, Hashtable, Enumerations,
Random Number Generation).

Using java.lang package:


The package java.lang has so many classes such as Math, Number, Double, Float,
Integer, Thread, Character, etc.

java.lang.Math:
The java.lang.Math class contains methods for performing basic numeric operations
such as the elementary exponential, logarithm, square root, and trigonometric functions.

Java Math class provides several methods to work on math calculations like min(),
max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

Example:
public class MathPackageDemo{
public static void main(String[] args){
double x = 28;
double y = 4;
System.out.println("Maximum number of x and y is: " +Math.max(x, y));
System.out.println("Square root of y is: " + Math.sqrt(y));
System.out.println("Power of x and y is: " + Math.pow(x, y));
System.out.println("Logarithm of x is: " + Math.log(x));
System.out.println("Logarithm of y is: " + Math.log(y));
System.out.println("log10 of x is: " + Math.log10(x));
System.out.println("log10 of y is: " + Math.log10(y));

// return the log of x + 1


System.out.println("log1p of x is: " +Math.log1p(x));
// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));
// return (a power of 2)-1
System.out.println("expm1 of a is: " +Math.expm1(x));

int a=30;
// converting values to radian
double b = Math.toRadians(a);
// return the trigonometric sine of a
System.out.println("Sine value of a is: " +Math.sin(a));
// return the trigonometric cosine value of a
System.out.println("Cosine value of a is: " +Math.cos(a));
// return the trigonometric tangent value of a
System.out.println("Tangent value of a is: " +Math.tan(a));
// return the trigonometric arc sine of a
System.out.println("Sine value of a is: " +Math.asin(a));
// return the trigonometric arc cosine value of a
System.out.println("Cosine value of a is: " +Math.acos(a));
// return the trigonometric arc tangent value of a
System.out.println("Tangent value of a is: " +Math.atan(a));
// return the hyperbolic sine of a
System.out.println("Sine value of a is: " +Math.sinh(a));
// return the hyperbolic cosine value of a
System.out.println("Cosine value of a is: " +Math.cosh(a));
// return the hyperbolic tangent value of a
System.out.println("Tangent value of a is: " +Math.tanh(a));
}
}

Wrapper classes and associated methods (Number, Double, Float; Integer, Byte; Short,
Long; Character, Boolean);

The wrapper class in Java provides the mechanism to convert primitive into object and
object into primitive.

Primitive Type Wrapper class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Autoboxing

The automatic conversion of primitive data type into its corresponding wrapper class is
known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to
Long, float to Float, boolean to Boolean, double to Double, and short to Short.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert
the primitive into objects.

public class WrapperExample3{


public static void main(String args[]){
byte b=10;
short s=20;
int i=30;
long l=40;
float f=50.0F;
double d=60.0D;
char c='a';
boolean b2=true;

//Autoboxing: Converting primitives into objects


Byte byteobj=b;
Short shortobj=s;
Integer intobj=i;
Long longobj=l;
Float floatobj=f;
Double doubleobj=d;
Character charobj=c;
Boolean boolobj=b2;

//Printing objects
System.out.println("---Printing object values---");
System.out.println("Byte object: "+byteobj);
System.out.println("Short object: "+shortobj);
System.out.println("Integer object: "+intobj);
System.out.println("Long object: "+longobj);
System.out.println("Float object: "+floatobj);
System.out.println("Double object: "+doubleobj);
System.out.println("Character object: "+charobj);
System.out.println("Boolean object: "+boolobj);

//Unboxing: Converting Objects to Primitives


byte bytevalue=byteobj; //or we can use byteobj.byteValue();
short shortvalue=shortobj; //or we can use shortobj.shortValue();
int intvalue=intobj; //or we can use intobj.intValue();
long longvalue=longobj;
float floatvalue=floatobj;
double doublevalue=doubleobj;
char charvalue=charobj;
boolean boolvalue=boolobj;

//Printing primitives
System.out.println("---Printing primitive values---");
System.out.println("byte value: "+bytevalue);
System.out.println("short value: "+shortvalue);
System.out.println("int value: "+intvalue);
System.out.println("long value: "+longvalue);
System.out.println("float value: "+floatvalue);
System.out.println("double value: "+doublevalue);
System.out.println("char value: "+charvalue);
System.out.println("boolean value: "+boolvalue);
}}

Methods used to convert Numbers to String

Method calling Conversion Action


str = Integer.toString() Primitive integer to String
str = Float.toString() Primitive float to String
str = Double.toString() Primitive double to String
str = Long.toString() Primitive long to String

public class WrapperClasses {


public static void main(String[] args) {
int number1 = 1234;
int number2 = 3456;
String concatint = Integer.toString(number1) + Integer.toString(number2);
System.out.println(concatint);
//similarly check others too
}
}

Methods used to convert String objects to Numberic objects:

Method calling Conversion Action


intval = Integer.valueOf(str) Converts string to Integer object
longval = Long.valueOf(str) Converts string to Long object
doubleval = Double.valueOf(str) Converts string to Double object
floatval = Float.valueOf(str) Converts string to Float object

public class WrapperClasses {


public static void main(String[] args) {
String number1 = "1234";
String number2 = "1234";
int intsum = Integer.valueOf(number1) + Integer.valueOf(number2);
Long longsum = Long.valueOf(number1) + Long.valueOf(number2);
Double doublesum = Double.valueOf(number1) + Double.valueOf(number2);
Float floatsum = Float.valueOf(number1) + Float.valueOf(number2);
System.out.println(intsum);
System.out.println(longsum);
System.out.println(floatsum);
System.out.println(doublesum);
}
}

Methods converting Numeric Strings to Primitive numbers

Method calling Conversion Action


int val = Integer.parseInt(str) Converts string to primitive integer
long val = Long. parseLong(str) Converts string to primitive long
double val = Double.valueOf(str) Converts string to primitive double
float val = Float.valueOf(str) Converts string to primitive float

public class WrapperClasses {


public static void main(String[] args) {
String number1 = "1234";
String number2 = "3456";
int add = Integer.parseInt(number1) + Integer.parseInt(number2);
System.out.println(add);
}//similarly please do check for other parsing methods
}

Using java.util package: Core classes (Vector, Stack, Dictionary, Hashtable,


Enumerations, Random Number Generation).

Vector:
Vector is used to generic dynamic array that can hold objects of any type and any
number. Unlike array, the objects do not have to be homogenous. Vectors are created like
arrays as follows;
Vector intvect = new Vector();//declaring vector array without size
Vector intvect = new Vector(5);//declaring vector array with size

Advantages of vector over array;


1. Vectors can store objects.
2. Vectors can be used to store list of objects that may vary in size.
3. We can add and delete objects from the list as and when needed.

Important Vector Methods:


Method Call Task performed
list.addElement(item) Add item to the end of the list.
list.elementAt(10) Gives the name of the 10th objects.
list.size() Returns the number of objects
list.removeElement(item) Remove the specified item from the list
list.removeElementAt(n) Remove the item stored in the nth position
of the list
list.removeAllElement() Removes all elements from vector list
list.copyInto(array) Copies all items from vector list to an array
list.insertElementAt(item,n) Inserts item at nth index or position
list.capacity() Returns total capacity; by default 10,
otherwise declared size in new Vector(n);
list.containsAll(Collection c) Returns true if if the vector contains all the
elements specified in the collection.
list.get(int index) Returns the element from specified index
list.setElementAt(Object e, int index) Insert element at specified index same as
insertElementAt(Object o, int index)
list.setSize() Specifying new size at any part of the
program.
list.toString() Returns the String representation of a
vector list.

Implementation of all methods used in Vector:


import java.util.Vector;

public class VectorImplementation {


public static void main(String[] args) {
Vector<String> list = new Vector<String>(30);
list.add("Harendra");
list.add("Narendra");
list.add("Ram");
list.add("Shyam");
System.out.println("Intial Vector Array is: " + list);
// getting total capacity
System.out.println("The capacity of a vector is: " + list.capacity());
// getting the current size
System.out.println("The size of a vector array or list is: " + list.size());
// searching the element
boolean yesno = list.contains("Harendra");
System.out.println("Is Harendra contained in current list?: " + yesno);
// containsAll using Collection
Vector<String> coll = new Vector<String>();
coll.add("Raju");
coll.add("Ram");
boolean find = list.containsAll(coll);
System.out.println("All elements of coll present in list? " + find);
// get method to return the element from specified index
System.out.println("The element at 3rd position is :" + list.get(3));
// adding new element
list.addElement("Suresh");
list.addElement("Ramesh");
System.out.println("Modified Vector Array is: " + list);
System.out.println("The size of a modified vector array or list is: " + list.size());
// accessing the list item
System.out.println("The sixth item is " + list.elementAt(5));
// removing specified item or element from vector list
list.removeElement("Ram");
System.out.println("Modified Vector Array after removing is: " + list);
System.out.println("The size of a modified vector array or list is: " + list.size());
// removing item or element from vector nth index
list.removeElementAt(2);
System.out.println("Modified Vector Array after removeElementAt(2) is: " + list);
System.out.println("The size of a modified vector array or list is: " + list.size());
// inserting element at nth index
list.insertElementAt("Ghanshyam", 3);
list.insertElementAt("Sita", 4);
list.insertElementAt("Gita", 2);
System.out.println("Modified Vector Array after insertElementAt() is: " + list);
System.out.println("The size of a modified vector array or list is: " + list.size());
// copying vector list to an array
String[] names = new String[list.size()];
list.copyInto(names);
System.out.println("The array items are:");
for (String item : names) {
System.out.print(item + " ");
}
// remove all items of a vector list
list.removeAllElements();
System.out.println("\nThe final vector list is empty: " + list);
}
}

Output:
Intial Vector Array is: [Harendra, Narendra, Ram, Shyam]
The capacity of a vector is: 30
The size of a vector array or list is: 4
Is Harendra contained in current list?: true
All elements of coll present in list? false
The element at 3rd position is :Shyam
Modified Vector Array is: [Harendra, Narendra, Ram, Shyam, Suresh, Ramesh]
The size of a modified vector array or list is: 6
The sixth item is Ramesh
Modified Vector Array after removing is: [Harendra, Narendra, Shyam, Suresh,
Ramesh]
The size of a modified vector array or list is: 5
Modified Vector Array after removeElementAt(2) is: [Harendra, Narendra, Suresh,
Ramesh]
The size of a modified vector array or list is: 4
Modified Vector Array after insertElementAt() is: [Harendra, Narendra, Gita, Suresh,
Ghanshyam, Sita, Ramesh]
The size of a modified vector array or list is: 7
The array items are:
Harendra Narendra Gita Suresh Ghanshyam Sita Ramesh
The final vector list is empty: []
Stack:
The Stack class inherits or extends Vector class. Additionally, stack class contain some
methods to perform operations such as pop, push, peek and search.
Methods used in stack class implementation;
Methods Descriptions
st.empty() Returns true if stack is empty
st.peek() Returns the element at the top of stack
st.pop() Removes the element from top of stack and
return the removed element
st.push() Adds an item to the top of the stack

Implementation:
import java.util.Stack;

public class stack {


public static void main(String[] args) {
Stack<String> st = new Stack<String>();
st.push("Java");
st.push("is");
st.push("an");
st.push("object");
st.push("oriented");
st.push("programming");
st.push("language");
System.out.println("The element in the stack are: " + st);
System.out.println("Element at Top of Stack: " + st.peek());
System.out.println("The element popped out of the Stack(Top of Stack) is: " + st.pop(
));
System.out.println("The element in the stack after pop operation are: " + st);
System.out.println("The result of searching object: " + st.search("object"));
}
}

Output:
The element in the stack are: [Java, is, an, object, oriented, programming, language]
Element at Top of Stack: language
The element popped out of the Stack(Top of Stack) is: language
The element in the stack after pop operation are: [Java, is, an, object, oriented,
programming]
The result of searching object: 3

Dictionary, HashTable and Enumeration:


Dictionary is an abstract class that represents a key/value storage repository and operates
much like Map.
Given a key and value, you can store the value in a Dictionary object. Once the value is
stored, you can retrieve it by using its key. Thus, like a map, a dictionary can be thought
of as a list of key/value pairs.
The abstract methods defined by Dictionary are listed below −
Sr.No. Method & Description
1 Enumeration elements( )
Returns an enumeration of the values contained in the dictionary.
2 Object get(Object key)
Returns the object that contains the value associated with the key. If the key is
not in the dictionary, a null object is returned.
3 boolean isEmpty( )
Returns true if the dictionary is empty, and returns false if it contains at least
one key.
4 Enumeration keys( )
Returns an enumeration of the keys contained in the dictionary.
5 Object put(Object key, Object value)
Inserts a key and its value into the dictionary. Returns null if the key is not
already in the dictionary; returns the previous value associated with the key if
the key is already in the dictionary.
6 Object remove(Object key)
Removes the key and its value. Returns the value associated with the key. If the
key is not in the dictionary, a null is returned.
7 int size( )
Returns the number of entries in the dictionary.

Implementation:
import java.util.*;

public class DictionaryHAshTableEnumeration {


public static void main(String[] args) {
Dictionary<String, String> dictionary = new Hashtable<String, String>();

// put method
dictionary.put("Apple", "A fruit");
dictionary.put("Ball", "A round shaped toy");
dictionary.put("Car", "A four wheeler vehicle designed to accomodate usually four p
eople");
dictionary.put("Dog", "An animal with four legs and one tail");

// get method
System.out.println("\nApple: " + dictionary.get("Apple"));
System.out.println("Dog: " + dictionary.get("Dog"));
System.out.println("Elephant: " + dictionary.get("Elephant"));
System.out.println();

// elements method
for (Enumeration<String> i = dictionary.elements(); i.hasMoreElements();) {
System.out.println("Values contained in Dictionary : " + i.nextElement());
}
System.out.println();

// keys method :
for (Enumeration<String> k = dictionary.keys(); k.hasMoreElements();) {
System.out.println("Keys contianed in Dictionary : " + k.nextElement());
}

// isEmpty method
System.out.println("\nThe dictionary is empty? " + dictionary.isEmpty());

// remove method :
dictionary.remove("Dog");

// Checking if the value is removed or not


System.out.println("\nDog: " + dictionary.get("Dog"));

// size method
System.out.println("\nSize of Dictionary : " + dictionary.size());
}
}

Output:
Apple: A fruit
Dog: An animal with four legs and one tail
Elephant: null

Values contained in Dictionary : An animal with four legs and one tail
Values contained in Dictionary : A round shaped toy
Values contained in Dictionary : A fruit
Values contained in Dictionary : A four wheeler vehicle designed to accomodate usually
four people

Keys contianed in Dictionary : Dog


Keys contianed in Dictionary : Ball
Keys contianed in Dictionary : Apple
Keys contianed in Dictionary : Car

The dictionary is empty? false

Dog: null

Size of Dictionary : 3
Random Number Generation:
Random numbers within a specific range of type integer, float, double, long, and boolean
can be generated in Java.

Implementation:
import java.util.Random;

public class RandomNumGenerator {


public static void main(String[] args) {
Random rand = new Random(); //instance of random class
int defaultint = rand.nextInt();
//generate random values from 0-24
int int_random = rand.nextInt(25);
double double_random=rand.nextDouble();
float float_random=rand.nextFloat();

System.out.println("Default Random integer " + defaultint);


System.out.println("Random integer value from 0 to" + int_random);
System.out.println("Random float value between 0.0 and 1.0 : "+float_random);
System.out.println("Random double value between 0.0 and 1.0 : "+double_random);

}
}

Output:
Default Random integer 1458303222
Random integer value from 0 to24
Random float value between 0.0 and 1.0 : 0.5172497
Random double value between 0.0 and 1.0 : 0.10373183149200027
Unit 10: Holding Collection of Data [3 hours]
Arrays and Collection Classes/Interface, Map/List/Set implementation: Map Interface,
List Interface, Set Interface.

The collection framework which is contained in the java.util package is one of Java‘s most
powerful sub-systems. The collection framework contains many interfaces such as Collection,
Map, and Iterator. Other interfaces of the framework extend these interfaces. The interfaces List
and Set are the sub-interfaces of the Collection interface. The SortedMap interface is the sub-
interface of the Map interface.
Map , List and Set can be cleary shown in picture below;

Iterator
Collection

ListIterator
List

Queue

Set

SortedSet
Map

SortedMap

Figure: Interfaces contained in Collection Framework

Collection: collection of elements.


List: sequences of elements.
Set: collection of unique elements.
Map: collection of key-value pairs, which must be unique.

Methods defined in Collection Interface

Methods Description
add(Object o) Returns true if object is added to the specified collection
addAll(Collection c) Return true if entire object in the collection is added to the
specified collection.
clear() Removes all elements from the collection
contains(Object o) Returns true if the collection contains specified element
containsAll(Collection c) Returns true if the collection contains all the elements in the
specified collection
equals(Object o) Returns true if the specified object matches to the object in the
collection
hashCode() Return the hash code for the collection
isEmpty() Returns if the collection is empty
iterator() Returns iterator over the elements in the collection
remove(Object o) Removes an object from the collection.
removeAll(Collection c) Returns true if all the elements in collection c is removed from the
specified collectiomn.
retainAll(Collection c) Returns true if all the elements in collection c is retained from the
specified collectiomn
size() Returns the number of elements in the collection
toArray() Returns an array containing all of the elements in the collection
toArray (Object[] a) Returns an array of object if the array contains all the elements in
the specified collection

The set Interface:

The set interface extends the Collection interface and it contains all the methods that are inherited
from the collection interface. The set interface does not allow the duplicate entry in a collection
so, add() method returns false if we are going to add duplicate element in a collection.

The List Interface


The List Interface contains ordered sequence of elements available in a collection. It allows
duplicate elements in the List. The List Interface inherits the methods of collection interface.
Additionally, List Interface has the following methods given below;

Methods defined in List Interface


Methods Descriptions
add(int index, Object o) Adds element o in the specified index of the list
addAll(int index, Collection c) Adds all the elements of collection c in the specified index of
the list
get(int index) Returns the element available in the specified index of a list.
indexOf(Object o) Returns the index of object o in the list. If there are more
occurences of same object, it will return the first object‘s
index. If not available it returns -1(unsuccessfull search).
lastIndexOf(Object o) Returns the last index of the object o in the list. If not found it
returns -1.
listIterator() Returns the list iterator of the elements.
listIterator(int index) Returns a list iterator of the elements starting from the
specified index of the list
remove(int index) Removes the element at the specified at the specified index of
the list.
set(int index, Object o) Replaces the element in the specified index of the list with the
specified element.
subList(int start, int end) Returns the elements available from the specified startindex to
the endindex

The Map Interface:


The map interface maps unique key elements to their values. The Map Interface allows us to view
the elements of a collection as set of keys, collection of values and mapping of key-value pairs.

Methods defined in Map Interface


Methods Descriptions
clear() Removes all the mappings from the Map
containsKey(Object key) Returns true if a map contains mapping for the specified key.
containsValue(Object value) Returns true if a specified value maps with one or more key in
a map interface.
entrySet() Returns the key-value pair contained in this map.
equals(Object o) Returns true if the specifies value maps with one or more key in
a map interface
get(Object key) Returns the value which is mapped to the specified key.
isEmpty() Returns true if a map contains no key-value mapping
keySet() Returns the keys in a map. If we remove a key from a map, the
corresponding value will also be removed.
put(Object key, Object value) Maps the specified key with specified value
putAll(Map t) Copied all the key value pair from the specified Map to the
current Map we are working on it.
remove(Object key) Removes the specified key from the Map
size() Returns the number of key-valu pairs mappings available in the
Map.

Collection Classes: ArrayList, LinkedList, HashSet and TreeSet; Accessing


Collections/Use of an Iterator, Comparator.

ArrayList:
The ArrayList class extends the AbstractList class and implements Interfaces such as
List, Cloneable and Serializable. Using the ArrayList class, we can use dynamic array in
java applications. The dynamic array is an array in which the array size is not fixed in
advance. Therefore, we can change the size of an array at run time using ArrayList class.
Every instance of arrayList class is allowed to store a set of elements in the List. The
capacity increases automatically if we add elements to the list.
Constructors used in ArrayList are;
ArrayList(): default constructor
ArrayList(Collection c): Creates a list to which the elements of the specified collection
are added.
ArrayList(int capacity): Creates empty list. The capacity of the list is initialized to the
specified value.
The ArrayList class inherits the methods from the List interface. Te elements of an array
can be accessed directly using get() and set() methods. The add() method is used to add
elements to the array list and remove() method is used to remove the elements from the
array list.

Example:
import java.util.ArrayList;

public class Arraylistdemo {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();// genertic type list
System.out.println("Initial size of an array: " + list.size());
//adding elements sequentially
list.add("Ram");
list.add("shyam");
list.add("harendra");
list.add("hitesh");
System.out.println("Size of an array after elements are added: " + list.size());
System.out.println("Elements of list are: " + list);
// adding element at specified index
list.add(3, "Rajendra");
list.add(0, "Manish");
System.out.println("Elements of modified list are: " + list);
// accessing the element at any specified index
System.out.println("The item at index 3 is: " + list.get(2));
// removing the element from specified index
list.remove(0);
// remove specified element
list.remove("Rajendra");
System.out.println("List after removing some elements are: " + list);
}
}

Output:
Initial size of an array: 0
Size of an array after elements are added: 4
Elements of list are: [Ram, shyam, harendra, hitesh]
Elements of modified list are: [Manish, Ram, shyam, harendra, Rajendra, hitesh]
The item at index 3 is: shyam
List after removing some elements are: [Ram, shyam, harendra, hitesh]

LinkedList:
The LinkedList class extends the AbstractSequentialList class and implements the List
interface. This class supports the methods shown below;
These methods allow us to insert and remove elements in a list. We can use the list as a
stack, queue and doubly linked list. The constructor of LinkedList are;
LinkedList()
LinkedList(Collection c)

Methods supported by LinkedList Class


Methods Description
addFirst(Object obj) Adds the specified element to the first
position of the list
addFirst(Object obj) Adds the specified element to the last
position of the list
getFirst() Used to get the first element from the list
getLast() Used to get the last element from the list
removeFirst(Object obj) Used to remove the first element from the
list
removeLast(Object obj) Used to remove the last element from the
list

Example:
import java.util.LinkedList;

public class LinkedListDemo {


public static void main(String[] args) {
LinkedList<String> animals = new LinkedList<String>();
animals.add("Tiger");
animals.add("Lion");
animals.add("Elephant");
System.out.println("Initial list is: " + animals);
// adding element to the first position
animals.addFirst("Mouse");
System.out.println("The list after adding to first position is: " + animals);
// adding element in the last position
animals.addLast("Fox");
System.out.println("The list after adding to last position is: " + animals);
// retrieving element from the first position
System.out.println("The first element of the list is: " + animals.getFirst());
// retrieving element from the last position
System.out.println("The first element of the list is: " + animals.getLast());
// remove
// removing element from the first position
animals.removeFirst();
System.out.println("The list after removing from the first position is: " + animals);
// removing element from the last position
animals.removeLast();
System.out.println("The list after removing from the last position is: " + animals);
}
}
Output:
Initial list is: [Tiger, Lion, Elephant]
The list after adding to first position is: [Mouse, Tiger, Lion, Elephant]
The list after adding to last position is: [Mouse, Tiger, Lion, Elephant, Fox]
The first element of the list is: Mouse
The first element of the list is: Fox
The list after removing from the first position is: [Tiger, Lion, Elephant, Fox]
The list after removing from the last position is: [Tiger, Lion, Elephant]

HashSet:
The HashSet class extends the AbstractSet class and implements the Set interface. The
HashSet class is used to create a collection and store it in a hash table. Each collection
refers to a unique value called hash code. The hash code is used as an index to associate
with the object, which is stored in the hash table. This type of storing in a hash table is
called hashing. Constructors for HashSet are as follows;
HashSet()
HashSet(Collection c)
HashSet(int capacity)
HashSet(int capacity, float fillratio): Initializes capacity and fill ratio of the HashSet. The
value of fill ratio ranges from 0.0 to 1.0. This value is used to set the initial size of the
hash set. If the number of elements is greater than the capacity of the hash set, the size of
the hash set is expanded automically by multiplying the capacity with the fill ratio. The
default value of fill ratio is 0.75.

Example:
import java.util.HashSet;

public class hashsetdemo {


public static void main(String[] args) {
HashSet<String> planets = new HashSet<String>();
planets.add("Mars");
planets.add("Venus");
planets.add("Earth");
planets.add("Mars");
planets.add("Jupitor");
planets.add("Saturn");
planets.add("Uranus");
planets.add("Neptune");
planets.add("Pluto");
System.out.println("The elements in the HashSet are: " + planets);
boolean a = planets.contains("Earth");
System.out.println(a);
//remove
planets.remove("Pluto");
System.out.println("List after removing Pluto: "+planets);
}
}

Output:
The elements in the HashSet are: [Earth, Mars, Neptune, Saturn, Venus, Uranus, Jupitor,
Pluto]
true
List after removing Pluto: [Earth, Mars, Neptune, Saturn, Venus, Uranus, Jupitor]

TreeSet:

The TreeSet class implements the Set interface. The sorted elements are stored in a Tree
structure. This class allows us to retrieve or access the elements in less time. Constructors
are shown below;
TreeSet()
TreeSet(Collection c)
TreeSet(Comparator co): Build the TreeSet based on the comparator.
TreeSet(SortedSet s): Builds a TreeSet which contains elements in the specified order.

Example:
import java.util.TreeSet;

public class TreeSetDemo {


public static void main(String[] args) {
TreeSet<String> planets = new TreeSet<String>();
planets.add("Mars");
planets.add("Venus");
planets.add("Earth");
planets.add("Mars");
planets.add("Jupitor");
planets.add("Saturn");
planets.add("Uranus");
planets.add("Neptune");
planets.add("Pluto");
System.out.println("The elements in the TreeSet are: " + planets);
// searching element in a TreeSet
boolean a = planets.contains("Earth");
System.out.println(a);
// remove
planets.remove("Pluto");
System.out.println("List after removing Pluto: " + planets);
planets.add("Sun");
System.out.println("List after adding Sun: " + planets);
//removing all elements at once
planets.clear();
System.out.println("TreeSet after clearing : " + planets);
}
}

Output:
The elements in the TreeSet are: [Earth, Jupitor, Mars, Neptune, Pluto, Saturn, Uranus,
Venus]
true
List after removing Pluto: [Earth, Jupitor, Mars, Neptune, Saturn, Uranus, Venus]
List after adding Sun: [Earth, Jupitor, Mars, Neptune,
Saturn, Sun, Uranus, Venus]
TreeSet after clearing : []

Iterator and Comparator:

Java Iterator

An Iterator is an object that can be used to loop through collections,


like ArrayList and HashSet. It is called an "iterator" because "iterating" is the technical
term for looping.

To use an Iterator, you must import it from the java.util package.

Example:
import java.util.ArrayList;
import java.util.Iterator;

public class Main {


public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(12);
numbers.add(8);
numbers.add(2);
numbers.add(23);
Iterator<Integer> it = numbers.iterator();
while(it.hasNext()) {
Integer i = it.next();
if(i > 10) {
it.remove();
}
}
System.out.println(numbers);
}
}
Output:
[8, 2]

Java Comparator:
Java Comparator interface is used to order the objects of a user-defined class.
This interface is found in java.util package and contains 2 methods compare(Object
obj1,Object obj2) and equals(Object element).
It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any
data member, for example, rollno, name, age or anything else.

Methods used in Comparator Interface


Method Description
public int compare(Object obj1, It compares the first object with the second object.
Object obj2)
public boolean equals(Object obj) It is used to compare the current object with the
specified object.

public void sort(List list, Comparator c): is used to sort the elements of List by the
given Comparator.

Example:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class Student {
int rollno;
String name;
int age;

Student(int rollno, String name, int age) {


this.rollno = rollno;
this.name = name;
this.age = age;
}
}

class NameComparator implements Comparator<Student> {


public int compare(Student s1, Student s2) {
return s1.name.compareTo(s2.name);
}
}

class AgeComparator implements Comparator<Student> {


public int compare(Student s1, Student s2) {
if (s1.age == s2.age)
return 0;
else if (s1.age > s2.age)
return 1;
else
return -1;
}
}

public class JavaComparator {


public static void main(String[] args) {
ArrayList<Student> al = new ArrayList<Student>();
al.add(new Student(101, "Harendra", 32));
al.add(new Student(106, "Narendra", 40));
al.add(new Student(105, "Birendra", 35));
al.add(new Student(104, "Dipendra", 25));
al.add(new Student(104, "Surendra", 30));

System.out.println("Sorting by Name");

Collections.sort(al, new NameComparator());


for (Student st : al) {
System.out.println(st.rollno + " " + st.name + " " + st.age);
}
System.out.println("Sorting by age");

Collections.sort(al, new AgeComparator());


for (Student st : al) {
System.out.println(st.rollno + " " + st.name + " " + st.age);
}
}
}

Output:
Sorting by Name
105 Birendra 35
104 Dipendra 25
101 Harendra 32
104 Harendra 30
106 Narendra 40
Sorting by age
104 Dipendra 25
104 Harendra 30
101 Harendra 32
105 Birendra 35
106 Narendra 40
Unit 11: Java Applications [8 hours]
About AWT and Swing, About JFrame (a top level window in swing), swing components
(JLabel, About text components like JTextField, JButton, Event Handling in Swing
Applications, Layout Management using FlowLayout, Border Layout, Grid Layout, Using
JPanel, Choice Components like JCheckBox, JRadioButton, Borders Components,
JComboBox and its events, JList and its events with MVC patterns, Key and Mouse Event
Handling, Menus in Swing, JTextArea, Dialog boxes in Swing, JTable for Displaying data
in tabular form, MDI using JDesktopPane and JInternalFrame, Using IDE like netbeans:
JBuilder for building java applications using Drag and Drop), Adapter classes.

Graphical User Interface(GUI)

GUI provides a user friendly mechanism for interacting with an application. The
components used in any applications, Such as Jframe, TextFields, TextAreas,
Radiobuttons, Checkboxes, ComboBoxes, etc. are the examples of GUI components.

Concept of AWT:

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.
Java AWT components are platform-dependent i.e. components are displayed according
to the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

The hierarchy of Java AWT classes are given below.


Figure 1: AWT Hierarchy

Example:

import java.awt.*; //using all classes contained in awt


class First extends Frame{ // inherit all the properties of awt Frame
First(){
Button b=new Button("click me"); // Button is created
b.setBounds(30,100,80,30); // setting button position in window
(i.e.Frame)
add(b); //adding button into frame
setSize(300,300);
//frame size 300 width and 300 height
setLayout(null); //no layout manager
setVisible(true);
//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First(); //class object creation or instantiation
}// end constructor
} //end class
Concept of Swing:

 Several Swing GUI components from package javax.swing are used to build java
GUIs. Swing is known as lightweight UI because it uses its own look and feel in
every OS unlike AWT.
 Some basic GUI components are as follows;
 JLabel: displays ineditable text or icons.
 JTextField: enables user to enter data.
 JButton: triggers an event when clicked.
 JCheckBox: specifies an option that can be selected.
 JComboBox: provides dropdown list.
 JList: Multiple items can be selected from the JList.
 JPanel: provides an area in which components can be placed and organized.

Hierarchy of Swing Components

Object Jlabel

Component JList

JTable
Container JComponent
JTextArea

JComboBox
Window Panel

JSlider
Applet

Frame Dialog JMenu

JButton

JFrame JDialog JApplet JPanel

Figure 2: Swing Hierarchy


Swing vs awt

 There are actually two sets of GUI components in java. Before swing was
introduced Java GUIs are built with components from Abstract Window
Toolkit(awt) in package java.awt.
 When a Java application with awt GUI executes on different Java platforms, the
application‘s GUI components display differently on each platform.
 E.g. But using Swing the component button in windows OS will have the same
appearance as the buttons in other windows applications and the component
button in macintosh os will have the same appearance of button as in other
macintosh applications.
 Using swing GUI components there is a uniform look and feel of components all
across the platforms.

Component and Container:


Conceptualy, container is a place where components are added. E.g. JFrame is a container
and components like JButton, JTextField, JPanel, etc are added. Components itself be a
container e.g. JPanel can contain other components such as JButton, JLabel, JTextArea,
etc.

Concept of Container and Components


import java.awt.Color;
import java.awt.Container;
import javax.swing.*;

public class MyJPanel {


public static void main(String[] args){
JFrame frame = new JFrame(); //object of jframe is created
frame.setVisible(true); //to show JFrame
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //to terminate
background running
frame.setBounds(100,100,500,300); //(x,y,width,height)
frame.setTitle("Harendra's Frame");
frame.setBackground(Color.blue);
frame.setLayout(null); //to make the size of the JFrame fixed

//Adding panel one to Frame


JPanel panel = new JPanel();
panel.setLayout(null);
panel.setBackground(Color.red);
panel.setBounds(0, 0, 250, 300);
frame.add(panel); // j panel is added into j frame (component
added to container)

//Adding panel two to Frame


JPanel panel2 = new JPanel(); //panel2 is created
panel2.setBackground(Color.yellow);//background color of panel2
panel2.setBounds(0, 0, 100, 250); //bound set of panel in jframe

panel.add(panel2); //one jpanel can be added into other jpanel


JButton btn = new JButton("Ok"); //button created
panel2.add(btn); //jbutton is added into jpanel2
}
}

Layout Management
Layout Manager:
 Layout Managers arrange the GUI component in a container for presentation
purposes.
 All layout managers implement the interface LayoutManager(in package
java.awt). Class Container‘s setLayout method takes an object that implements the
LayoutManager interface as an argument.
FlowLayout:
◦ Default for javax.swing.JPanel. Places the components sequentially (from
left to right) in the order they were added. It‘s also possible to specify the
order of the components by using the container method add, which takes a
component and an integer index position as argument.
BorderLayout:
◦ Default for JFrames. Arranges the components into five areas: NORTH,
SOUTH, EAST, WEST and CENTER.
GridLayout:
◦ Arranges the components into single row and column.

FlowLayout:
 FlowLayout is the simplest layout manager. GUI components are arranged on a
container from left to right in the order in which they are added to the container. It
is the default layout manager.
 When the edge of the container is reached, components continue to display on the
next line.
 Class FlowLayout allows GUI components to be left aligned, centered(default
one) and right aligned.
 FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
 FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
 FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

Simple Example:
import java.awt.*;
import javax.swing.*;

public class FlowLayoutDemo extends JFrame {

FlowLayoutDemo() {
setLayout(new FlowLayout());
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");

add(b1);//default placed at center


add(b2);
add(b3);
add(b4);
add(b5);

setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new FlowLayoutDemo();
}
}

BorderLayout :
 BorderLayout manager is the default layout manager for the JFrame.
 It arranges the components into five regions: NORTH, SOUTH, EAST, WEST
AND CENTER.
 NORTH corresponds to the top of the container, SOUTH corresponds to the
bottom, EAST corresponds to the right, WEST corresponds to the left.
 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.

Simple Example:
import java.awt.*;
import javax.swing.*;

public class BorderLayoutDemo extends JFrame {

BorderLayoutDemo() {
setLayout(new BorderLayout(5, 5));// vgap and hgap 5
JButton b1 = new JButton("NORTH");
JButton b2 = new JButton("SOUTH");
JButton b3 = new JButton("EAST");
JButton b4 = new JButton("WEST");
JButton b5 = new JButton("CENTER");

add(b1, BorderLayout.NORTH);
add(b2, BorderLayout.SOUTH);
add(b3, BorderLayout.EAST);
add(b4, BorderLayout.WEST);
add(b5, BorderLayout.CENTER);

setSize(300, 300);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new BorderLayoutDemo();
}
}

GridLayout
 GridLayout manager divides the container into a grid so that the components can
be placed in rows and columns.
 Every component in a GridLayout has the same width and height.
 Components are added to a GridLayout starting at the top-left cell of the grid and
proceeding left to right untill the row is full.
 And, the process continues left to right on the next row and so on.
 GridLayout(): creates a grid layout with one column per component in a row.
 GridLayout(int rows, int columns): creates a grid layout with the given rows
and columns but no gaps between the components.
 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.

Example:
import java.awt.*;
import javax.swing.*;

public class MyGridLayout extends JFrame {


GridLayout layout;

MyGridLayout() {
layout = new GridLayout(3, 3, 5, 5);// 3 by 3 grids and 5 hgap and vgap
setLayout(layout);
setTitle("Grid Layout");
setSize(300, 300);
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");
JButton b9 = new JButton("9");

add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
add(b6);
add(b7);
add(b8);
add(b9);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public static void main(String[] args) {


new MyGridLayout();
}
}

Text Input
Text Fields, Password Fields, Text Areas, Scroll Pane, Label and Labeling
Components.
 We are finally ready to start introducing the Swing user interface components. We
start with components that let a user input and edit text. You can use the
JTextField and JText-area components for gathering text input.
 A text field can accept only one line of text; a text area can accept multiple lines of
text.
 A JPasswordField accepts one line of text without showing the contents.
 Note: All three of these classes inherit from a class called JTextComponent. You
will not be able to construct a JTextComponent yourself because it is an abstract
class.
 The usual way to add a text field to a window is to add it to a panel or other
container:
 JPanel panel = new JPanel();
 JTextField textField = new JTextField("Default input", 20);
 panel.add(textField);
 This code adds a text field and initializes the text field by placing the string
"Default input‖ inside it. The second parameter of this constructor sets the
width. In this case, the width is 20 ―columns.‖
 One column is the expected width of one character in the font you are using for
the text.
 If you need to reset the number of columns at runtime, you can do that with the
setColumns method.
 TIP: After changing the size of a text box with the setColumns method, call the
revalidate method of the surrounding container.
 textField.setColumns(10);
 panel.revalidate();
 The revalidate method recomputes the size and layout of all components in a
container.
After you use the revalidate method, the layout manager resizes the container, and the
changed size of the text field will be visible.
 JTextField textField = new JTextField(20);
 You can change the content of the text field at any time by using the setText
method from the JTextComponent parent class mentioned in the previous section.
For example:
◦ textField.setText("Hello!");
◦ String text = textField.getText().trim();
◦ This method returns the exact text that the user typed. To trim any
extraneous leading and trailing spaces from the data in a text field, apply
the trim method to the return value of getText.
 To change the font in which the user text appears, use the setFont method.
void setFont(Font f)

Labels and Labeling Components

 Labels are components that hold text. They have no decorations (for example, no
boundaries). They also do not react to user input. You can use a label to identify
components.
 1. Construct a JLabel component with the correct text.
 2. Place it close enough to the component you want to identify so that the user can
see that the label identifies the correct component.
 The constructor for a JLabel lets you specify the initial text or icon, and
optionally, the alignment of the content. You use constants from the
SwingConstants interface to specify alignment. That interface defines a number of
useful constants such as LEFT, RIGHT, CENTER, NORTH, EAST, and so on.
The JLabel class is one of several Swing classes that implement this interface.
Therefore, you can specify a right-aligned label either as
◦ JLabel label = new JLabel("User name: ", SwingConstants.RIGHT);
 or
◦ JLabel label = new JLabel("User name: ", JLabel.RIGHT);
The setText and setIcon methods let you set the text and icon of the label at runtime.

javax.swing.Jlabel contains
 JLabel(String text)
 JLabel(Icon icon)
 JLabel(String text, int align)
 JLabel(String text, Icon icon, int align) constructs a label.
 String getText()
 void setText(String text)
 gets or sets the text of this label.
 Icon getIcon()
 void setIcon(Icon icon) gets or sets the icon of this label.
 Parameters: text The text in the label
icon The icon in the label
align One of the swingConstants constants
LEFT (default), CENTER,
or RIGHT.
Password Fields
 Password fields are a special kind of text field. The characters that the user
entered are not actually displayed.
 Instead, each typed character is represented by an echo character, typically an
asterisk (*).
 Swing supplies a JPasswordField class that implements such a text field.

javax.swing.JPasswordField contains
 JPasswordField(String text, int columns) constructs a new password field.
 void setEchoChar(char echo) sets the echo character for this password field. This
is advisory; a particular look and feel may insist on its own choice of echo
character. A value of 0 resets the echo character to the default.
 char[] getPassword() returns the text contained in this password field. For stronger
security, you should overwrite the content of the returned array after use. (The
password is not returned as a String because a string would stay in the virtual
machine until it is garbage-collected.)

Text Areas
 Sometimes, we need to collect user input that is more than one line long. As
mentioned earlier, we use the JTextArea component for this collection. When we
place a text area component in our program, we can enter any number of lines of
text, using the ENTER key to separate them.
 In the constructor for the JTextArea component, you specify the number of rows
and columns for the text area. For example,
 textArea = new JTextArea(8, 40); // 8 rows 40 columns each.
◦ textArea.setRows(10); textArea.setColumns(50); to change the number of
rows and columns respectively.
 If there is more text than the text area can display, then the remaining text is
simply wrapped.
textArea.setLineWrap(true); // long lines are wrapped

Implementation:
package TextInput;

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

class TextComponentFrame extends JFrame


{
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 300;
public TextComponentFrame()
{
setTitle("TextComponentTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

final JTextField textField = new JTextField();


final JPasswordField passwordField = new JPasswordField();

JPanel northPanel = new JPanel();


northPanel.setLayout(new GridLayout(2, 2));
northPanel.add(new JLabel("User name: ", SwingConstants.RIGHT));
northPanel.add(textField);
northPanel.add(new JLabel("Password: ", SwingConstants.RIGHT));
northPanel.add(passwordField);

add(northPanel, BorderLayout.NORTH);

final JTextArea textArea = new JTextArea(8, 40);


JScrollPane scrollPane = new JScrollPane(textArea);

add(scrollPane, BorderLayout.CENTER);

// add button to append text into the text area

JPanel southPanel = new JPanel();

JButton insertButton = new JButton("Insert");


southPanel.add(insertButton);

insertButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
textArea.append("User name: " + textField.getText() + " Password: "
+ new String(passwordField.getPassword()) + "\n");
}
});

add(southPanel, BorderLayout.SOUTH);

// add a text area with scrollbars


}
public static void main(String[] args) {
TextComponentFrame frame = new TextComponentFrame();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
}

Choice Components [ Checkboxes, Radiobuttons, Comboboxes, Borders, Sliders ]

Components providing the choice chosen from set of items, or choosing any one of the item or
choosing many items.

CheckBoxes:
 If you want to collect just a ―yes‖ or ―no‖ input, use a checkbox component.
Checkboxes automatically come with labels that identify them.
 The user usually checks the box by clicking inside it and turns off the check mark
by clicking inside the box again.
 To toggle the check mark, the user can also press the space bar when the focus is in the
checkbox.
 Checkboxes need a label next to them to identify their purpose. You give the label
text in the constructor.
o bold = new JCheckBox("Bold");
 You use the setSelected method to turn a checkbox on or off. For example:
o bold.setSelected(true);
 The isSelected method then retrieves the current state of each checkbox. It is false
if unchecked; true if checked.
 When the user clicks on a checkbox, this triggers an action event. As always, you
attach an action listener to the checkbox. In our program, the two checkboxes
share the same action listener.
o ActionListener listener = . . .
o bold.addActionListener(listener);
o italic.addActionListener(listener);
 The actionPerformed method queries the state of the bold and italic
checkboxes and sets the font of the panel to plain, bold, italic, or both
bold and italic.
Implementation:
package ChoiceComponents;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class CheckBoxFrame extends JFrame {


public static final int DEFAULT_WIDTH = 600;
public static final int DEFAULT_HEIGHT = 200;
private JLabel label;
private JCheckBox bold;
private JCheckBox italic;
private static int FONTSIZE = 20;

public CheckBoxFrame()
{
setTitle("CheckBoxTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// add the sample text label

label = new JLabel("The quick brown fox jumps over the lazy dog.");
label.setFont(new Font("Serif", Font.PLAIN, FONTSIZE));
add(label, BorderLayout.CENTER);

//Event handling on check box is checked or unchecked


ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
int mode = 0;
if (bold.isSelected()) mode += Font.BOLD;
if (italic.isSelected()) mode += Font.ITALIC;
label.setFont(new Font("Serif", mode, FONTSIZE));
}
};

// add the check boxes

JPanel buttonPanel = new JPanel();

bold = new JCheckBox("Bold");


bold.addActionListener(listener);
buttonPanel.add(bold);

italic = new JCheckBox("Italic");


italic.addActionListener(listener);
buttonPanel.add(italic);
add(buttonPanel, BorderLayout.SOUTH);
}
}

package ChoiceComponents;

import javax.swing.JFrame;

public class CheckBoxFrameMain {


public static void main(String[] args) {
CheckBoxFrame frame = new CheckBoxFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Radio Buttons:
In many cases, we want to require the user to check only one of several boxes.
When another box is checked, the previous box is automatically unchecked. Such a group of
boxes is often called a radio button group because the buttons work like the station selector
buttons on a radio. When you push in one button, the previously depressed button pops out.
 Implementing radio button groups is easy in Swing. We can construct one object of type
ButtonGroup for every group of buttons. Then, we can add objects of type JRadioButton
to the button group. The button group object is responsible for turning off the previously
set button when a new button is clicked.
◦ ButtonGroup group = new ButtonGroup();
◦ JRadioButton smallButton = new JRadioButton("Small", false);
◦ group.add(smallButton);
◦ JRadioButton mediumButton = new JRadioButton("Medium", true);
◦ group.add(mediumButton);

Event Handling for Radiobutton:


 The event notification mechanism for radio buttons is the same as for any other
buttons.
 When the user checks a radio button, the radio button generates an action event. In
our example program, we define an action listener that sets the font size to a
particular value:
ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
// size refers to the final parameter of the addRadioButton method
label.setFont(new Font("Serif", Font.PLAIN, size));
}
};

Example:
package ChoiceComponents;
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;

public class RadioButtonFrame extends JFrame


{
private final static int DEFAULT_WIDTH=500;
private final static int DEFAULT_HEIGHT=200;
private JLabel label;
private JPanel buttonPanel;
private ButtonGroup group;
private static final int DEFAULT_SIZE = 12;

public RadioButtonFrame()
{
setTitle("RadioButtonTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// add the sample text label

label = new JLabel("The quick brown fox jumps over the lazy dog.");
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
add(label, BorderLayout.CENTER);

// add the radio buttons

buttonPanel = new JPanel();


group = new ButtonGroup();

addRadioButton("Small", 8);
addRadioButton("Medium", 12);
addRadioButton("Large", 18);
addRadioButton("Extra large", 36);

add(buttonPanel, BorderLayout.SOUTH);
}

public void addRadioButton(String name, final int size)


{
boolean selected = size == DEFAULT_SIZE;
JRadioButton button = new JRadioButton(name, selected);
group.add(button);
buttonPanel.add(button);

// this listener sets the label font size


ActionListener listener = new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
// size refers to the final parameter of the addRadioButton
method
label.setFont(new Font("Serif", Font.PLAIN, size));
}
};

button.addActionListener(listener);
}
}

package ChoiceComponents;
import javax.swing.JFrame;

public class RadioButtonMain {


public static void main(String[] args)
{
RadioButtonFrame frame = new RadioButtonFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

Borders:
 If you have multiple groups of radio buttons in a window, you will want to
visually indicate which buttons are grouped. Swing provides a set of useful
borders for this purpose.
 Border can be applied to any component that extends JComponent. The most
common usage is to place a border around a panel and fill that panel with other
user interface elements such as radio buttons.
Types of Borders:
We can choose from quite a few borders, but you follow the same steps for all of them.
1. Call a static method of the BorderFactory to create a border. You can choose
among the following styles:
 Lowered bevel(tilt)
 Raised bevel
 Etched
 Line
 Matte
 Empty (just to create some blank space around the component)
2. add a title to our border by passing border to BorderFactory.createTitledBorder.
3. combining several borders with a call to BorderFactory.createCompoundBorder.
4. Add the resulting border to your component by calling the setBorder method of
the JComponent class.
For example, here is how we can add an etched border with a title to a panel:
◦ Border etched = BorderFactory.createEtchedBorder()
◦ Border titled = BorderFactory.createTitledBorder(etched, "A Title");
panel.setBorder(titled);

Example:
package ChoiceComponents;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.border.Border;

class BorderFrame extends JFrame {

public static final int DEFAULT_WIDTH = 600;


public static final int DEFAULT_HEIGHT = 200;
private JPanel demoPanel;
private JPanel buttonPanel;
private ButtonGroup group;
private JLabel label;

public BorderFrame() {
setTitle("BorderTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

demoPanel = new JPanel();


buttonPanel = new JPanel();
group = new ButtonGroup();

addRadioButton("Lowered bevel",
BorderFactory.createLoweredBevelBorder());
addRadioButton("Raised bevel",
BorderFactory.createRaisedBevelBorder());
addRadioButton("Etched", BorderFactory.createEtchedBorder());
addRadioButton("Line", BorderFactory.createLineBorder(Color.BLUE));
addRadioButton("Matte", BorderFactory.createMatteBorder(10, 10, 10,
10, Color.BLUE));
addRadioButton("Empty", BorderFactory.createEmptyBorder());

Border etched = BorderFactory.createEtchedBorder();


Border titled = BorderFactory.createTitledBorder(etched, "Border
types");
buttonPanel.setBorder(titled);

setLayout(new GridLayout(2, 1));


add(buttonPanel);
add(demoPanel);
label = new JLabel(“Borders”);
demoPanel.add(label);
}

public void addRadioButton(String buttonName, final Border b) {


JRadioButton button = new JRadioButton(buttonName);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
demoPanel.setBorder(b);
label.setText(buttonName);
}
});

group.add(button);
buttonPanel.add(button);
}
}

package ChoiceComponents;

public class BorderFrameMain {

public static void main(String[] args) {


BorderFrame frame= new BorderFrame();
frame.setVisible(true);
}
}

Combo Boxes:
 radio buttons are not a good choice because they take up too much screen space.
 The alternative is combobox. When the user clicks on the component, a list of
choices drops down, and the user can then select one of them.
 The JComboBox class provides a combo box component.

Some methods of JCombobox


 the setEditable method to make the combo box editable.
 obtain the current selection or edited text by calling the getSelectedItem method.
 add the choice items with the addItem method.
 addItem is called only in the constructor, but you can call it any time.
◦ faceCombo = new JComboBox();
◦ faceCombo.setEditable(true);
◦ faceCombo.addItem("Serif");
◦ faceCombo.addItem("SansSerif");
 addItem adds the string at the end of the list. new items can be added anywhere in
the list with the insertItemAt method;
◦ faceCombo.insertItemAt("Monospaced", 0); // add at the beginning
 to remove items at runtime, you use the removeItem or removeItemAt method.
◦ faceCombo.removeItem("Monospaced");
◦ faceCombo.removeItemAt(0); // remove first item
◦ The removeAllItems method removes all items at once.

Event handling when selecting an item in combobox:


 When the user selects an item from a combo box, the combo box generates an
action event. To find out which item was selected, call getSource on the event
parameter to get a reference to the combo box that sent the event.
 Then call the getSelectedItem method to retrieve the currently selected item.
public void actionPerformed(ActionEvent event)
{
label.setFont(new Font(String) faceCombo.getSelectedItem(), Font.PLAIN,
DEFAULT_SIZE));
}

Implementation:
package ChoiceComponents;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

class ComboBoxFrame extends JFrame


{
public static final int DEFAULT_WIDTH = 300;
public static final int DEFAULT_HEIGHT = 200;
private JComboBox faceCombo;
private JLabel label;
private static final int DEFAULT_SIZE = 12;

public ComboBoxFrame()
{
setTitle("ComboBoxTest");
setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT);

// add the sample text label


label = new JLabel("The quick brown fox jumps over the lazy dog.");
label.setFont(new Font("Serif", Font.PLAIN, DEFAULT_SIZE));
add(label, BorderLayout.CENTER);

// make a combo box and add face names


faceCombo = new JComboBox();
faceCombo.setEditable(true);
faceCombo.addItem("Serif");
faceCombo.addItem("SansSerif");
faceCombo.addItem("Monospaced");
faceCombo.addItem("Dialog");
faceCombo.addItem("DialogInput");

// the combo box listener changes the label font to the selected face name

faceCombo.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event)
{
label.setFont(new Font((String)
faceCombo.getSelectedItem(), Font.PLAIN,
DEFAULT_SIZE));
}
});
// add combo box to a panel at the frame's southern border
JPanel comboPanel = new JPanel();
comboPanel.add(faceCombo);
add(comboPanel, BorderLayout.SOUTH);
}
}

package ChoiceComponents;

public class ComboBoxFrameMain {


public static void main(String[] args) {
ComboBoxFrame frame= new ComboBoxFrame();
frame.setVisible(true);
}
}

Model View Controller:


Model designs based on MVC architecture follow the MVC design pattern and they
separate the application logic from the user interface when designing software. As the
name implies MVC pattern has three layers, which are:

Model – Represents the business layer of the application


View – Defines the presentation of the application
Controller – Manages the flow of the application

Example:
Model – CourseModel.java
package mvcPackage;

public class CourseModel {


private String CourseName;
private String CourseId;
private String CourseCategory;

public String getId() {


return CourseId;
}

public void setId(String id) {


this.CourseId = id;
}

public String getName() {


return CourseName;
}

public void setName(String name) {


this.CourseName = name;
}

public String getCategory() {


return CourseCategory;
}

public void setCategory(String category) {


this.CourseCategory = category;
}

View – CourseView.java

package mvcPackage;

public class CourseView {


public void printCourseDetails(String CourseName, String CourseId, String
CourseCategory) {
System.out.println("Course Details: ");
System.out.println("Name: " + CourseName);
System.out.println("Course ID: " + CourseId);
System.out.println("Course Category: " + CourseCategory);
}
}

Controller – CourseController.java

package mvcPackage;

public class CourseController {


private CourseModel model;
private CourseView view;

public CourseController(CourseModel model, CourseView view) {


this.model = model;
this.view = view;
}

public void setCourseName(String name) {


model.setName(name);
}

public String getCourseName() {


return model.getName();
}

public void setCourseId(String id) {


model.setId(id);
}

public String getCourseId() {


return model.getId();
}

public void setCourseCategory(String category) {


model.setCategory(category);
}

public String getCourseCategory() {


return model.getCategory();
}

public void updateView() {


view.printCourseDetails(model.getName(), model.getId(),
model.getCategory());
}
}

Main – CourseMain.java [to execute main method]

package mvcPackage;

public class CourseMain {

public static void main(String[] args) {


CourseModel course = new CourseModel();
course.setName("Java");
course.setId("CSC01");
course.setCategory("Programming");
CourseView view = new CourseView();
CourseController controller = new CourseController(course, view);
controller.updateView();
}
}

JList:
The JList Component:
– The JList component is similar to a set of check boxes or radio buttons,
except that the items are placed inside a single box and are selected by
clicking on the items themselves, not on buttons. If you permit multiple
selection for a list box, the user can select any combination of the items in
the box.
• To construct this list component, you first start out with an array of strings, then
pass the array to the JList constructor:
– String[] words= { "quick", "brown", "hungry", "wild", ... };
– JList wordList = new JList(words);
• Alternatively, we can use an anonymous array:
– JList wordList = new JList(new String[] {"quick", "brown", "hungry",
"wild", ... });
• List boxes do not scroll automatically. To make a list box scroll, you must insert it
into a scroll Pane:
– JScrollPane scrollPane = new JScrollPane(wordList);

Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the specified
array.
JList(ListModel<ary> Creates a JList that displays elements from the specified,
dataModel) non-null, model.

Methods Description
Void It is used to add a listener to the list,
addListSelectionListener(ListSelectionListener to be notified each time a change to
listener) the selection occurs.
int getSelectedIndex() It is used to return the smallest
selected cell index.
ListModel getModel() It is used to return the data model
that holds a list of items displayed
by the JList component.
void setListData(Object[] listData) It is used to create a read-only
ListModel from an array of objects.

Example:
package mvcPackage;

import javax.swing.JFrame;
import javax.swing.JList;

public class JListDemo extends JFrame {


private JList<String> list;// generic type

public JListDemo() {
String week[] = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
list = new JList<String>(week);
list.setSelectedIndex(3);
add(list);
setSize(200, 300);
setVisible(true);
}
public static void main(String[] args) {
new JListDemo();
}
}

Event Handler in JList Component


package mvcPackage;

import java.awt.FlowLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class JListDemo extends JFrame implements ListSelectionListener {


private JList<String> list;// generic type
private JLabel lbl;
private FlowLayout layout;

public JListDemo() {
setTitle("JList Event Handler");
layout = new FlowLayout();
setLayout(layout);
String week[] = { "Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday" };
list = new JList<String>(week);
list.setSelectedIndex(3);
list.addListSelectionListener(this);
add(list);
lbl = new JLabel("Select Day and Displayed here..");
add(lbl);
setSize(400, 300);
setVisible(true);
}

public static void main(String[] args) {


new JListDemo();
}

@Override
public void valueChanged(ListSelectionEvent e) {
lbl.setText(list.getSelectedValue());
}
}
JMenuBar:

Menu Bar
 A menu bar on top of the window contains the names of the pull-down menus.
 Clicking on a name opens the menu containing menu items and submenus.
 When the user clicks on a menu item, all menus are closed and a message is sent to the
program.

Menu Building
 Building menus is straightforward. Creation of menu-bar:
◦ JMenuBar menuBar = new JMenuBar();
 A menu bar is just a component that we can add anywhere we like. Normally, menu-bar
appear at the top of a frame. We can add it there with the setJMenuBar method:
◦ frame.setJMenuBar(menuBar);
 For each menu, we can create a menu object:
◦ JMenu editMenu = new JMenu("Edit");
 Adding top level menus
◦ menuBar.add(editMenu);
 menu items, separators, and submenus to the menu object:
◦ JMenuItem pasteItem = new JMenuItem("Paste");
◦ editMenu.add(pasteItem);
◦ editMenu.addSeparator();
◦ JMenu optionsMenu = . . .; // a submenu
◦ editMenu.add(optionsMenu);

Some methods of Menus:


 The method JMenu.add(String s) conveniently adds a menu item to the end of a menu.
For example:
◦ editMenu.add("Paste");
◦ The add method returns the created menu item, so you can capture it and then add
the listener, as follows:
◦ JMenuItem pasteItem = editMenu.add("Paste");
pasteItem.addActionListener(listener);

Methods for Menus


 javax.swing.JMenuItem methods
◦ JMenuItem(String label, Icon icon)
◦ constructs a menu item with the given label and icon.
 javax.swing.AbstractButton methods
◦ void setHorizontalTextPosition(int pos)
◦ sets the horizontal position of the text relative to the icon.
 Parameters:
◦ pos SwingConstants.RIGHT(text is to the right of icon) or
◦ SwingConstants.LEFT(text is to the left of icon)

Implementation of MENU and MENUITEMS


package MenusPackage;

import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.KeyStroke;

public class MenuDemo extends JFrame {


JMenuBar mb;
JMenu fm, em, vm, zm;
JMenuItem miopen, misave;
JCheckBoxMenuItem misb;

public MenuDemo() {
super("Menu Demo File Frame");
setSize(400, 300);
setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mb = new JMenuBar();
fm = new JMenu("File");
vm = new JMenu("View");
em = new JMenu("Edit");
zm = new JMenu("Zoom");
mb.add(fm);
mb.add(vm);
mb.add(em);
fm.setMnemonic('F');//alt+f
vm.setMnemonic('V');//alt+v
em.setMnemonic('E');//alt+e
miopen = new JMenuItem("Open", 'o');
misave = new JMenuItem("Save", 's');
misb = new JCheckBoxMenuItem("Status Bar", true);
fm.add(miopen);
fm.add(misave);
vm.add(misb);
vm.add(zm);
JMenuItem exit = new JMenuItem("Exit", KeyEvent.VK_N);
exit.setAccelerator(KeyStroke.getKeyStroke("ctrl X"));//press ctrl+x
fm.add(exit);

exit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.exit(0);
}
});
setJMenuBar(mb);
setVisible(true);
}
public static void main(String[] args) {
MenuDemo frame = new MenuDemo();
}
}

JTable:

The JTable class is used to display data in tabular form. It is composed of rows and
columns.
• A table is a component that displays rows and columns of data. You can drag the
cursor on column boundaries to resize columns. You can also drag a column to a
new position. Tables are implemented by the JTable class, which extends
JComponent.
• One of its constructors is shown here:
– JTable(Object data[ ][ ], Object colHeads[ ])
Here, data is a two-dimensional array of the information to be presented, and
colHeads is an onedimensional array with the column headings.

There are some methods used in JTable given below;

 addColumn(TableColumn column[]): adds a column at the end of the JTable.


 clearSelection(): selects all the selected rows and columns.
 editCellAt(int row, int col): edits the cell.
 setvalueAt(Object value, int row, int col): sets the cell value as ‗value‘ for the
position [row,col] in the JTable.

Example:
package mvcPackage;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableColumn;

public class JTableDemo {


JFrame f;

JTableDemo() {
f = new JFrame();
String data[][] = { { "101", "Harendra", "100000" }, { "102", "Mahendra",
"200000" },
{ "101", "Narendra", "300000" } };
String column[] = { "ID", "NAME", "SALARY" };
JTable jt = new JTable(data, column);
jt.setBounds(30, 40, 200, 300);
JScrollPane sp = new JScrollPane(jt);
jt.setValueAt("Surendra", 0, 1);//modify the value at [0,1] cell
jt.addColumn(new TableColumn(2));//add the copy of the column at index
2
f.add(sp);
f.setSize(300, 400);
f.setVisible(true);
}

public static void main(String[] args) {


new JTableDemo();
}
}
Event Hndling:

Event: An event is an object that describes a state change in a source. It can be generated
as a consequence of a program interacting with the elements in a graphical user interface.
Event Sources: A source is an object that generates an event. This occurs when the
internal state of that object changes in some way. Sources may generate more than one
type of event. Some of the event sources are JButtons, JTextFields, JComboBoxs,
Jsliders, Window, etc.
Event Listeners: To react to an event, there is a need to implement correct event listener.
A listener is an object that is notified when an event occurs. Some of the commonly used
listeners are ActionListener, KeyListener, FocusListener, WindowListener,
ChangeListener, etc.
Basically, event handling is the process of controlling the events created by the
components(such as: Jbutton, JCheckBox, JRadioButton, JList, etc.).
Different event sources can produce different kinds of events. For example, a button can
send ActionEvent objects, whereas a window can send WindowEvent objects.
Event Delegation Model: Modern versions of java use the Delegation Event Model to
handle the events. This model defines the standard mechanism to generate and handle the
events. In this model, source generates an event and sends it to one or more listeners. All
classes used in event handling process are known as delegated classes.

Table: List of Event classes.

Event Classes Descriptions


ActionEvent Generated when a button is pressed, radiobutton is selected,
checkbox item is checked, menu item is selected, and list item is
double clicked.
AdjustmentEvent Generated when a scroll pane is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized or becomes
visible.
ContainerEvent Generated when a component is added to or removed from a
container.
FocusEvent Generated when a component gains or losses keyboard focus.
ItemEvent Generated when a list item is clicked.
KeyEvent Generated when input is received from keyboard.
MouseEvent Generated when mouse is dragged, moved, clicked, pressed,
released, enters, or exits.
MouseWheelEvent Generated when mousewheel is scrolled or used.
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated,
deiconified, opened or quit.
ChangeEvent Generated when the JSlider‘s values are changed by using Jslider.

• When an event is triggered the JAVA runtime first determines its source and type.
• If a listener for this type of event is registered with the source an event object is
created.
• For each listener to this type of event, the java runtime invokes the appropriate
event handling method to the listener and passes the event object as the parameter.
Figure: Event Handling

Table: List of Listener classes.

Event Classes Descriptions


ActionListener Declares one method to receive action events.
void actionPerformed(ActionEvent event)
AdjustmentListener Handles the events generated when scrollbar is manipulated.
void adjustmentValueChanged(AdjustmentEvent event)
ComponentListener Handles the event when a component is hidden, moved, resized or
shown.
void componentResized(ComponentEvent event)
void componentMoved(ComponentEvent event)
void componentShown(ComponentEvent event)
void componentHidden(ComponentEvent event)
ContainerListener Handles the event when a component is added or removed from a
container.
void componentAdded (ContainerEvent event)
void componentRemoved (ContainerEvent event)
FocusListener Handles the event when a component gains or losses keyboard
focus.
void focusGained (FocusEvent event)
void focusLost (FocusEvent event)
ItemListener Handles events when a list item is clicked.
void itemStateChanged (ItemEvent event)
KeyListener Handles events when input is received from keyboard.
void keyPressed (KeyEvent event)
void keyReleased (KeyEvent event)
void keyTyped (KeyEvent event)
MouseListener Handles events when mouse is dragged, moved, clicked, pressed,
released, enters, or exits.
void mouseClicked (MouseEvent event)
void mouseEntered (MouseEvent event)
void mouseExited (MouseEvent event)
void mousePressed (MouseEvent event)
void mouseReleased (MouseEvent event)
MouseWheelListener Handles events when mousewheel is scrolled or used.
void mouseDragged (MouseEvent event)
void mouseMoved(MouseEvent event)
CaretListener Handles events when caret changes its position or if text is
selected, a caret event is fired by a text component.
void caretUpdate (CaretEvent event)
WindowListener Handles events when a window is activated, closed, deactivated,
deiconified, opened or quit.
void windowActivated (WindowEvent event)
void windowClosed (WindowEvent event)
void windowClosing (WindowEvent event)
void windowDeactivated (WindowEvent event)
void windowDeiconified (WindowEvent event)
void windowIconified (WindowEvent event)
void windowOpened (WindowEvent event)
ChangeListener Handles events when the JSlider‘s values are changed.
void stateChanged (ChangeEvent event)

Action Event:
• In Java, most components have a special event called an ActionEvent. This is one
of the most common event for that component. A good example is a click for a
button. To have any component listen for an ActionEvent, we must register the
component with an ActionListener as;
• Component.addActionListener(new ActionListener());
• And then write the
• Public void actionPerformed(ActionEvent event){
– Method for the component to react to the event
}

An overview of how event handling in the AWT works


• A listener object is an instance of a class that implements a special interface called
(naturally enough) a listener interface.
• An event source is an object that can register listener objects and send them event
objects.
• The event source sends out event objects to all registered listeners when that event
occurs.
• The listener objects will then use the information in the event object to determine
their reaction to the event.
• Here is an example for specifying a listener:
• ActionListener listener = new ActionListener ();
• JButton button = new JButton("Ok");
• button.addActionListener(listener);
• Now the listener object is notified whenever an ―action event‖ occurs in the
button. For buttons, as you might expect, an action event is a button click.
• To implement the ActionListener interface, the listener class must have a method
called actionPerformed that receives an ActionEvent object as a parameter.
class listener implements ActionListener
{
...
public void actionPerformed(ActionEvent event)
{
// reaction to button click goes here
...
}
}
Whenever the user clicks the button, the JButton object creates an ActionEvent
object and calls listener.actionPerformed(event), passing that event object. An event
source such as a button can have multiple listeners. In that case, the button calls the
actionPerformed methods of all listeners whenever the user clicks the button.

Steps of Event Handling:


1. Implements the listener interface and overrides its methods.
2. Register the component with the listener.
3. Put proper code in required overridden method.

Example:
class EventHandling implements ActionListener{ //Step 1(ActionListener interface is
implemented)

JButton button; //JButton is created


Jframe frame; //Jframe is created
EventHandling(){ //Constructor created (same name as
class name)
frame=new JFrame(); //frame is instantiated
frame.setTitle(“Event Handling Frame”); //title of a frame
frame.setLayout(new FlowLayout()); //flowlayout is added to JFrame
frame.setSize(400,500); //size of frame is 400 pixels by 500
pixels
frame.setVisible(true); //frame is visible or shown

button = new JButton(“Close Frame”); //button object is instantiated


button.addActionListener(this); //Step 2(‘this’ is an event generated
by clicking button.
public actionPerformed(ActionEvent event){ //Step 3 (method for handling
ActionEvent)
System.exit(0); // frame closed
} //actionPerformed closed
} //constructor closed
public static void main(String[] args){ //main method is invoked by
JVM
new EventHandling(); //constructor is called
} //main method closed
} //class closed
Using Delegation Model to Handle Events

1. Handling Action Events


public class DelegationModelDemo extends JFrame implements ActionListener {

private JTextField t1,t2,t3;


private JLabel l1,l2,l3;
private JButton b1,b2;

public DelegationModelDemo() {
super("Handling Action Events");
l1= new JLabel("First Value");
t1=new JTextField(10);
l2= new JLabel("Second Value");
t2=new JTextField(10);
l3= new JLabel("Result");
t3=new JTextField(10);
b1=new JButton("+");
b2=new JButton("-");
b1.addActionListener(this); //’this’ represent a class that implements
ActionListener
b2.addActionListener(this); //’this’ represent a class that implements
ActionListener

setLayout(new FlowLayout(FlowLayout.LEFT,150,10));//gaps between


components hor, vert
add(l1);add(t1);add(l2);add(t2);add(l3);add(t3); add(b1);add(b2);
setSize(400,300);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
int x,y,z;
x=Integer.parseInt(t1.getText());//values come from textfields are
always of string type
y=Integer.parseInt(t2.getText());//so Iteger,parseInt() change the
type from string to int.
if(e.getActionCommand()=="+") //if event is of name +
z=x+y;
else
z=x-y;
t3.setText(String.valueOf(z)); //as z is integer type, textfield always
set the string.
}
public static void main(String[] args) {
new DelegationModelDemo();
}
}
Output:

Figure: ActionEvent Demonstration.

Note: Above program deals with ActionEvent and ActionListener. The


ActionListener interface is implemented and ActionEvent that are generated by
clicking buttons are handled by actionPerformed(ActionEvent event) method.
Also, getActionCommand() is used to retrieve the name of event.

2. Handling Key Events

The class KeyEvent is defined in java.awt.event package. Key events occur when
a key is pressed on the keyboard. Any component can generate these events, and a
class must implement KeyListener interface to support them. An object that
implements the KeyListener interface gets this KeyEvent when the event occurs
and hence must handle the event by overriding keyTyped(), keyPressed(), and
keyreleased() methods of KeyListener Interface. Presseing and releasing a key on
the keyboard results in generating the following key events(in order);
- KEY_PRESSED
- KEY_TYPED
- KEY_RELEASED

Implementation:
import java.awt.FlowLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.*;

public class KeyListenerDemo extends JFrame implements KeyListener{


private JTextField t1,t2,t3;
private JLabel l1,l2,l3;
private JButton b;
KeyListenerDemo(){
super("Handling Key Event");
l1= new JLabel("First Value");
t1=new JTextField(10);
l2= new JLabel("Second Value");
t2=new JTextField(10);
l3= new JLabel("Result");
t3=new JTextField(10);
b=new JButton("Calculate");
b.addKeyListener(this);//calculate button is clicked to activate Key
Listener
setLayout(new FlowLayout());
add(l1);add(t1);add(l2);add(t2);add(l3);add(t3);add(b);
setSize(100,300);
setVisible(true);

}
@Override
public void keyPressed(KeyEvent ke) {
int x,y,z;
x=Integer.parseInt(t1.getText());
y=Integer.parseInt(t2.getText());

if(ke.getKeyChar()=='a'){
z=x+y;
}
else if(ke.getKeyChar()=='s'){
z=x-y;
}
else{
t3.setText("Press A or S");
return;
}
t3.setText(String.valueOf(z));
}
@Override
public void keyReleased(KeyEvent arg0) {
keyLabel.setText("Key is released");
}
@Override
public void keyTyped(KeyEvent arg0) {
keyLabel.setText("Key typed");
}
public static void main(String[] args) {
new KeyListenerDemo();
}
}

Output:
Figures: Key Event Demonstration.

Note: The above programs used KeyEvent and KeyListener and all methods
implemented from KeyListener interface as keyPressed(), keyReleased(),
keyTyped(). KeyListener is active only when the calculate button is clicked.

3. Handling Window Event


The class WindowEvent is defined in java.awt.event package. This is generated
whenever there is a change in the window state such as minimized, maximized,
activate, deactivated, opened, closing, closed. Window event is generated by
components such as JFrame, JInternalFrame, JDialog, etc. To handle window event, a
class must implement WindowListener interface or extend WindowAdapter class. The
object that implements the WindowListener interface gets this window when the event
occurs and hence must handle the event by overriding windowClosing(),
windowClosed(), windowIconified(), windowDeiconified(), windowActivated(),
windowDeactivated() and windowOpened() methods of WindowListener interface.

4.1 Using WindowAdapter Class


import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class WindowAdapterDemo extends WindowAdapter {


private JFrame frame;
public WindowAdapterDemo() {
frame = new JFrame();
frame.setVisible(true);
frame.addWindowListener(this);
frame.setSize(300, 400);
}

public void windowClosing(WindowEvent we) { //triggered at closing


time of frame
JOptionPane.showMessageDialog(frame, "GoodByee");
}

public void windowOpened(WindowEvent we) { //triggered when the


frame is opened/run
JOptionPane.showMessageDialog(frame, "WelCome!!");
}

public void windowIconified(WindowEvent we) { //triggered when


frame is minimized
JOptionPane.showMessageDialog(frame, "See You later");
}

public void windowDeiconified(WindowEvent we) { //triggered when frame is


restored from minimixed
JOptionPane.showMessageDialog(frame, "Welcome Back");
}

public static void main(String[] args) {


new WindowAdapterDemo();
}
}
Note: We can declare only those methods which are needed, by using
WindowAdapter Class.
Figure: windowOpened Figure: windowIconified Figure: windowDeiconified
Figure: windowClosing

4.2 Using WindowListener Interface


import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.*;

public class WindowListenerDemo implements WindowListener{

JFrame frame;
public WindowListenerDemo() {
frame=new JFrame();
frame.setVisible(true);
frame.addWindowListener(this);
frame.setSize(300, 400);
}

public void windowClosing(WindowEvent we){


JOptionPane.showMessageDialog(frame, "GoodByee");
}
public void windowOpened(WindowEvent we){
JOptionPane.showMessageDialog(frame, "WelCome!!");
}
public void windowIconified(WindowEvent we){
JOptionPane.showMessageDialog(frame, "See You later");
}
public void windowDeiconified(WindowEvent we){
JOptionPane.showMessageDialog(frame, "Welcome Back");
}
public static void main(String[] args) {
new WindowListenerDemo();
}
@Override
public void windowClosed(WindowEvent e) {
JOptionPane.showMessageDialog(frame, "Window is closed");

}
@Override
public void windowActivated(WindowEvent e) {
JOptionPane.showMessageDialog(frame, "Window Activated");

}
@Override
public void windowDeactivated(WindowEvent e) {
JOptionPane.showMessageDialog(frame, "Window Deactivated");
}
}
Note: But in case of using window listener classes we have to declare all the
methods of WindowListener interface. There is same output of WindowListener
interface and WindowAdapter class.

4. Handling Mouse Events


MouseEvent is generated wenever a user performs as action with the mouse. These
include pressing, releasing, clicking, entering, exiting, moving and dragging of mouse.
To handle a mouse event, a class must implement the MouseListener interface or
extend MouseAdapter class. The object that implements the MouseListener interface
gets mouse event occurs and hence must handle the event by overriding
mouseClicked(), mouseEntered(), mousePressed(), mouseExited() and
mouseReleased() methods of MouseListener interface.
- mousePressed(): which is triggered when the mouse is on the component.
- mouseClicked(); which is triggered when the mouse is pressed and released on the
component (mousePressed() is called first).
- mouseReleased(): which is triggered when the mouse is released on the
component(mousePressed() must have been called first).
- mouseEntered() and mouseExited(): triggered when mouse enters and exits the
component respectively.

Implementation:
import java.awt.*;
import java.awt.event.*;

import javax.swing.JFrame;

public class mouselistenerdemo extends JFrame implements MouseListener {


Label l;

mouselistenerdemo() {

addMouseListener(this);

l = new Label();
l.setBounds(20, 50, 100, 20);
add(l);
setLayout(null);
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);
}

public void mouseClicked(MouseEvent e) {


l.setText("Mouse Clicked");
}

public void mouseEntered(MouseEvent e) {


l.setText("Mouse Entered");
}

public void mouseExited(MouseEvent e) {


l.setText("Mouse Exited");
}

public void mousePressed(MouseEvent e) {


l.setText("Mouse Pressed");
}

public void mouseReleased(MouseEvent e) {


l.setText("Mouse Released");
}

public static void main(String[] args) {


new mouselistenerdemo();
}
}

Note: In above program, we are forced to implement all the methods that are declared in
MouseListener interface and are overridden in the program. We can not skip any of the
methods while implementing MouseListener interface in any class to handle the mouse
events.

Note: We can make a program using MouseAdapter class similar as MouseListener as


below.

Extending MouseAdapter class:


import java.awt.*;
import java.awt.event.*;

import javax.swing.JFrame;

public class mouselistenerdemo extends MouseAdapter {


Label l;
JFrame frame;
mouselistenerdemo() {
frame=new JFrame();
frame.addMouseListener(this);

l = new Label();
l.setBounds(20, 50, 100, 20);
frame.add(l);
frame.setLayout(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void mouseClicked(MouseEvent e) {


l.setText("Mouse Clicked");
}

public void mouseEntered(MouseEvent e) {


l.setText("Mouse Entered");
}

public void mouseExited(MouseEvent e) {


l.setText("Mouse Exited");
}
//Here we have commented one overridden method and still the program executes
// public void mousePressed(MouseEvent e) {
// l.setText("Mouse Pressed");
// }

public void mouseReleased(MouseEvent e) {


l.setText("Mouse Released");
}

public static void main(String[] args) {


new mouselistenerdemo();
}
}

Note: In a program above we have only overridden the methods from MouseAdapter
class that are needed.
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you
inherit the adapter class, you will not be forced to provide the implementation of all the
methods of listener interfaces. So it saves code.

The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event


packages. The Adapter classes with their corresponding listener interfaces are given
below.

Adapter class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener

Desktop Panes and Internal Frames:


• Many applications present information in multiple windows that are all contained
inside a large frame. If you minimize the application frame, all of its windows are
hidden at the same time. In the Windows environment, this user interface is
sometimes called the multiple document interface or MDI
• Use a regular JFrame window for the application.
• Set the content pane of the JFrame to a JDesktopPane.
• desktop = new JDesktopPane();
• setContentPane(desktop);
• Construct JInternalFrame windows. You can specify whether you want the icons
for resizing or closing the frame. Normally, you want all icons.
• JInternalFrame iframe = new JInternalFrame(title,
• true, // resizable
• true, // closable
• true, // maximizable
• true); // iconifiable
• Add components to the content pane of the frame.
• iframe.getContentPane().add(c);
• Set a frame icon. The icon is shown in the top-left corner of the frame.
• iframe.setFrameIcon(icon);
• Use a regular JFrame window for the application.
• Set the content pane of the JFrame to a JDesktopPane.
• desktop = new JDesktopPane();
• setContentPane(desktop);
• Construct JInternalFrame windows. You can specify whether you want the icons
for resizing or closing the frame. Normally, you want all icons.
• JInternalFrame iframe = new JInternalFrame(title,
• true, // resizable
• true, // closable
• true, // maximizable
• true); // iconifiable
• Add components to the content pane of the frame.
• iframe.getContentPane().add(c);
• Set a frame icon. The icon is shown in the top-left corner of the frame.
iframe.setFrameIcon(icon);

Implementation:
import java.awt.FlowLayout;
import javax.swing.*;

public class DeskTopPane extends JFrame{


JDesktopPane dp;
JInternalFrame iframe;
JTextField tf;
JLabel lb;
JInternalFrame iframeone;

DeskTopPane(){
setSize(600,600);
setDefaultLookAndFeelDecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
dp= new JDesktopPane();
iframe= new JInternalFrame("Internal frame", true, true, true, true);
iframe.setSize(100, 100);
iframe.setLocation(50, 50);
dp.add(iframe);
add(dp);
lb=new JLabel("Email");
tf=new JTextField(10);
iframe.setLayout(new FlowLayout(FlowLayout.CENTER));
iframe.add(tf);
iframe.add(lb);
iframe.setVisible(true);

iframeone=new JInternalFrame("Frame two",true,true,true,true);


iframeone.setSize(150, 50);
iframeone.setLocation(200, 100);
dp.add(iframeone);
iframeone.setVisible(true);
}
public static void main(String[] args) {
DeskTopPane frame= new DeskTopPane();
}
}
Unit 12: Introduction to Java Applets [1 hour]
Definition, applet lifecycle methods, build a simple applet, using applet viewer, adding
controls: animation concepts.

Java Applets:
An applet is a special kind of Java program that runs in a Java enabled browser. This is
the first Java program that can run over the network using the browser. Applet is typically
embedded inside a web page and runs in the browser.

Applets are designed to be embedded within an HTML page. Applets interact with the
user through the AWT.
In other words, we can say that Applets are small Java applications that can be accessed
on an Internet server, transported over Internet, and can be automatically installed and run
as apart of a web document.

To create an applet, a class must class extends java.applet.Applet class.

An Applet class does not have any main() method. It is viewed using JVM. The JVM can
use either a plug-in of the Web browser or a separate runtime environment to run an
applet application.

JVM creates an instance of the applet class and invokes init() method to initialize an
Applet.

Note: Java Applet is deprecated since Java 9. It means Applet API is no longer
considered important. Applet support ended in March 2019. Oracle announced in January
2016 that Applets would be deprecated in Java SE 9, and the technology was removed
in Java SE 11. Components required to run Applets on non-Windows platforms
are being removed starting July 2020.

Lifecycle of Java Applet


Following are the stages in Applet;

1. Applet is initialized.
2. Applet is started
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

Example: Here is an example of applet although it is deprecated in newer version of Java


and now it is not working.
import java.applet.Applet;
import java.awt.Graphics;

public class appletdemo extends Applet {


public void paint(Graphics graphics) {
graphics.drawString("Harendra Raj Bist", 50, 25);
}
}

Write a html file in same directory for displaying the contents of Applet in a web view as
follows;
<html>
<head>
<TITLE> A Simple Program </TITLE>
</head>

<body>
Here is the output of my program:
<applet code="appletdemo.class" width="150" height="25"></applet>
</body>
</html>

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides
1 life cycle methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle
methods of applet.

 public void init(): is used to initialized the Applet. It is invoked only once.
 public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
 public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
 public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.

public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.

How to run an Applet?


There are two ways to run an applet

By html file.
By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that create an
html file and place the applet code in html file. Now click the html file.
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
}

Note: class must be public because its object is created by Java Plugin software that
resides on the browser.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in
comment and compile it. After that run it by: appletviewer First.java. Now Html file is
not required but it is for testing purpose only.

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}

}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
Unit 13: Database Programming using JDBC [2 hours]
Using Connection, Statement and ResultSet interfaces for manipulating data with the
database.

How to install JDBC?

 First step is to download latest sqljdbc for ms sql server.

 After that, add it to the project.

 Likely as, Open your Eclipse and create a new java project of you can use
any old project to add the jdbc libraries. For this, right click on your
project -> build path->configure build path->libraries->module->add
external jar/add libraries.

 choose the downloaded sqljdbc.jar file.

 For database, you have to install the microsoft sql server and sql management
studio. Then follow the following methods;
 Open SQL Server Configuration Manager and under SQL Server
Network Configuration go to Protocols for SQLEXPRESS. Right-click
on TCP/IP and choose Properties. Set Enabled = true.
 While you are there, click on IP Addresses tab and find the section IP
All. Set TCP Port to 1433.
 Add sqljdbc_auth.dll file to your PATH Environment Variable. In my
case:
D:\HarendraFolder\sqljdbc_6.0.7130.100_enu\sqljdbc_6.0\enu\auth\x6
4.
 Copy the sqljdbc_auth.dll to your JDK directory. In my case:
C:\Program Files\Java\jdk-13.0.2\bin.
 The sqljdbc.jar is a file that is used to connect the java application with database.
In this jar file, we have a package ―com.microsoft.sqlserver.jdbc” which contains
many different classes used for the interaction with the database.
 Database URLs: These are the connection strings used to connect with database.
jdbcUrl="jdbc:sqlserver:"+server+":"+port+";databaseName="+database+";i
ntegratedSecurity=true";
 Making the Connection: You need to find out the names of the JDBC driver
classes used by your vendor. Typical driver names are;
- com.microsoft.sqlserver.jdbc.SQLServerDriver(WE USE THIS)
- COM.ibm.db2.jdbc.app.DB2Driver
- COM.cloudscape.core.JDBCDriver

Database connection with MSSql server:

 Create a new java class to connect to a database namely ―TestDatabaseDemo‖


 Add the code in your class

 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

 String server=‖//DESKTOP-L7LVCJU\\SQLEXPRESS";

 This is a name of a server that can be copied from Sql Management Studio. Open Sql
server Management Studio and create a database after authenticating the server with
Windows Authentication.

 String database = "CollegeDb";

 Name of a database that is created in SSMS(Sql Server Management Studio)

 int port=1433;

 if you have not set port yet follow the instructions below;

 It is a network port that is set by: SQL Server Configuration Manager and under
SQL Server Network Configuration go to Protocols for SQLEXPRESS. Right-click
on TCP/IP and choose Properties. Set Enabled = true.
 While you are there, click on IP Addresses tab and find the section IP All. Set TCP
Port to 1433.
 Also restart Sql Server Services – SQL Server (SQLExpress)=Right Click and
Restart.

 String
jdbcUrl="jdbc:sqlserver:"+server+":"+port+";databaseName="+database+";integrated
Security=true";

 This is the connectionstring that is used to connect to the sql server. It contains server
type(i.e.jdbc:sqlserver), server name(i.e. //Desktop-L7LVCJU\\SQLEXPRESS),
Database name(i.e. CollegeDb) and integratedSecurity = true for windows
authentication and false for username and password if we are using the database
server of certain organization.

Executing SQL Statements: Managing Connections, Statements, Result Set, SQL


Exceptions, Populating Database.

 Connection con= DriverManager.getConnection(jdbcUrl);

 Connection is a java class that is used to connect the java program to the sql server.
And DriverManager .getConnection(“ConnectionString”) method takes
connectionstring as an argument.

 java.sql.Statement statement=con.createStatement();
 Statement is a java class used to support all kinds of statements that are necessary for
database. createStatement() method in inbuilt method used to create the statements
that are listed below;
a. Insertion
› String insertdata="INSERT INTO StdTbl VALUES('Ram',‘Vedas‘…………)";
statement.executeUpdate(insertdata);
b. Updation
› String updateString="UPDATE tblStudent "+" SET Rollno=75 "+" WHERE
StudentName='Harendra'";
statement.executeUpdate(updateString);
c. Deletion
› String deleteString="DELETE FROM StdTbl "+" "+ "WHERE StudentName='Ram'";
statement.executeUpdate(deleteString);
d. Selection
 ResultSet rsltset = statement.executeQuery("SELECT Name, Address from
Info_tbl;");
ResultSet is a java class used used to keep the data selected from the database table
according to queries. executeQuery() method invokes the queries.
while(rsltset.next()) {
System.out.println("The person is " + rsltset.getNString("Name") + " from ―
+ rsltset.getInt("Address"));
}

This is how the data is displayed that is contained in ResultSet.

Note: executeQuery() method is for retrieving data from database table and
executeUpdate() method is for Insertion, Updation and Deletion of data from database
table.

Creating Table

Creating Table:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TableCreationDemo {


ResultSet rsltset;
Statement statement;
Connection con;

public TableCreationDemo() throws SQLException, ClassNotFoundException {

try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver loaded");

String server = "//DESKTOP-L7LVCJU\\SQLEXPRESS";


String database = "CollegeDb";
int port = 1433;

String jdbcUrl = "jdbc:sqlserver:" + server + ":" + port +


";databaseName=" + database+ ";integratedSecurity=true";

con = DriverManager.getConnection(jdbcUrl);
System.out.println("Connection obtained");
statement = con.createStatement();
System.out.println("Statement is created");

// Creating a table in database CollegeDb


String createTable = "CREATE TABLE EMPLOYEE" + "(EmpID
stName varchar(255),"+ "FirstName varchar(255)," + "Addres
varchar(255)," + " City varchar(255)" + ");";
statement.executeUpdate(createTable);
System.out.println("Table created Successfully");

} catch (SQLException ex) {


System.out.println("Exception is:" + ex);
} finally {
rsltset.close();
statement.close();
con.close();
System.out.println("Resources released");
}
}

public static void main(String[] args) throws ClassNotFoundException,


SQLException {
new TableCreationDemo();

}
}

Implementation: CRUD Operations

1. Select data from database


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDatabaseDemo {
static ResultSet rsltset;
static Statement statement;
static Connection con;

public static void main(String[] args) throws SQLException {


try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver loaded");

String server = "//DESKTOP-L7LVCJU\\SQLEXPRESS";


String database = "CollegeDb";
int port = 1433;

String jdbcUrl = "jdbc:sqlserver:" + server + ":" + port +


";databaseName=" + database
+ ";integratedSecurity=true";

con = DriverManager.getConnection(jdbcUrl);
System.out.println("Connection obtained");
statement = con.createStatement();
System.out.println("Statement is created");

String selectData = "SELECT * from tblStudent;";


rsltset = statement.executeQuery(selectData);

while (rsltset.next()) {
System.out.println("The name of the Student is " +
rsltset.getNString("StudentName")+ " whose College Name
is " + rsltset.getNString("CollegeName"));
}

} catch (Exception ex) {


System.out.println("Exception is:" + ex);
} finally {
rsltset.close();
statement.close();
con.close();
System.out.println("Resources released");
}
}
}

2. Inserting Data into database Table


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class InsertionData {
static ResultSet rsltset;
static Statement statement;
static Connection con;
public static void main(String[] args) throws SQLException,
ClassNotFoundException {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver loaded");

String server = "//DESKTOP-L7LVCJU\\SQLEXPRESS";


String database = "CollegeDb";
int port = 1433;

String jdbcUrl = "jdbc:sqlserver:" + server + ":" + port +


";databaseName=" + database+ ";integratedSecurity=true";

con = DriverManager.getConnection(jdbcUrl);
System.out.println("Connection obtained");
statement = con.createStatement();
System.out.println("Statement is created");

//Insertion of data into database table


statement.executeUpdate("INSERT INTO tblStudent
VALUES('Ram', 'Vedas', 'Kalanki', '9841931900', 'Shyam')");
System.out.println("Data are inserted Successfully");

//Selection from database table


System.out.println("The data are as follows");
System.out.println("----------------------------------------------");
String selectData = "SELECT * from tblStudent;";
rsltset = statement.executeQuery(selectData);

while (rsltset.next()) {
System.out.println("The name of the Student is " +
rsltset.getNString("StudentName")+ " whose College Name
is " + rsltset.getNString("CollegeName"));
}

} catch (SQLException ex) {


System.out.println("Exception is:" + ex);
} finally {
rsltset.close();
statement.close();
con.close();
System.out.println("Resources released");
}
}
}
3. Updating Data of table
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class UpdationData {


static ResultSet rsltset;
static Statement statement;
static Connection con;

public UpdationData() throws ClassNotFoundException, SQLException {


try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver loaded");

String server = "//DESKTOP-L7LVCJU\\SQLEXPRESS";


String database = "CollegeDb";
int port = 1433;

String jdbcUrl = "jdbc:sqlserver:" + server + ":" + port +


";databaseName=" + database+ ";integratedSecurity=true";

con = DriverManager.getConnection(jdbcUrl);
System.out.println("Connection obtained");
statement = con.createStatement();
System.out.println("Statement is created");

// Updation of data into database table


String updateString = "UPDATE tblStudent " + " SET
Address='Naikap' " + " WHERE StudentName='Ram'";
statement.executeUpdate(updateString);

// Selection from database table


System.out.println("The data are as follows");
System.out.println("----------------------------------------------");
String selectData = "SELECT * from tblStudent;";
rsltset = statement.executeQuery(selectData);

while (rsltset.next()) {
System.out.println("The name of the Student is " +
rsltset.getNString("StudentName")+ " whose Address is " +
rsltset.getNString("Address"));
}

} catch (SQLException ex) {


System.out.println("Exception is:" + ex);
} finally {
rsltset.close();
statement.close();
con.close();
System.out.println("Resources released");
}
}

public static void main(String[] args) throws ClassNotFoundException,


SQLException {
new UpdationData();
}
}
4. Deleting data from table
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DeletionData {


static ResultSet rsltset;
static Statement statement;
static Connection con;
public DeletionData() throws SQLException, ClassNotFoundException {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver loaded");

String server = "//DESKTOP-L7LVCJU\\SQLEXPRESS";


String database = "CollegeDb";
int port = 1433;

String jdbcUrl = "jdbc:sqlserver:" + server + ":" + port +


";databaseName=" + database+ ";integratedSecurity=true";

con = DriverManager.getConnection(jdbcUrl);
System.out.println("Connection obtained");
statement = con.createStatement();
System.out.println("Statement is created");

// Deletion of data into database table


String deleteString="DELETE FROM tblStudent "+" "+ "WHERE
StudentName='Ram'";
statement.executeUpdate(deleteString);

// Selection from database table


System.out.println("The data are as follows");
System.out.println("----------------------------------------------");
String selectData = "SELECT * from tblStudent;";
rsltset = statement.executeQuery(selectData);
while (rsltset.next()) {
System.out.println("The name of the Student is " +
rsltset.getNString("StudentName")+ " whose Address is " +
rsltset.getNString("Address"));
}

} catch (SQLException ex) {


System.out.println("Exception is:" + ex);
} finally {
rsltset.close();
statement.close();
con.close();
System.out.println("Resources released");
}
}

public static void main(String[] args) throws ClassNotFoundException,


SQLException {
new DeletionData();

}
}

ResultSet Concurrency
A ResultSet can have one of two concurrency levels:

1. ResultSet.CONCUR_READ_ONLY:
CONCUR_READ_ONLY means that the ResultSet can only be read.
statement = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);

2. ResultSet.CONCUR_UPDATABLE
CONCUR_UPDATABLE means that the ResultSet can be both read and updated.
statement = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

If a ResultSet is updatable, you can update the columns of each row in the ResultSet. You
do so using the many updateXXX() methods. For instance:
statement = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet result = statement.executeQuery("SELECT * FROM tblStudent");
result.absolute(2);
result.updateString("StudentName", "Mahesh Bist");
result.updateRow();

We can also update a column using column index instead of column name. Here is an
example:
result.updateString (1, "Ram");
result.updateInt (2, 55);
result.updateRow();

Implementation:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
public class RowSetsCachedRowSetsDemo

static Statement statement;


static Connection con;

public static void main(String[] args) throws SQLException, ClassNotFoundException {


JdbcRowSet rowset = RowSetProvider.newFactory().createJdbcRowSet();
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver loaded");
String server = "//DESKTOP-L7LVCJU\\SQLEXPRESS";
String database = "CollegeDb";
int port = 1433;
String jdbcUrl = "jdbc:sqlserver:" + server + ":" + port + ";databaseName=" +
database+ ";integratedSecurity=true";
con = DriverManager.getConnection(jdbcUrl);

// Read and update table data


statement = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet result = statement.executeQuery("SELECT * FROM tblStudent");
// Updating the table due to ResultSet.CONCUR_UPDATABLE
result.absolute(2);
result.updateString("StudentName", "Mahesh Bist");
result.updateRow();

// Reading the table due to ResultSet.CONCUR_UPDATABLE


result.first();
readStudentInfo("first", result);
result.relative(3);
readStudentInfo("relative(3)", result);
result.previous();
readStudentInfo("previous", result);
result.absolute(4);
readStudentInfo("absolute(4)", result);
result.last();
readStudentInfo("last", result);
result.relative(-2);
readStudentInfo("relative(-2)", result);
}
private static void readStudentInfo(String position, ResultSet result) throws
SQLException {
String name = result.getString("StudentName");
String college = result.getString("CollegeName");
String number = result.getString("ContactNumber");
String studentInfo = "%s: %s - %s - %s\n";
System.out.format(studentInfo, position, name, college, number);
}
}

You might also like