0% found this document useful (0 votes)
4 views557 pages

Java Object-Oriented Programming Guide

The document outlines the syllabus for CST 205, focusing on Object Oriented Programming using Java, divided into five modules covering topics such as design approaches, UML diagrams, Java features, exception handling, and JDBC architecture. Each module includes specific subjects and programming tasks, emphasizing practical applications alongside theoretical concepts. The introduction to Java highlights its characteristics, including being object-oriented, platform-independent, and simple to learn.

Uploaded by

dayal.bc1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views557 pages

Java Object-Oriented Programming Guide

The document outlines the syllabus for CST 205, focusing on Object Oriented Programming using Java, divided into five modules covering topics such as design approaches, UML diagrams, Java features, exception handling, and JDBC architecture. Each module includes specific subjects and programming tasks, emphasizing practical applications alongside theoretical concepts. The introduction to Java highlights its characteristics, including being object-oriented, platform-independent, and simple to learn.

Uploaded by

dayal.bc1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CST 205: OBJECT ORIENTED PROGRAMMING USING JAVA

IMPORTANT TOPICS

MODULE 1

● Function Oriented Design &Object oriented Design( With Example) [3 or 8


Mark]
● Basic Object Oriented concepts [10 or 14 Mark]
● UML diagrams- Class diagram, Activity diagram, Use case diagram[8 or
6 Mark]
● JVM and Byte code [3 or 5 Mark]
● JRE,JDK,JIT Compiler[3 Mark]
● Garbage Collection [3 or 5 Mark]
● Lexical Issues(Tokens) [10 or 14 Mark]
● Java features (Buzzwords) [10 or 14 Mark]

MODULE 2

● Type Conversion and Casting with example[3 Mark]


● Data types in java [8 or 10 Mark]
● Operators in java [8 or 10 Mark]
● Type of constructors in java(with sample code) [8 Mark]
● Method overloading and overriding with sample code[10 Mark]
● This keyword with example [3 or 5 Mark]
● Super and final keyword with example
● Abstract class[8 Mark]
● Command line arguments(3 Mark)
● **Programs

MODULE 3

● Packages and it’s accessing methods[8 or 10 Mark]


● Interfaces in java with example [8 or 10 Mark]
● Types of java Exception with example[3 or 6 Mark]
● Exception handling try, catch, throw, throws, finally with sample code(10
Mark)
● Difference between throw and throws(3 Mark)
● Serialization with sample code.
● **Programs-Package creation, File Handling

MODULE 4

● String constructors [6 or 8 Mark]


● Special String Operations-Character Extraction, String Comparison,
Searching Strings, Modifying Strings, valueOf().
● Collections in java- collection interface and list interface [8 or 10 Mark]
● Thread life cycle [8 Mark]
● Thread creation (By extending Thread class and By implementing
Runnable interface.)[8 Mark]
● Thread synchronization-with sample code(Using Synchronized keyword and
Synchronized block)[8 or 10 Mark]
● Delegation Event Model
● Event handling Methods
● **Programs- Thread Creation, Strings

MODULE 5

● Swing and its features


● Difference between AWT and Swing[3 Mark]
● Model View architecture[6 Mark]
● Components and containers [3 Mark]
● JDBC Architecture[6 or 8 Mark]
● Java Database Connectivity with MySql, steps and Program(14 Marks)
● **Swing Programs

Note: Mark distribution may differ


CST 205: MODULE 1

MODULE 1
INTRODUCTION:

Approaches to Software Design - Functional Oriented Design, Object Oriented Design, Case
Study of Automated Fire Alarm System.

Object Modeling Using Unified Modeling Language (UML) – Basic Object Oriented concepts,
UML diagrams, Use case model, Class diagram, Interaction diagram, Activity diagram, State chart
diagram.

Introduction to Java - Java programming Environment and Runtime Environment, Development


Platforms -Standard, Enterprise. Java Virtual Machine (JVM), Java compiler, Bytecode, Java
applet, Java Buzzwords, Java program structure, Comments, Garbage Collection, Lexical Issues.
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1

Example:
CST 205: MODULE 1

Example:

MULTIPLICITY
Indicates how many objects of each class taken part in relationship.
CST 205: MODULE 1

EXAMPLE 1: Class diagram for ATM System

NB: (Assign type of value returned in this diagram as I described during class)
CST 205: MODULE 1

EXAMPLE 2: CLASS DIAGRAM FOR HOTEL MANAGEMENT SYSTEM


CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1

ONLINE SHOPPING SYSTEM USE CASE

UML - INTERACTION DIAGRAMS


From the term Interaction, it is clear that the diagram is used to describe some type of
interactions among the different elements in the model. This interaction is a part of dynamic
behavior of the system.

This interactive behavior is represented in UML by two diagrams known as Sequence


diagram and Collaboration diagram. The basic purpose of both the diagrams are
similar.

Sequence diagram emphasizes on time sequence of messages and collaboration


diagram emphasizes on the structural organization of the objects that send and receive
messages.
CST 205: MODULE 1

Purpose of Interaction Diagrams


The purpose of interaction diagrams is to visualize the interactive behavior of the system.
Visualizing the interaction is a difficult task.

Sequence and collaboration diagrams are used to capture the dynamic nature but from a
different angle.

The purpose of interaction diagram is −

 To capture the dynamic behaviour of a system.

 To describe the message flow in the system.

 To describe the structural organization of the objects.

 To describe the interaction among objects.

How to Draw an Interaction Diagram?


As we have already discussed, the purpose of interaction diagrams is to capture the
dynamic aspect of a system. So to capture the dynamic aspect, we need to understand what
a dynamic aspect is and how it is visualized. Dynamic aspect can be defined as the
snapshot of the running system at a particular moment.

Following things are to be identified clearly before drawing the interaction diagram:

 Objects taking part in the interaction. 

 Message flows among the objects.

 The sequence in which the messages are flowing. 

 Object organization.

1) The Sequence Diagram


EG:- The following sequence diagram has four objects (Customer, Order, SpecialOrder
and NormalOrder).
CST 205: MODULE 1

The following diagram shows the message sequence for SpecialOrder object and the same
can be used in case of NormalOrder object. It is important to understand the time sequence
of message flows. The message flow is nothing but a method call of an object.

The first call is sendOrder () which is a method of Order object. The next call is confirm
() which is a method of SpecialOrder object and the last call is Dispatch () which is a
method of SpecialOrder object. The following diagram mainly describes the method calls
from one object to another, and this is also the actual scenario when the system is running.
CST 205: MODULE 1

2) Collaboration Diagram
The second interaction diagram is the collaboration diagram. It shows the object
organization as seen in the following diagram. In the collaboration diagram, the method
call sequence is indicated by some numbering technique. The number indicates how the
methods are called one after another. We have taken the same order management system
to describe the collaboration diagram.

Method calls are similar to that of a sequence diagram. However, difference being the
sequence diagram does not describe the object organization, whereas the collaboration
diagram shows the object organization.

To choose between these two diagrams, emphasis is placed on the type of requirement. If
the time sequence is important, then the sequence diagram is used. If organization is
required, then collaboration diagram is used.

Interaction diagrams can be used −


CST 205: MODULE 1

 To model the flow of control by time sequence.

 To model the flow of control by structural organizations.

 For forward engineering. 

 For reverse engineering.

ACTIVITY DIAGRAMS
Activity diagram is another important diagram in UML to describe the dynamic aspects
of the system.

Activity diagram is basically a flowchart to represent the flow from one activity to
another activity. The activity can be described as an operation of the system.

The control flow is drawn from one operation to another. This flow can be sequential,
branched, or concurrent.

Purpose of Activity Diagrams


It captures the dynamic behavior of the system. Activity diagram is used to show message
flow from one activity to another.

Activity is a particular operation of the system. Activity diagrams are not only used for
visualizing the dynamic nature of a system, but they are also used to construct the
executable system by using forward and reverse engineering techniques. The only missing
thing in the activity diagram is the message part.

It does not show any message flow from one activity to another. Activity diagram is
sometimes considered as the flowchart. Although the diagrams look like a flowchart, they
are not. It shows different flows such as parallel, branched, concurrent, and single.

The purpose of an activity diagram can be described as −

 Draw the activity flow of a system.


CST 205: MODULE 1

 Describe the sequence from one activity to another.

 Describe the parallel, branched and concurrent flow of the system.

How to Draw an Activity Diagram?


Activity diagrams are mainly used as a flowchart that consists of activities performed by
the system. Activity diagrams are not exactly flowcharts as they have some additional
capabilities. These additional capabilities include branching, parallel flow, swimlane, etc.

Before drawing an activity diagram, we must have a clear understanding about the
elements used in activity diagram. The main element of an activity diagram is the activity
itself. An activity is a function performed by the system. After identifying the activities,
we need to understand how they are associated with constraints and conditions.

Before drawing an activity diagram, we should identify the following elements −

 Activities

 Association

 Conditions

 Constraints

Once the above-mentioned parameters are identified, we need to make a mental layout of
the entire flow. This mental layout is then transformed into an activity diagram.

Following is an example of an activity diagram for order management system. In the


diagram, four activities are identified which are associated with conditions. One important
point should be clearly understood that an activity diagram cannot be exactly matched
with the code. The activity diagram is made to understand the flow of activities and is
mainly used by the business users

Following diagram is drawn with the four main activities −

 Send order by the customer


CST 205: MODULE 1

 Receipt of the order

 Confirm the order

 Dispatch the order

After receiving the order request, condition checks are performed to check if it is normal
or special order. After the type of order is identified, dispatch activity is performed and
that is marked as the termination of the process.

Where to Use Activity Diagrams?


The basic usage of activity diagram is similar to other four UML diagrams. The specific
usage is to model the control flow from one activity to another. This control flow does not
include messages.

Activity diagram is suitable for modeling the activity flow of the system. An application
can have multiple systems. Activity diagram also captures these systems and describes the
CST 205: MODULE 1

flow from one system to another. This specific usage is not available in other diagrams.
These systems can be database, external queues, or any other system.

We will now look into the practical applications of the activity diagram. From the above
discussion, it is clear that an activity diagram is drawn from a very high level. So it gives
high level view of a system. This high level view is mainly for business users or any other
person who is not a technical person.

This diagram is used to model the activities which are nothing but business requirements.
The diagram has more impact on business understanding rather than on implementation
details.

Activity diagram can be used for −

 Modeling work flow by using activities. 

 Modeling business requirements.

 High level understanding of the system's functionalities.

 Investigating business requirements at a later stage.

STATECHART DIAGRAMS
Statechart diagram define different states of an object during its lifetime and these states
are changed by events.

Statechart diagrams are useful to model the reactive systems. Reactive systems can be
defined as a system that responds to external or internal events.

Statechart diagram describes the flow of control from one state to another state. States
are defined as a condition in which an object exists and it changes when some event is
triggered. The most important purpose of Statechart diagram is to model lifetime of an
object from creation to termination.
CST 205: MODULE 1

Statechart diagrams are also used for forward and reverse engineering of a system.
However, the main purpose is to model the reactive system.

Following are the main purposes of using Statechart diagrams −

 To model the dynamic aspect of a system.

 To model the life time of a reactive system.

 To describe different states of an object during its life time.

 Define a state machine to model the states of an object.

How to Draw a Statechart Diagram?


Statechart diagram is used to describe the states of different objects in its life cycle.
Emphasis is placed on the state changes upon some internal or external events. These
states of objects are important to analyze and implement them accurately.

Statechart diagrams are very important for describing the states. States can be identified
as the condition of objects when a particular event occurs.

Before drawing a Statechart diagram we should clarify the following points −

 Identify the important objects to be analyzed.

 Identify the states.

 Identify the events.

Following is an example of a Statechart diagram where the state of Order object is


analyzed.

The first state is an idle state from where the process starts. The next states are arrived for
events like send request, confirm request, and dispatch order. These events are responsible
for the state changes of order object.
CST 205: MODULE 1

During the life cycle of an object (here order object) it goes through the following states
and there may be some abnormal exits. This abnormal exit may occur due to some problem
in the system. When the entire life cycle is complete, it is considered as a complete
transaction as shown in the following figure. The initial and final state of an object is also
shown in the following figure.

Where to use Statechart Diagrams?


Statechart diagram defines the states of a component and these state changes are dynamic
in nature. Its specific purpose is to define the state changes triggered by events. Events are
internal or external factors influencing the system.

Statechart diagrams are used to model the states and also the events operating on the
system. When implementing a system, it is very important to clarify different states of an
object during its life time and Statechart diagrams are used for this purpose. When these
CST 205: MODULE 1

states and events are identified, they are used to model it and these models are used during
the implementation of the system.

If we look into the practical implementation of Statechart diagram, then it is mainly used
to analyze the object states influenced by events. This analysis is helpful to understand the
system behavior during its execution.

The main usage can be described as −

 To model the object states of a system.

 To model the reactive system. Reactive system consists of reactive objects.

 To identify the events responsible for state changes. 

 Forward and reverse engineering. 

INTRODUCTION TO JAVA
Java is a high-level programming language originally developed by Sun Microsystems
and released in 1995. Java runs on a variety of platforms, such as Windows, Mac OS, and
the various versions of UNIX. The language was developed by James Gosling.

ADVANTAGES / CHARACTERISTICS OF JAVA PROGRAMMING

(JAVA BUZZWORDS)
 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
CST 205: MODULE 1

web and interpreted by the Java 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. Java is similar to C++, but with most of
the more complex features of C and C++ removed. 

Java does not provide:

o Programmer-controlled dynamic memory


o Pointer arithmetic
o struct
o typedefs
o #define

 Secure − With Java's secure feature it enables to develop virus-free, tamper-free


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

JAVA PROGRAMMING ENVIRONMENT

Java is a recently developed, concurrent, class-based, object-oriented programming and


runtime environment, consisting of:

 A programming language
CST 205: MODULE 1

 An API specification
 A virtual machine specification

 JAVA RUNTIME ENVIRONMENT(JRE)

Java runtime, or Java runtime environment (JRE), is a set of the minimum components
necessary to create and run a Java application and is part of a Java development kit (JDK).

It is made up of the Java virtual machine (JVM), Java class libraries, and the Java class
loader. So, while a developer would use a JDK to develop Java software, a JRE is made
up of tools used to program and run Java applications, and a JVM is a kind of computer-
within-a-computer, the purpose of which is to execute a Java program.
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1

JAVA DEVELOPMENT PLATFORMS

(STANDARD & ENTERPRISE EDITIONS)

There are four platforms of the Java programming language:

 Java Platform, Standard Edition (Java SE)


 Java Platform, Enterprise Edition (Java EE)
 Java Platform, Micro Edition (Java ME)
 Java FX

All Java platforms consist of a Java Virtual Machine (VM) and an application
programming interface (API). The Java Virtual Machine is a program, for a particular
hardware and software platform, that runs Java technology applications. An API is a
collection of software components that you can use to create other software components
or applications. Each Java platform provides a virtual machine and an API, and this
allows applications written for that platform to run on any compatible system with all
the advantages of the Java programming language: platform-independence, power,
stability, ease-of-development, and security.

 Java SE

When most people think of the Java programming language, they think of the Java
SE API. Java SE's API provides the core functionality of the Java programming
language. It defines everything from the basic types and objects of the Java
CST 205: MODULE 1

programming language to high-level classes that are used for networking, security,
database access, graphical user interface (GUI) development, and XML parsing.

In addition to the core API, the Java SE platform consists of a virtual machine,
development tools, deployment technologies, and other class libraries and toolkits
commonly used in Java technology applications.

 Java EE

The Java EE platform is built on top of the Java SE platform. The Java EE platform
provides an API and runtime environment for developing and running large-scale,
multi-tiered, scalable, reliable, and secure network applications.

JAVA VIRTUAL MACHINE (JVM)

The Java Virtual Machine is called JVM, is an abstract computing machine or


virtual machine interface that drives the java code.

• JVM stands for Java Virtual Machine.

• JVM is the engine that drives the java code.

• Mostly in other Programming Languages, compiler produce code for a particular


system but Java compiler produce Bytecode for a Java Virtual Machine.

• Bytecode is an intermediary language between Java source and the host system.

• It is the medium which compiles Java code to bytecode which gets interpreted on
a different machine and hence it makes it Platform/Operating system independent.
CST 205: MODULE 1

Java is called platform independent because of Java Virtual Machine. As different


computers with the different operating system have their own JVM, when we submit
a .class file to any operating system, JVM interprets the bytecode into machine level
language.

 JVM is the main component of Java architecture and it is the part of the JRE (Java
Runtime Environment).
 A program of JVM is written into “ C Programming Language” aqnd JVM is
Operating System dependent.
 JVM is responsible to allocate the necessary memory needed by the Java program.
 JVM is responsible to deallocate memory space.
CST 205: MODULE 1

JAVA APPLET
CST 205: MODULE 1

Applet implementation ways


CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1
CST 205: MODULE 1

LEXICAL ISSUES
Java programs is a collection of White spaces , Identifiers , comments , Literals ,
Operators ,Separators and Keywords.

1. White Spaces

Java is a free form language. This means that you do not need to follow any special
indentation rules. In java, white spaces is a space , tab or new line.
CST 205: MODULE 1

2. Identifiers

Identifiers are used for class names, method names and variable names. An identifier may
be any descriptive sequence of uppercase and lowercase letters, numbers or the
underscore and dollar sign design.

3. Literals (Constants)

A constant value in java is created by using a literal representation of it. A literal can be
used anywhere a value of its type is allowed.

4. Comments

First is single line comment (//)and the second one is multi line comment. (/*….*/)

5. Separators

There are few symbols in java that are used as [Link] most commonly used
separator in java is the semicolon ' ; '. some other separators are Parentheses '( )' , Braces '
{} ' , Bracket ' [] ' , Comma ' , ' , Period ' . ' .

6. Java Keywords

There are 49 reserved keywords currently defined in java. These keywords cannot be
used as names for a variable, class or method.

The Keywords are : abstract , assert , Boolean , break , byte , case , catch , char , class ,
const , continue , default , do , double , else , 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.
CST 205: MODULE 1

GARBAGE COLLECTION
Java garbage collection is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual
Machine, or JVM for short. When Java programs run on the JVM, objects are created on
the heap, which is a portion of memory dedicated to the program. Eventually, some objects
will no longer be needed. The garbage collector finds these unused objects and deletes
them to free up memory.

How Java Garbage Collection Works?


Java garbage collection is an automatic process. The programmer does not need to
explicitly mark objects to be deleted. The garbage collection implementation lives in the
JVM. Each JVM can implement garbage collection however it pleases; the only
requirement is that it meets the JVM specification. Although there are many JVMs,
Oracle’s HotSpot is by far the most common. It offers a robust and mature set of garbage
collection options.

BASIC STRUCTURE OF A JAVA PROGRAM


The structure of a java program consists of:

1. Documentation Section
2. Package Statement
3. Import Statement
4. Interface Section
5. Class Definition
6. Main Method Class

Documentation Section
It is used to improve the readability of the program. It consists of comments in Java which
include basic information such as the method’s usage or functionality to make it easier for
CST 205: MODULE 1

the programmer to understand it while reviewing or debugging the code. A Java comment
is not necessarily limited to a confined space, it can appear anywhere in the code.
There are three types of comments that Java supports

 Single line Comment


 Multi-line Comment
 Documentation Comment

Package Statement

There is a provision in Java that allows you to declare your classes in a collection
called package. There can be only one package statement in a Java program and it has to
be at the beginning of the code before any class or interface declaration.

Import Statement

Many predefined classes are stored in packages in Java, an import statement is used to refer
to the classes stored in other packages. An import statement is always written after the
package statement but it has to be before any class declaration.

Interface Section

This section is used to specify an interface in Java. It is an optional section which is mainly
used to implement multiple inheritance in Java. An interface is a lot similar to a class in
Java but it contains only constants and method declarations.

Main Method Class

The main method is from where the execution actually starts and follows the order
specified for the following statements. Let’s take a look at a sample program to understand
how it is structured.
CST 205: MODULE 1

Example:
public class Example //main() should be declared inside the class and use this
//class name as program name, eg: [Link]
{
public static void main (String args []) // main method declaration
{
[Link](“hello world”); //printing statement
}
}

Let’s analyze the above program line by line to understand how it works.

public class Example


This creates a class called Example. You should make sure that the class name starts with
a capital letter, and the public word means it is accessible from any other classes.
CST 205: MODULE 1

Comments
To improve the readability, we can use comments to define a specific note or functionality
of methods, etc for the programmer.

Braces
The curly brackets are used to group all the commands together. To make sure that the
commands belong to a class or a method.

public static void main()


 When the main method is declared public, it means that it can be used outside of
this class as well.
 The word static means that we want to access a method without making its objects.
As we call the main method without creating any objects.
 The word void indicates that it does not return any value. The main is declared as
void because it does not return any value.
 Main is the method, which is an essential part of any Java program.

String[] args
It is an array where each element is a string, which is named as args. If you run the Java
code through a console, you can pass the input parameter. The main() takes it as an input.

[Link]();
The statement is used to print the output on the screen where the system is a predefined
class, out is an object of the PrintWriter class. The method println prints the text on the
screen with a new line. All Java statements end with a semicolon.

JAVA COMMENTS
The Java comments are the statements that are not executed by the compiler and
interpreter. The comments can be used to provide information or explanation about
the variable, method, class or any statement. It can also be used to hide program code.

Types of Java Comments


There are three types of comments in Java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
CST 205: MODULE 1

1) JAVA SINGLE LINE COMMENT (//)


The single line comment is used to comment only one line.

Syntax:

// This is single line comment

Example:

public class Abc


{
public static void main(String args[ ] )
{
int i=10; //Here, i is a variable
[Link](i);
}
}
CST 205: MODULE 1

Output:

10

2) JAVA MULTI LINE COMMENT (/* */)


The multi line comment is used to comment multiple lines of code.

Syntax:

/*
This
is
multi line
comment
*/

Example:

public class Abc


{
public static void main(String args[])
{
/* Let's declare and
print variable in java. */
int i=10;
[Link](i);
}
}

Output:

10

3) JAVA DOCUMENTATION COMMENT


The documentation comment is used to create documentation API. To create
documentation API, you need to use javadoc tool.

Syntax:
CST 205: MODULE 1

/**
This
is
documentation
comment
*/

Example:

/** The Calculator class provides methods to get addition and subtraction of given 2 num
bers.*/
-
public class Calculator
{
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b)
{
return a+b;
}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b)
{
return a-b;
}
}
-

Compile it by javac tool:

javac [Link]

Create Documentation API by javadoc tool:

javadoc [Link]

Now, there will be HTML files created for your Calculator class in the current directory.
Open the HTML files and see the explanation of Calculator class provided through
documentation comment.
CST 205 OBJECT ORIENTED PROGRAMMING IN JAVA
MODULE 1 IMPORTANT QUESTIONS AND ANSWERS

1. Explain different approaches in software designing.


2. Compare approaches in software designing.
3. Compare Function (Procedure) Oriented Approach (POP) with Object Oriented Approach (OOP)
Answer
Procedure Oriented Approach: Importance is for functions rather than data.
● Top-Down Decomposition: POP starts at high level view of a system which refines high
level function to low level functions. Consider an example of a Student Management System
which consist of a high level function enrollStudent(). For enrolling a student some other
internal activities are carried out which includes, student record creation, course selection
and fee payement. These activities can be identified as low level functions of the high level
function enrollStudent(). Thus enrollStudent() can be further divided into low level functions
such as createStudent(), selectCourse(), payFees().
● Centralized State System: In POP various functions share data, so that the system state is
centralized. For example, in Student Management System, the data “StudentRecord” will be
shared by various functions such as a createStudent(), deleteStudent(), updateStudent() for
making updation regarding Students.
● Free Data Flow: Since POP follows Centralized State System, data flows freely between the
functions. The changes made by function on a data will affect other functions too.
● Less Secure: POP doesn’t have any access control mechanisms which makes data less secure.
Object Oriented Programming: Importance is for data rather than functions
● Bottom-Up Approach: OOPs first identifies classes then identifies the required high level
member functions. For example in a Student Management System, using OOPs we can
identify Student and Teacher classes. Student class may consist of functions like
enrollCourse(), viewAttendance(), viewMarks() etc.. Whereas, Teacher class may consist of
functions like uploadNotes(), enterAttendance(), enterMarks()…
● Decentralized State System: In OOPs every class have its own member data and methods.
So, the variables(data) aren’t shared globally.
● Restricted Data Flow: In OOPs objects of a class holds the data regarding that class which
can’t be directly accessed by any other classes. Data of a class can be only accessed from
another class by invoking methods.
● Highly Secure: Since OOPs provides access control mechanisms, data can be created as
private or protected in a class which makes it inaccessible from other classes.
4. Explain an example case Study of Procedure Oriented Programming and Object-Oriented
Programming
5. Explain case Study of an Automated Fire Alarm System
Answer
Procedure Oriented Design
● First identify and list global data (normal or array variables with data type)
● The identify and list different functions (needs your imagination, if given read
the requirement para carefully and identify functions) that share the global data.
● In case of an Automated Fire Alarm System using POP, following are the
1. GLOBAL DATA
BOOL detector_status[Max_Rooms]; // an array variable which stores the
status(ON/OFF) of fire detector installed at all rooms(Max Rooms) in the hotel.
int detector_locs[Max_Rooms]; // an array variable to store the locations of activated
fire detectors (Max Rooms) in the hotel.
BOOL alarm_status[Max_Rooms]; //an array variable which stores the
status(ON/OFF) of fire alarms installed at all rooms(Max Rooms) in the hotel.
int alarm_locs[Max_Rooms]; // an array variable to store the locations of activated fire
alarms at all rooms(Max Rooms) in the hotel.
int neighbor_alarms[Max_Rooms][10] ; // a multi-dimensional array variable to store
neighbouring alarms of a fire detector. Each detector have 10 neighboring alarms.
int sprinkler[Max_Rooms]; // an array variable to store information of sprinklers
installed at all rooms.

*note: Since there are many rooms, fire detectors, alarms, sprinklers, corresponding data needs
to store in array variables.

2. HIGH LEVEL FUNCTIONS


interrogate_detectors() // a function to check the status of detectors
get_detectorLocatation() // a function to get location of currently activated fire detectors
determine_neighbour_alarm() // a function to identify neighboring alarms of currently
activated detectors
determine_neighbour_sprinklers() // a functions to identify sprinklers near activated fire
detector
ring_alarm() // function to activate alarms near activated fire detectors.
activate_Sprinkler() //function to activate identified sprinklers neighboring to activated
fire
detectors
reset_alarm() //function to reset alarms after fire has been handled
reset_sprinkler() //function to reset sprinklers

Object Oriented Programming


● First identify the classes required in the system.
● Then for each class, identify member variables(attributes) and member functions(operations)
● In case of an Automated Fire Alarm System using OOP, following are the
● Classes: detector, alarm, sprinkler
● List Members of each class
1. class Detector
attributes(variables): status, location, neighbors
operations(functions): create, senseStatus, getLocation, findNeighbors
2. class Alarm
attributes(variables): location, status
operations(functions): create, ringAlarm, getLocation, findNeighbor, resetAlarm
3. class Sprinkler
operations(functions): create, activateSprinkler, getLocation
resetSprinkler
6. Explain the need of UML. What are the advantages?
Answer
● UML stands for Unified Modeling Language.
● It is a general-purpose modeling language used for developing object oriented softwares.
● Includes several graphical notations that drives the software development task and can be
through out the software development lifecycle.
● Following are the advantages of using UML:
1. Enhances communication and collaboration between Project team members: It
contains standard design information which can be shared among developers.
2. Provides a Better understanding of the system requirements, relation between various
entities, operations, data and workflow.
3. Unifies design by providing a standard way to design software and systems.
4. Saves time since during development and testing UML Diagrams acts as a reference.
7. How classes are represented in a class diagram. Show the representation of Student class.
Answer
● Foremost, a class consist of member variables and member functions.
● UML class representation must include the list of these members inside a Rectangle box
as shown:

● A Student class can be represented as follows:

● Inside the box First row represents class name


● Second row represents member variables listed as
access_specifier var_name : datatype
● Third row represents member functions
access_specifier function_name(para1:type, para2:type…): returntype
● Access specifier + (public), -(private), *(protected)
8. Draw a use case diagram for Online Music Player

Answer
● For drawing an use case diagram first and foremost identify the actors (users)who are going
to interact with the system:
In the case of Online Music Player, following are the actors: Listeners, Admin
● Now Identify various usecases (operations) associated with each
user Listeners: Login, SearchMusic, PlayMusic, Stop,
ChangeSettings Admin: Login, ManageUser, ManageSongs

LOGIN

SEARCH

MANAGE
USER
PLAY

MANAGE

STOP SONGS

CHANGE

9. Explain Java Runtime Environment and Programming Environment


Answer
● Java runtime environment (JRE) is a set of components used to create and run Java
Applications.
● JRE is a part of Java Development Kit (JDK).
● JRE consists of 3 components: Class Loader, Java Class Libraries and JVM.
● JRE runs on top of OS to provide additional Java Specific resources.
● The components of JRE works together to provide an environment for Java application
development and deployment.
ClassName

Member Variables

Member Functions

Student

+name : String
+rn : int
+rank : int
- fees : long
+
displayDetails(n:Stri
ng, r: int) : void
+displayRank(
ra:int): void

● JRE acts as a translator and facilitator, so that Java programs are portable from one system to
another without modifications.
● Java Class libraries contains predefined functions that can be called whenever required.
● Class Loader connects Class Libraries and JVM by loading the required libraries to JVM.
● JVM is the part that executes the code.
● Java Programming Environment consist of a programming language, API Specification and a
Virtual Machine.
10. Explain ByteCodes and JVM.
11. Why java is Platform Independent? Give reasons.
12. Why Java programs are called WORA (Write Once Run Anywhere)
Answer
● Bytecode and JVM in Java is the reason java is platform-independent.
● Bytecodes are generated in .class format when a program is successfully compiled for the first
time.
● It is the instruction set for Java Virtual Machine (JVM).
● When a Java program is executed, the compiler compiles
that piece of code and a Bytecode is generated for each
method in that program in the form of a .class file.
● We can run this bytecode on any other platform as well.
But the bytecode is a non-runnable code that requires or
relies on an interpreter. This is where JVM plays an
important part.
● The bytecode generated after the compilation is run by the
Java virtual machine. Resources required for the
execution are made available by the Java virtual machine
for smooth execution which calls the processor to allocate
the resources.
● JVM (Java Virtual Machine) acts as a run time engine to run Java based applications. It is the
part that invokes main function of a Java Program.
● Java applications are called WORA (Write Once Run Anywhere). This means a
programmer can develop Java code on one system and can expect it to run on any other
Java-enabled system without any adjustment. This is all possible because of JVM.
● When we compile a .java file, .class files (contains byte-code) with the same class
names present in .java file are generated by the Java compiler.

13. Explain different Java Development Platforms


Answer

There are three platforms of the Java programming language:


• Java Platform, Standard Edition (Java SE)
• Java Platform, Enterprise Edition (Java EE)
• Java Platform, Micro Edition (Java ME)
• All Java platforms consist of a Java Virtual Machine (VM) and an application
programming interface (API). The Java Virtual Machine is a program, for a particular
hardware and software platform, that runs Java applications. An API is a collection of
software components that you can use to create other software components or
applications.
• Standard Edition (Java SE): Java SE’s API offers the Java programming language’s
core functionality. It defines all the basis of type and object to high-level classes. It is used
for networking, security, database access, graphical user interface (GUI) development, and
XML parsing.
• Enterprise Edition (Java EE): The Java EE platform offers an API and runtime
environment for developing and running highly scalable, large-scale, multi-tiered, reliable,
and secure network applications.
• Micro Edition (Java ME): The Java ME platform offers an API and a small-footprint
virtual machine running Java programming language applications on small devices, like
mobile phones.
14. Explain Java Applets

15. Compare Java Applets and Standalone Java Applications

Answer

Java Applications
● They are normal java programs that require a main () function.
● Have full access to local storage.
● Trusted by OS.
● For execution a web browser isn’t
required Example:
class Sample
{
public static void main(String args[])
{

}
}
Java Applets
● Applets are programs that can be embedded in an HTML website.
● It runs inside a web browser and requires an extension of JDK to be installed in the browser
for execution.
● Doesn’t have full access to local storage, can’t read and write without permission.
● It doesn’t require a main() method for its execution.
● A java applet program consist of following functions: init(), start() and paint().

Example:

import
[Link];
import [Link];
// importing necessary packages
public class SampleApplet extends Applet //class must extend Applet class in java
{
public void paint(Graphics g) // paint function includes all graphics related operations
{
// printing the message using drawString() method
// other parameters are of the position
[Link]("Java Applet", 250, 250);
}
}
16. Explain Java Buzzwords. (Properties of Java Programming Language)

Answer
● Object oriented - Java provides the basic object technology of C++ with some enhancements
and some deletions.
● Architecture neutral - Java source code is compiled into architecture-independent object
code. The object code is interpreted by a Java Virtual Machine (JVM) on the target
architecture.
● Portable - Java implements additional portability standards. For example, ints are always 32-
bit, 2's-complemented integers. User interfaces are built through an abstract window system
that is readily implemented in Solaris and other operating environments.
● Distributed - Java contains extensive TCP/IP networking facilities. Library routines support
protocols such as HyperText Transfer Protocol (HTTP) and file transfer protocol (FTP).
● Robust - Both the Java compiler and the Java interpreter provide extensive error checking.
Java manages all dynamic memory, checks array bounds, and other exceptions.
● Secure - Features of C and C++ that often result in illegal memory accesses are not in the
Java language. The interpreter also applies several tests to the compiled code to check for
illegal code. After these tests, the compiled code causes no operand stack over- or underflows,
performs no illegal data conversions, performs only legal object field accesses, and all opcode
parameter types are verified as legal.
● High performance - Compilation of programs to an architecture independent machine-like
language, results in a small efficient interpreter of Java programs. The Java environment also
compiles the Java bytecode into native machine code at runtime.
● Multithreaded - Multithreading is built into the Java language. It can improve interactive
performance by allowing operations, such as loading an image, to be performed while
continuing to process user actions.
● Dynamic - Java does not link invoked modules until runtime.
● Simple - Java is similar to C++, but with most of the more complex features of C and C++
removed.

17. Explain Object Oriented Concepts.


Answer
1. Classes: Class is a collection of objects that share common traits. It can be used as a template
for creating the objects. Class consists of member variables and methods that are common to all
objects of that class. Member variables represents data associated with the objects and methods
corresponds to operations that can be carried out by the objects.

Eg: Consider a Student class.

- Member variables associated with Student class are: name, rollno, marks, rank, fees…
- Methods associated with Student class are: displayDetails(), payFees() etc…

2. Objects: Instance of a class. All objects belonging to a class share common variables and
methods. However the values of variables differ across objects.
Eg: In a Student class, objects will be different students say stud1, stud2, stud3…..All these objects
have name, rollno, marks, rank and fees that may contain different values. In addition all these
objects can perform the operations displayDetails(), payFees() defined in class Student.
3. Encapsulation: Wrapping up of data and methods into a single entity. The only way to access
data is through methods.

In the above example Employee class is trying to access the Teachers data through the member
method displayDetails() of class Teachers. It is possible because the data and methods of classes are
wrapped as a single entity by means of encapsulation.

4. Inheritance: It is a process by which object of one class inherit the properties of objects of
another class. It is the capability to define a new class in terms of an existing class. The existing class
or Parent class is known as a base class or super class and the new class or child class is known as
derived class or sub class. Inheritance supports code reusability.

Example : Consider a parent class named Vehicle and its members as given in the figure.

• Vehicle is a class having member variables String reg_no, model, color, int
fuel_capacity and member functions void vehicleDetails(), void fillfuel() and void
calculateSpeed().
• wo subclasses of the class Vehicle are created Car and Bus. The subclasses will inherit
the member variables and functions of Vehicle class. Car and Bus can have their own
member variables as shown in the figure.

5. Abstraction: Abstraction is the process of hiding certain details and showing only essential
information to the user. Abstraction can be achieved with either abstract classes or interfaces. Its main
goal is to handle complexity by hiding unnecessary details from the user. That enables the user to
implement more complex logic on top of the provided abstraction without understanding or even
thinking about all the hidden complexity.

Two types of Abstraction:

When the object data is not visible to the outer world, it


creates data abstraction. If needed, access to the Objects’
data is provided through some methods. In the example
member variables of the class are private members limiting
the access of data within the class.

When we hide the internal implementation of the different


functions involved in a user operation, it creates process
abstraction. In the example, several functions are private
members, thus hiding the implementation details from
outside world.
6. Polymorphism: An object or reference basically can take multiple forms in different
instances. As the word suggests, ‘poly’ means ‘many’ and ‘morph’ points at ‘forms’; thus,
polymorphism as a whole would mean ‘a property of having many forms.’

There are two types of polymorphism

● Dynamic Polymorphism
● Static Polymorphism

In Dynamic polymorphism, the object creation is done at run-time the form of method which should
be executed (the method in the object) can be only decided at run-time. Method Overriding is a type
of Dynamic polymorphism or Run Time Polymorphism. In method overriding, when functions of
same signature is used in both parent and child, the function of superclass will be overridden by the
subclass method.

In Static Polymorphism, method overloading happens. Method overloading is having more than one
method with the same method name but with different arguments (return type may or may not be
same). Here when calling the methods compiler compiler choose which method to call depending on
the parameters passed when calling. This happens at compile-time

18. Explain comments in Java.


19. What are the uses of comments? Explain different types of comments.
Answer
Comments can be used to explain Java code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.

Types: Single Line, Multi Line Comments & Documentation Comments

A Single-line comment starts and ends in the same line. To write a single-line comment, we can use
the // symbol. For example,
// "Hello, World!" program example
class Main
{
public static void main(String[] args)
{
// prints "Hello, World!"
[Link]("Hello, World!");
}
}

Teachers
int tid
String name, designation
void displayDetsils()
Employee
The Java compiler ignores everything from // to the end of line. Hence, it is also known as End of
Line comment.

Multi Line Comments: When we want to write comments in multiple lines, we can use the
multi- line comment. To write multi-line comments, we can use the /*. */ symbol. For example,

/* This is an example of multi-line comment.

* The program prints "Hello, World!" to the standard output.

*/

class HelloWorld {

public static void main(String[] args) {

[Link]("Hello, World!");

This type of comment is also known as Traditional Comment. In this type of comment, the Java
compiler ignores everything from /* to */.

Documentation Comments: This type of comment is used to produce an HTML file that documents
your program. The documentation comment begins with a /** and ends with a */ .

20. Explain various lexical issues in Java Programming Language.


Answer
• These are the atomic elements in a java program.
• Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
• Whitespace : Java is a free-form language. This means that you do not need to follow any
special indentation rules. In Java, whitespace is a space, tab, or newline. A program could be
written all on one line or in any other way, as long as there was at least one whitespace
character between each token that was not already delineated by an operator or separator.
• Identifiers: Identifiers are used to name things, such as classes, variables, and methods. An
identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the
underscore and dollar-sign characters. They must not begin with a number. Again, Java is
case- sensitive, so VALUE is a different identifier than Value. Some examples of valid
identifiers are
• Literals: A constant value in Java is created by using a literal representation of it. For
example, here are some literals:

• Comments: Comments can be used to explain Java code, and to make it more readable. It
can also be used to prevent execution when testing alternative code.

/* This is an example of multi-line comment and Single Line Comment.

* The program prints "Hello, World!" to the standard output.

*/

class HelloWorld {

public static void main(String[] args)

{ // Printing Hello World

[Link]("Hello, World!");

• Separators: In Java, there are a few characters that are used as separators. The most
commonly used separator in Java is the semicolon.
• Keywords: There are 50 keywords currently defined in the Java language. These keywords,
combined with the syntax of the operators and separators, form the foundation of the Java
language. These keywords cannot be used as identifiers. Thus, they cannot be used as names
for a variable, class, or method. The keywords const and goto are reserved but not used. In the
early days of Java, several other keywords were reserved for possible future use.

21. Explain Java Program Structure with example.


Answer
import packages; // import the required

packages public class ClassName

public static void main ( String args[ ] )

// program body

• All java programs are enclosed within a class.


• We can define multiple classes in a single program.
• class is the keyword used to create a class.
• Syntax: class ClassName

…………….

- ClassName of class must begin with uppercase alphabet.


• Save the program in the name of the class which contains the void main( ) function with .java
extension.

eg: [Link]

• Program starts execution from void main() function which is represented as

public static void main( String args[] )

….

- public : It has to be public so that java runtime can execute this method. If you make any
method non-public then it’s not allowed to be executed by any program, there are some access
restrictions applied.
- static : java runtime starts, there is no object of the class present. That’s why the main method
has to be static so that JVM can load the class into memory and call the main method. If the
main method won’t be static, JVM would not be able to call it because there is no object of
the class is present.
- void : Java programming mandates that every method provide the return type. Java main
method doesn’t return anything, that’s why it’s return type is void. This has been done to keep
things simple because once the main method is finished executing, java program terminates.
So there is no point in returning anything, there is nothing that can be done for the returned
object by JVM.
- main : This is the name of java main method. It’s fixed and when we start a java program, it
looks for the main method.
- String args[] : Java main method accepts a single argument of type String array. This is also
called as java command line arguments.

Example:
CST 205 MODULE 2
CST 205 MODULE 2

DATA TYPES IN JAVA


Java is rich in data types which allows the programmer to select the appropriate type
needed to store variables of an application.

 Every variable in Java has a data type which tells the compiler what type of
variable it as and what type of data it is going to store.
 It specifies the size and type of values.
 Information is stored in a computer memory with different data types.
 Whenever a variable is declared it becomes necessary to define a data type that
what will be the type of data that variable can hold.
Data Types available in Java are:

 Primitive Data Type


Java supports 8 primitive data types: byte, short, int, long, float, double, char and
boolean.
 Non-Primitive Data Types
Classes, Interface, Arrays etc.

Figure 21 : Data Types in JAVA

INTEGERS

Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values. Java does not support unsigned, positive-only integers.
CST 205 MODULE 2

Table 4 : Integer Data Tyes and Size

long 64 bit
int 32 bit
Short 16 bit
Byte 8 bit

i) byte
The smallest integer type is byte. This is a signed 8-bit. Variables of type byte are
especially useful

 When you’re working with a stream of data from a network or file.


 When you’re working with raw binary data that may not be directly compatible with
Java’s other built-in types.
Byte variables are declared by use of the byte keyword. For example, the following
declares two byte variables called b and c:
byte b, c;

ii) short

short is a signed 16-bit type. It is probably the least used Java type. Example
short s;

iii) int
The most commonly used integer type is int. In addition to other uses, variables of type
int are commonly employed to control loops and to index arrays. Example

int a;

iv) long
long is a signed 64-bit type and is useful for those occasions where an int type is not
large enough to hold the desired value. Example

long a;

FLOATING-POINT
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. There are two kinds of floating-point types, float and
double, which represent single- and double-precision numbers, respectively.
CST 205 MODULE 2

Table 5: Integer Data Types in JAVA

Type Contains Default Size Range


Byte Signed integer 0 8 bit -128 to 127
short Signed integer 0 16 bit -32,768 to 32767
Int Signed integer 0 32 bit -2147,483,648 to 2147,483,647

Long Signed integer 0 64 bit -9223,372,036,854,755,808 to


9223,372,036,854,755,807

float
The type float specifies a single-precision value that uses 32 bits of storage. Variables of
type float are useful when you need a fractional component, but don’t require a large degree of
precision.
Example: float hightemp, lowtemp;
double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. When you
need to maintain accuracy over many iterative calculations, or are manipulating large-valued numbers,
double is the best choice.
Table 6: Floating Point Data Types

float floating point 0.0f 32 bit


single-precision
double floating point 0.0 64 bit
double-precision

CHARACTERS
In Java, the data type used to store characters is char. Java uses Unicode to represent characters.
At the time of Java's creation, Unicode required 16 bits. Thus, in Java char is a 16- bit type.
Example: char letterA = 'A‘;
Table 7 : Character Data Type

char Unicode character unsigned \u0000 16 bits \u0000 to \uFFFF

BOOLEANS
Java has a primitive type, called boolean, for logical values. It can have only one of two
possible values, true or false. This is the type returned by all relational operators, as in the case of a
> b.
Example: boolean b;
Table 8 : boolean Data Type

Type Contains Default Size Range


boolean true or false false 1 bit true or false
CST 205 MODULE 2

JAVA OPERATORS
Java provides a rich set of operators’ environment. Java operators can be divided into following
categories:

 Arithmetic operators
 Relation operators
 Logical operators
 Bitwise operators
 Assignment operators
 Conditional operators
 Misc operators

Arithmetic operators
Arithmetic operators are used in mathematical expression in the same way that are used in
algebra.

Table 9 : Arithmetic Operators

+ adds two operands


- subtract second operands from first
* multiply two operand
/ divide numerator by denominator
% remainder of division
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one

Relation operators
The following table shows all relation operators supported by Java.

Table 10 : Relation operators

== Check if two operand are equal


!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand
CST 205 MODULE 2

Logical operators
Java supports following 3 logical operator. Suppose a=1 and b=0;

Table 11 : Logical Operators

&& Logical AND (a && b) is false


|| Logical OR (a || b) is true
! Logical NOT (!a) is false

Bitwise operators
Java defines several bitwise operators that can be applied to the integer types long, int, short,
char and byte

Table 12 : Bitwise Operators

& Bitwise AND


| Bitwise OR
^ Bitwise exclusive OR
>> left shift
<< right shift

Now let’s see truth table for bitwise &, | and ^

Table 13: Truth Table

0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

The bitwise shift operators shifts the bit value. The left operand specifies the value to be
shifted and the right operand specifies the number of positions that the bits in the value
are to be shifted. Both operands have the same precedence.

Example:
a = 0001000, b = 2
a << b = 0100000, a >> b = 0000010

Assignment Operators
Assignment operator supported by Java are as follows:
CST 205 MODULE 2

= assigns values from right side operands to left side operand a=b
+= adds right operand to the left operand and assign the result a+=b is same as
to left a=a+b
-= subtracts right operand from the left operand and assign a-=b is same as
the a=a-b
result to left operand
*= multiply left operand with the right operand and assign the a*=b is same as
result to left operand a=a*b
/= divides left operand with the right operand and assign the a/=b is same as
result to left operand a=a/b
%= calculate modulus using two operands and assign the result a%=b is same as
to left operand a=a%b

CONDITIONAL OPERATOR/ TERNARY


OPERATOR(?:)
It is also known as ternary operator and used to evaluate Boolean expression,
epr1 ? expr2 : expr3

If epr1Condition is true? Then value expr2: Otherwise value expr3

LITERALS IN JAVA
Literals is an identifier whose value is fixed and does not change during the execution of the program.
Types of Literals
CST 205 MODULE 2

Integer Literals
Integer Literals are numbers that has no fractional pars or exponent. It refers to the whole numbers. Integers
always begin with a digit or + or -.
We can specify integer constants in
 Decimal
 Octal
 Hexadecimal
Decimal Integer Literals
It consists of any combination of digits taken from the set 0 to 9.
Example:
int a = 100; //Decimal Constant
int b = -145 // A negative decimal constant
int c = 065 // Leading zero specifies octal constant, not decimal

Octal Integer Literals


It consists of any combination of digits taken from the set 0 to 7. However the first digit must be 0, in order
to identify the constant as octal number.
Example:
int a = 0374; //Octal Constant
int b = 097; // Error: 9 is not an octal digit.

Hexadecimal Integer Literals


A Sequence of digits begin the specification with 0X or 0x, shadowed by a system of digits in the range 0 to
9 and A (a) to F(f).
Example:
int a = 0x34;
int b = -0XABF;
CST 205 MODULE 2

Unsigned Literals
We use either u or U suffix for Unsigned Constants and use either the l or L suffix. for Long constants
Example :
328u 0x7FFFFFL 0776745ul;

Floating-point Literals
Floating-point Literals are also called as real constants. The Floating Point contains decimal points and can
contain exponents. They are used to represent values that will have a fractional part and can be represented
in two forms – fractional form and exponent form.
In the fractional form, the fractional number contains the integer part and fractional part. A dot (.) is used to
separate the integer part and fractional part.
Example:
float x = 2.7f;
In the exponential form, the fractional number contains constants a mantissa and exponent. Mantissa contains
the value of the number and the exponent contains the magnitude of the number. The exponent, if any present,
specifies the magnitude of the number as a power of 10.
Example:
7.6: 23.46e0 // 23.46 x 100 = 23.46 x 1 = 23.46 23.46e1 // 23.46 x 101= 23.46 x10 = 234.6

Character Literals
Character Literals are specified as single character enclosed in pair of single quotation marks. Single
character constants are internally represented as ASCII codes.
char a=’c’;

String Literals
String Literals are treated as an array of char. By default, the compiler adds a special character called the
‘null character’ (‘\0’) at the end of the string to mark the end of the string.
Example:
String str = “good morning”;

Boolean literals
There are two Boolean literals
 true represents a true Boolean value
 false represents a false Boolean value
CST 205 MODULE 2
ARRAY

Arrays refer to a named list of final number 'n' of similar data elements. Each of the data
elements can be referenced respectively by a set of consecutive numbers, usually 0,1,2,3. ... n.
If the name of an array of 10 elements is ARY, then its elements will be referenced as shown
below:

ARY[0] , ARY[1] , ARY[2] , ................. ARY[9] ;

Arrays can be one dimensional, two dimensional or multi dimensional.


One-Dimensional Arrays
Array is a finite,ordered,homogenous data structure. It is finite because it contains limited number of
elements. It is homogeneous because it contain same type of elements. It is ordered because all elements
are stored in continuous memory locations.

Array elements are accessed using array index or subscript.

Arrays are of 3 types

1) one dimensional
2) two dimensional
3) multi dimensional

ONE DIMENSIONAL ARRAYS

Array having one index are one dimensional arrays.


So there is only the single bracket in it.

Eg:- An array A having 5 elements means a[5](starting from index 0 to 4)

The Syntax For Declaring Array Elements in java is as Follows-

datatype arrayname[ ]=new datatype[size of array];

eg:- int a[ ] = new int [5];

import [Link].*;

class OneDimensionalArray
CST 205 MODULE 2

public static void main(String args[]) throws Exception

int i=0;
int a[] = new int[10];
String n;

[Link]("Enter the Elements");


BufferedReader obj=new BufferedReader(new InputStreamReader([Link]));

for(i=0;i< 5; i++)
{
n = [Link]();
a[i]=[Link](n);
}
[Link]("After the Inputting");
for(i=0; i< 5; i++)
{
[Link]("a[ "+i+"]"+"="+a[i]);
}
}
}
Two-Dimensional Arrays
The Two Dimensional array Elements are used when we Wants to Perform the Operation in Matrix Forms
the Two Dimensional arrays are used For Creating Matrix and Displaying array elements in the Form of
Rows and Columns The Total Elements of Arrays Will be Calculated by Multiplying the Elements of
Rows and Columns Like int a[3][3] i. e 9 Elements will be used by Array These are Called as Two
Dimensional Because they use two Brackets.

Eg:-
int a[][]=new int[3][3];
import [Link].*;
class TwoDimensionalArray
{
public static void main(String args[]) throws Exception
{
int a[ ][ ] = new int[2][3], sum = 0, r ,c;
String n;
[Link]("Enter the Elements");
BufferedReader obj=new BufferedReader(new InputStreamReader([Link]));
CST 205 MODULE 2

for(r=0;r< 2; r++)
{
for(c=0; c< 3; c++)
{
n = [Link]();
a[r][c]=[Link](n);
}
}
[Link]("After the Inputting");

for(r=0; r< 2; r++)


{
for(c=0; c < 3; c++)
{
[Link]("\t" +a[r][c]);
sum = sum + a[r][c];
}
[Link]("\n");
}
[Link]("Sum="+sum);
}
}

STRINGS
Like an integer characters are also be in the Array. The Array of Characters are called as the Strings . we
Know that when Collection of Characters are called as String.

In java for Creating an String array we use:-

String s[ ]=new String[10];

Here is the s is an array of type String Means it can accept only 10 Characters but if you will use String as
then:-

String s = new String("Welcome To Strings");

S is an object of Class String and now you can use any Method From String Class The Various String
Methods those are Reside in String Class are :-
CST 205 MODULE 2

A. ToLowerCase:- For Converting a String into small letters or in small cases.


B. ToUpperCase:- For Converting a String into Upper letters or in Upper cases.
C. Length:- For Calculating the Number of Characters in a String.
D. Trim:- For Removing both left and Right Side Spaces.
E. charAt:- For Finding a Character at the Position.
F. indexOf:- For Finding the Position of a Character in a String.
G. substring:- For Extracting a string from a string.
H. replace:- For Replacing a Character in the String.
I. compareTo:- For Comparing a String With another.
J. Concat:- For Joining Two strings and Making a Single String.

VECTORS
The Vector class implements a growable array of objects. Like an array, it contains components that can be
accessed using an integer index. However, the size of a Vector can grow or shrink as needed to
accommodate adding and removing items after the Vector has been created.

Each vector tries to optimize storage management by maintaining a capacity and a capacity Increment.
The capacity is always at least as large as the vector size; it is usually larger because as components are
added to the vector, the vector's storage increases in chunks the size of capacity Increment. An application
can increase the capacity of a vector before inserting a large number of components; this reduces the amount
of incremental reallocation.

Creating vector object by:

Vector list = new Vector();

TYPE CASTING/TYPE CONVERSION


Converting one primitive data type into another is known as type casting (type conversion) in Java.

You can cast the primitive data types in two ways namely:
i) Widening (Implicit type casting)
CST 205 MODULE 2

ii) Narrowing. (Explicit type casting)


i) Widening − Converting a lower data type to a higher data type is known as widening. In
this case the casting/conversion is done automatically therefore, it is known as implicit type
casting. In this case both data types should be compatible with each other.

Example

public class WideningExample

public static void main(String args[])


{

char ch = 'C';

int i = ch;

[Link](i);

}
Output
Integer value of the given character: 67
ii) Narrowing − Converting a higher data type to a lower data type is known as narrowing. In
this case the casting/conversion is not done automatically, you need to convert explicitly
using the cast operator “( )” explicitly. Therefore, it is known as explicit type casting. In this
case both datatypes need not be compatible with each other.

Example

import [Link];
CST 205 MODULE 2

public class NarrowingExample

public static void main(String args[])

Scanner sc = new Scanner([Link]);

[Link]("Enter an integer value: ");

int i = [Link]();

char ch = (char) i;

[Link]("Character value of the given integer: "+ch);

}
Output
Enter an integer value:
67
Character value of the given integer: C

CONTROL STATEMENTS IN JAVA


Java decision-making statements allow you to make a decision, based upon the
result of a condition.

I) SELECTION STATEMENTS


if Statement
o if statement
o if-else statement
o else-if statement
 switch statement
II) LOOPING/ITERATION STATEMENTS
 for
 while
 do while
CST 205 MODULE 2

III) JUMPING STATEMENTS


 break
 continue
 label
-
1) SELECTION STATEMENTS

1) Java if Statements
If statements in Java is used to control the program flow based on some
condition, it’s used to execute some statement code block if the expression is evaluated
to true, otherwise, it will get skipped. This is the simplest way to modify the control
flow of the program.
If statements in Java is used to control the program flow based on some
condition, it’s used to execute some statement code block if the expression is evaluated
to true, otherwise, it will get skipped. This is the simplest way to modify the control
flow of the program.

The basic format of if statement is:

Syntax:

if(test_expression)
{
CST 205 MODULE 2

statement 1;
statement 2;
...
}

‘Statement n’ can be a statement or a set of statements and if the test expression is


evaluated to
true, the statement block will get executed or it will get skipped.
Example of a Java Program to Demonstrate If
statements Example:
public class Sample
{
public static void main(String args[])
{
int number1=20, number2=30;

if(number1> number2)
[Link]("number1 is greater");
}
}

2) Java if-else Statements

If else statements in Java is also used to control the program flow based on some
condition, only the difference is: it’s used to execute some statement code block if the
expression is evaluated to true, otherwise execute else statement code block.

The basic format of if else statement is:

Syntax:
if(test_expression)
{
//execute your code
CST 205 MODULE 2

}
else
{
//execute your code
}
Example:
public class Sample
{
public static void main(String args[])
{
int number1 = 80, number2 = 30;
if(number1> number2)
{
[Link]("number1 is greater");
}
else
{
[Link]("number2 is greater");
}
}
}
3) Java else-if Statements

else if statements in Java is like another if condition, it’s used in the program
when if statement having multiple decisions.

The basic format of else if statement is:

Syntax:

if(test_expression)
{
CST 205 MODULE 2

//execute your code


}
else if(test_expression n)
{
//execute your code
}
else
{
//execute your code
}

Example:

public class Sample


{
public static void main(String args[])
{
int number1 = 30, number2 = 30;
if (number2 > number1)
{ [Link]("number2 isgreater");
}
else if(number1 > number2)
{
[Link]("number1 isgreater");
}
else
{
[Link]("Both are equal");
}
}
}
CST 205 MODULE 2

4) Java switch Statements


Java switch statement is used when you have multiple possibilities for the if statement.

The basic format of the switch statement is:

Syntax:
switch(variable)
{
case 1:
//execute your code
break;

case n:
//execute your code
break;

default:
//execute your code
}

After the end of each block it is necessary to insert a break statement


because if the programmers do not use the break statement, all consecutive blocks
of codes will get executed from each and every case onwards after matching the
case block.
Example:
public class Sample
{
public static void main(String args[])
{
int chioce = 5;
switch (chioce)
{
CST 205 MODULE 2

case 1:
[Link]("You chose One");
break;

case 2:
[Link]("You chose Two");
break;

case 3:
[Link]("You chose Three");
break;

case 4:
[Link]("You chose
Four"); break;

case 5:
[Link]("You chose Five");
break;

default:
[Link]("Invalid Choice. Enter a no between 1 and 5");
}
}
}

II) JAVA LOOPS

Java supports many looping features which enable programmers to develop


concise Java programs with repetitive processes.

Java supports following types of loops:

 while loops
 do while loops
CST 205 MODULE 2

 for loops

Java Loop Control Statements


Loop control statements are used to change the normal sequence of execution of the
loop.
CST 205 MODULE 2

1) Java while loops


Java while loops statement allows to repeatedly run the same block of code
until a condition is met. while loop is the most basic loop in Java. It has one
control condition and executes as long the condition is true. The condition of the
loop is tested before the body of the loop is executed, hence it is called an entry-
controlled loop.

The basic format of while loop statement is:

Syntax:
while (condition)
{
statement(s);
Incrementation;
}
Example
:

public class Sample


{
public static void main(String args[])
{
/* local variable Initialization */
int n = 1, times = 5;
/* while loops execution */
while (n <= times)
{
[Link]("Java while loops:" + n);
n++;
}
}
}
2) Java do-while loops
Java do-while loops are very similar to the while loops, but it always
CST 205/281 MODULE 2
executes the code block at least once and furthermore as long as the condition
remains true. This is an exit- controlled loop.

The basic format of do-while loop statement is:

Syntax:
do
{
statement(s);

}while( condition );
CST 205/281 MODULE 2

Example:

public class Sample


{
public static void main(String args[])
{
/* local variable Initialization */
int n = 1, times = 0;
/* do-while loops execution */
do
{
[Link]("Java do while loops:" + n); n++;
} while (n <= times);
}
}
3) Java for loops

Java for loops is very similar to Java while loops in that it continues to
process a block of code until a statement becomes false, and everything is defined in
a single line.
Syntax:

for ( init; condition; increment )


{
statement(s);
}
Example:

public class Sample


{
public static void main(String args[])
{
CST 205/281 MODULE 2
/* local variable Initialization */ int
n = 1, times = 5;

/* for loops execution */


for (n = 1; n <= times; n = n + 1)
{
[Link]("Java for loops:" + n);
}
}
}
CST 205 MODULE 2

III) JUMP STATEMENTS


Jump statements are used to interrupt the normal flow of program.

Types of Jump Statements are:

 break
 continue
 label

1) break statement
The break statement is used inside loop or switch statement. When compiler finds the
break statement inside a loop, compiler will abort the loop and continue to execute
statements followed by loop.

Example of break statement

//[Link]

class Abc
{
public static void main(String args[])
{
int a=1;
while(a<=10)
{
if(a==5)
break;
[Link]("\n\tStatement : " + a);
a++;

}
CST 205 MODULE 2

[Link]("\n\t End of Program.");


}
}

Output :

Statement: 1.
Statement: 2.
Statement: 3.
Statement: 4.
End of Program.

The above program will abort the loop when the value of a reaches upto 5 and skip all
statements present in loop.

2) continue statement
The continue statement is also used inside loop. When compiler finds the continue
statement inside a loop, compiler will skip all the following statements in the loop and
resume the loop.

Example of continue statement

//[Link]

class xyz
{
public static void main(String args[])
{
int a=0;
CST 205 MODULE 2

while(a<10)
{
a++;
if(a==5)
continue;
[Link]("\n\tStatement " + a);
}
[Link]("\n\tEnd of Program.");
}

Output :

Statement 1.
Statement 2.
Statemnet 3.
Statement 4.
Statement 6.
Statement 7.
Statement 8.
Statement 9.
Statement 10.
End of Program.

The above program will skip all statements present in loop when the value of a reaches
upto 5 and continue the loop from 6 to 10.

3) Labelled Loop
Java does not support goto, it is reserved as a keyword just in case they wanted to add it
to a later version.
 Unlike C/C++, Java does not have goto statement, but java supports label.
CST 205 MODULE 2

 The only place where a label is useful in Java is right before nested loop statements.
 We can specify label name with break to break out a specific outer loop.

According to nested loop, if we put break statement in inner loop, compiler will jump out
from inner loop and continue the outer loop again. What if we need to jump out from the
outer loop using break statement given inside inner loop? The answer is, we should
define lable along with colon(:) sign before loop.

Syntax of Labelled loop

Java Labelled Break and Continue

In the case of nested loops to break and continue a particular loop we should go for labelled
break and continue statements. The Java labelled loops allows transferring to a particular
line or statement.

Example: Labelled Break Statement

class Test
CST 205 MODULE 2

{
public static void main(String args[ ])
{
out: for(int i=1; i<=100; i++)
{
[Link]("outer");
for(int j=1; j<=100; j++)
{
[Link]("nested");
if(j==2)
{
// break; this will exit from inner for loop only
break out; // this will exit from both for loops
}
}
}

}
}

Output:-

outer
nested
nested

Example: Labelled Continue Statement

class Test
CST 205 MODULE 2

{
public static void main(String[] args)
{
out: for(int i=1; i<=100; i++)
{
[Link]("outer");
for(int j=1; j<=100; j++)
{
[Link]("nested");
if(j==2)
{
// continue; this will skip second(j==2) iteration
of inner for loop only
continue out; // this will skip current iteration of
both for loops
}
}
}
}
}

Output:- The outer for loop will iterate 100 times but the inner for loop will iterate twice
each time.

outer
nested
nested
outer
nested
nested
.
.
CST 205 MODULE 2

.
outer
nested
nested

INTRODUCTION TO OOP
CLASS FUNDAMENTALS
Everything in Java is defined in a class.

A class is a group of objects which have common properties. It is a template or blueprint


from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface

Syntax to declare a class:

class <class_name>
{
field;
method;
}

EXAMPLE:-
CST 205 MODULE 2

class Employee

String name;

String ssn;

String emailAddress;

int yearOfBirth;

 The order of data fields and methods in a class is not significant.

If you recall, each class must be saved in a file that matches its name, for
example: [Link]

Note that in Java, Strings are also classes rather than being implemented as primitive
types.

Unlike local variables, the state variables (known as fields) of objects do not have to be
explicitly initialized. Primitive fields (such as yearOfBirth) are automatically set to
primitive defaults (0 in this case), whereas objects (name, ssn, emailAddress) are
automatically set to null — meaning that they do not point to any object.

A class can contain any of the following variable types.

 Local variables − Variables defined inside methods, constructors or blocks are


called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.

 Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
CST 205 MODULE 2

variables can be accessed from inside any method, constructor or blocks of that
particular class.

 Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.

OBJECTS IN JAVA
Let us now look deep into what are objects. If we consider the real-world, we can find
many objects around us, cars, dogs, humans, etc. All these objects have a state and a
behavior.

If we consider a dog, then its state is - name, breed, color, and the behavior is - barking,
wagging the tail, running.

If you compare the software object with a real-world object, they have very similar
characteristics.

Software objects also have a state and a behavior. A software object's state is stored in
fields and behavior is shown via methods.

So in software development, methods operate on the internal state of an object and the
object-to-object communication is done via methods.

As mentioned previously, a class provides the blueprints for objects. So basically, an


object is created from a class. In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −

 Declaration − A variable declaration with a variable name with an object type.

 Instantiation − The 'new' keyword is used to create the object.

 Initialization − The 'new' keyword is followed by a call to a constructor. This call


initializes the new object.
CST 205 MODULE 2

Example:- Employee e = new Employee();

 To access member data or methods of an object, use the dot (.)


notation: [Link] or [Link]()

Consider this simple example of creating and using instances of the Employee class:

class Employee

String name;

String ssn;

String emailAddress;

int yearOfBirth;

};

public class EmployeeDemo

public static void main(String args[ ])

Employee e1 = new Employee ();

[Link] = "John";

[Link] = "555-12-345";

[Link] = "john@[Link]";
CST 205 MODULE 2

Employee e2 = new Employee ();

[Link] = "Tom";

[Link] = "456-78-901";

[Link] = 1974;

[Link]("Name: " + [Link]);

[Link]("SSN: " + [Link]);

[Link]("Email Address: " + [Link]);

[Link]("Year Of Birth: " + [Link]);

[Link]("Name: " + [Link]);

[Link]("SSN: " + [Link]);

[Link]("Email Address: " + [Link]);

[Link]("Year Of Birth: " + [Link]);

Running this code produces:

Name: John

SSN: 555-12-345

Email Address: john@[Link]

Year Of Birth: 0
CST 205 MODULE 2

Name: Tom

SSN: 456-78-901

Email Address: null

Year Of Birth: 1974

Referencing an Object's Variables

The following is the general form of a qualified name, which is also known as a long
name: [Link];

METHODS IN JAVA
A Java method is a collection of statements that are grouped together to perform an
operation. When you call the [Link]() method, for example, the system
actually executes several statements in order to display a message on the console.

 Creating Method
Syntax:-
modifier returnType nameOfMethod (Parameter List)
{
// method body
}
The syntax shown above includes −
 modifier − It defines the access type of the method and it is optional to use.
 returnType − Method may return a value.
 nameOfMethod − This is the method name. The method signature consists of the
method name and the parameter list.
 Parameter List − The list of parameters, it is the type, order, and number of
parameters of a method. These are optional, method may contain zero parameters.
 method body − The method body defines what the method does with the
statements.
CST 205 MODULE 2

Example:-
public static int sum(int a, int b)
{
// body
}
Here,
 public static − modifier
 int − return type
 sum − name of the method
 a, b − formal parameters
 int a, int b − list of parameters

Example:
public static int minimum(int a, int b)
{
int min;
if (a > b)
min = b;
else
min = a;
return min;
}
CST 205 MODULE 2

PARAMETER-LESS CONSTRUCTOR

-Constructors having no arguments are parameter less constructors.


CST 205 MODULE 2
CST 205 MODULE 2

PARAMETERIZED CONSTRUCTORS
-

-> Constructors having arguments.

.
CST 205 MODULE 2
CST 205 MODULE 2

JAVA this KEYWORD


The this keyword refers to the current object in a method or constructor.

Example
Using this with a class attribute (x):

public class Abc


{

int x;

// Constructor with a parameter


CST 205 MODULE 2

public Abc (int x)


{

this .x = x;
}

// Call the constructor

public static void main(String args[ ])

Abc obj = new Abc (5);

[Link]("Value of x = " + obj.x);

}
}
OUTPUT

The most common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter). If you omit the keyword in the example above, the
output would be "0" instead of "5".

this can also be used to:

 Invoke current class constructor


 Invoke current class method
 Return the current class object
 Pass an argument in the method call
 Pass an argument in the constructor call.
CST 205 MODULE 2
CST 205 MODULE 2
CST 205 MODULE 2
CST 205 MODULE 2

PASSING OBJECT AS ARGUMENTS AND RETURNING


OBJECT
CST 205 MODULE 2
CST 205 MODULE 2

RECURSION IN JAVA

 Function call by itself is known as recursion.


Eg:-
public class Recursion
{
int factorial(int n)
{
if (n == 1)
return 1;
else
return(n * factorial(n-1));
}
}
Class Abc
{
public static void main(String[] args)
{
Recursion obj=new Recursion();
[Link]("Factorial of 5 is: "+[Link](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
CST 205 MODULE 2

ACCESS CONTROL
Access control is a mechanism, an attribute of encapsulation which restricts the access of
certain members of a class to specific parts of a program. Access to members of a class can
be controlled using the access modifiers. There are four access modifiers in Java. They are:

1. public
2. protected
3. default
4. private

If the member (variable or method) is not marked as


either public or protected or private, the access modifier for that member will
be default. We can apply access modifiers to classes also.
CST 205 MODULE 2

STATIC MEMBERS

In Java, static members are those which belongs to the class and you can access these
members without instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.

Example for static member

class Abc
{
static int a; // static member “a”
static String str; //static member “str”
static void disp() //This is a Static Method
{
[Link]("value of a is: "+a);
[Link]("Value of string str is: "+str);
}
}
class Xyz
{
public static void main(String args[])
{
disp();
}
}
Output:
value of a is: 0
Value of string str is: null
…………………………………………………………………………………
CST 205 MODULE 2

Example for static method


class St
{
static void print() // This is a static method
{
[Link] ("hello");
}
}
Class Abc
{
public static void main(String args[ ])
{
/* We can see that we are calling this method without creating any object. */
print();
}
}
Output: hello

JAVA 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 “a”, 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 xyz
{
final int a=3; //final variable
void run() Output:
{
a=10;
Compile Time Error
}
public static void main (String args[])
{
xyz obj=new xyz();
[Link]();
} }
CST 205 MODULE 2

JAVA 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 Outer
{
//code
class Inner
{
//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 classes non-static and static nested [Link] non-static
nested classes are also known as inner classes.
CST 205 MODULE 2

o Non-static nested class (inner class)


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

COMMAND-LINE ARGUMENT
A command-line argument is an information that directly follows the program's name
on the command line when it is executed. To access the command-line arguments inside
a Java program is quite easy. They are stored as strings in the String array passed to
main( ).
Example
The following program displays all of the command-line arguments that it is called with
-
public class Abc
{
public static void main(String args[ ])
{
for(int i = 0; i<[Link]; i++)
{
[Link]("args[" + i + "]: " + args[i]);
}
}
}
Try executing this program as shown here -

$java Abc I am a BTech student 100 -500


Output
This will produce the following result -

args[0]: I
args[1]: am
args[2]: a
args[3]: BTech
args[4]: student
args[5]: 100
CST 205 MODULE 2

args[6]: -500

--------------------------------------------------------------------------------------
VARIABLE LENGTH ARGUMENTS
In JDK 5, Java has included a feature that simplifies the creation of methods that need to
take a variable number of arguments. This feature is called varargs and it is short-form for
variable-length arguments. A method that takes a variable number of arguments is a varargs
method.
Prior to JDK 5, variable-length arguments could be handled two ways. One using
overloaded method(one for each) and another put the arguments into an array, and then
pass this array to the method. Both of them are potentially error-prone and require more
code. The varargs feature offers a simpler, better option.
Syntax :
A variable-length argument is specified by three periods(…). For Example,

public static void fun(int ... a)


{
// method body
}
This syntax tells the compiler that fun( ) can be called with zero or more arguments. As a
result, here a is implicitly declared as an array of type int[]. Below is a code snippet for
illustrating the above concept :
// Java program to demonstrate varargs
class Test1
{
// A method that takes variable number of integer
// arguments.
static void fun(int ...a)
{
[Link]("Number of arguments: " + [Link]);

// using for each loop to display contents of a


for (int i: a)
CST 205 MODULE 2

[Link](i + " ");


[Link]();
}
public static void main(String args[])
{
// Calling the varargs method with different number of parameters .
fun(100); // one parameter
fun(1, 2, 3, 4); // four parameters
fun(); // no parameter
}
}

Output:
Number of arguments: 1
100
Number of arguments: 4
1234
Number of arguments: 0
 The … syntax tells the compiler that varargs has been used and these arguments
should be stored in the array referred to by a.
 The variable a is operated on as an array. In this case, we have defined the data type
of a as int. So it can take only integer values. The number of arguments can be found
out using [Link], the way we find the length of an array in Java.

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

Why use inheritance in java?


CST 205 MODULE 2

o For Method Overriding (so runtime polymorphism can be achieved).


o 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 derived-class extends base-class


{
// 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, and
the new class is called child or subclass.

Java supports three types of inheritance −

 Single Level inheritance - A class inherits properties from a single class. For example,
Class B inherits Class A.
 Multilevel inheritance - A class inherits properties from a class which again has inherits
properties
 Hierarchical inheritance - Multiple classes inherits properties from a single class. For
example, Class B inherits Class A and Class C inherits Class A.
 (NB: Multiple inheritance (derivation of a class from more than one parent class) is not
supported in java, instead interfaces are used in java)
CST 205 MODULE 2
CST 205 MODULE 2
CST 205 MODULE 2

OUTPUT
-
Hello
Child class

KEYWORD “SUPER”
The super keyword in java is a reference variable that is used to refer parent class objects. The
keyword “super” came into the picture with the concept of Inheritance. It is majorly used in the
following contexts:

1. Use of super with variables:

This scenario occurs when a derived class and base class has same data members. In that case
there is a possibility of ambiguity for the JVM. We can understand it more clearly using this
code snippet:

/* Base class A*/


class A
{
int x;
A( )
{
x= 10;
}
}

/* sub class B extending A */


class B extends A
{
int x ;
B( )
{
x= 18;
}

void display()
{
/* print x of base class (A) */
[Link]("Value of x in class A: " + super.x);
}
}

class Abc
CST 205 MODULE 2
{
public static void main(String args[ ])
{
B obj = new B();
[Link]();
}
}

Output:
Value of x in class A: 10

In the above example, both base class and subclass have a member “x”. We could access “x”of base class
in subclass using super keyword.

2. Use of super with methods: This is used when we want to call parent class method. So
whenever a parent and child class have same named methods then to resolve ambiguity we use super
keyword. This code snippet helps to understand the said usage of super keyword.

class A
{
void message()
{
[Link]("CLASS A");
}
}

class B extends A
{
void message()
{
[Link]("CLASS B");
}

void display() // Note that display() is only in class B

{
message(); // will invoke or call current class message() method

[Link](); // will invoke or call class A message() method


}
}

class Abc
{
CST 205 MODULE 2
public static void main(String args[])
{
B obj = new B();

[Link](); // calling display() of B

}
}

Output:
CLASS B
CLASS A
In the above example, we have seen that if we only call method message() then, the current class
message() is invoked but with the use of super keyword, message() of superclass could also be
invoked.

3. Use of super with constructors:

super keyword can also be used to access the parent class constructor. One more important thing
is that, ‘’super’ can call both parametric as well as non parametric constructors depending upon
the situation. Following is the code snippet to explain the above concept:
class A
{
A( )
{
[Link]("class A Constructor");
}
}

/* subclass B extending the class A */


class B extends A
{
B( )
{
super(); // invoke or call class A constructor

[Link]("class B Constructor");
}
}

class Test
{
public static void main(String[] args)
{
CST 205 MODULE 2
B obj = new B( );
}
}

Output:
Class A Constructor
Class B Constructor

In the above example we have called the superclass constructor using keyword ‘super’ via subclass
constructor.

PROTECTED MEMBERS
Protected keyword in Java refers to one of its access modifiers. The methods or data
members declared as protected can be accessed from:
 Within the same class.
 Subclasses of same packages.
 Different classes of same packages.
 Subclasses of different packages.

1. If one wishes to access a protected modifier outside a package, then inheritance is

needed to be applied.
CST 205 MODULE 2

2. Protecting a constructor prevents the users from creating the instance of the class,

outside the package.

3. During overriding, when a variable or method is protected, it can be overridden to

other subclass using either a public or protected modifier only.

4. Outer class and interface cannot be protected.

CALLING ORDER OF CONSTRUCTORS


1. The base-class constructor is called. This step is repeated recursively such that the
root of the hierarchy is constructed first, followed by the next-derived class, etc.,
until the most-derived class is reached.
2. Member initializers are called in the order of declaration.
3. The body of the derived-class constructor is called.
CST 205 MODULE 2

METHOD OVERRIDING
CST 205 MODULE 2

OUTPUT
Method A
Method A in class B
Method B

If no overriding is used, output will be:


Method A
Method A
Method B
CST 205 MODULE 2

OBJECT CLASS IN JAVA


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.

The Object class is beneficial if you want to refer any object whose type you don't know.
Notice that parent class reference variable can refer the child class object, know as
upcasting.

ABSTRACT CLASSES AND METHODS

ABSTRACT CLASS

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.

EXAMPLE:-
CST 205 MODULE 2

ABSTRACT METHOD

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

Example of abstract method

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

class abc
{
public static void main (string args[])
{
C obj = new C ( );
obj.amethod1( );
}
}
CST 205 MODULE 2

USING “final” WITH INHERITANCE


 The final keyword is final that is we cannot change.
 We can use final keywords for variables, methods, and class.
 If we use the final keyword for the inheritance that is if we declare any method
with the final keyword in the base class so the implementation of the final
method will be the same as in derived class.
 We can declare the final method in any subclass for which we want that if any
other class extends this subclass.

Case 1: Declare final variable with inheritance

class Parent
{
/* Creation of final variable pa of string type i.e
the value of this variable is fixed throughout all
the derived classes or not overidden*/

final String pa = "Hello , We are in parent class variable";


}
class Child extends Parent
{
/* Creation of variable ch of string type i.e
the value of this variable is not fixed throughout all
the derived classes or overidden*/

String ch = "Hello , We are in child class variable";


}

class Test
{
public static void main(String args [ ])
{
Parent p = new Parent();
// Calling a variable pa by parent object
[Link]([Link]);
CST 205 MODULE 2

Child c = new Child();

// Calling a variable ch by Child object


[Link]([Link]);
// Calling a variable pa by Child object
[Link]([Link]);
}
}

Output

Hello , We are in parent class variable


Hello , We are in child class variable
Hello , We are in parent class variable

Case 2: Declare final methods with inheritance

class Parent
{
/* Creation of final method parent of void type i.e
the implementation of this method is fixed throughout
all the derived classes or not overidden*/
final void parent( )
{
[Link]("Hello , we are in parent method");
}
}
class Child extends Parent
{

/* Creation of final method child of void type i.e


the implementation of this method is not fixed throughout
all the derived classes or not overidden*/
void child( )
{
[Link]("Hello , we are in child method");
}
}

class Test
{
public static void main(String args[ ])
{
Parent p = new Parent();
// Calling a method parent() by parent object
[Link]();

Child c = new Child();


// Calling a method child() by Child class object
[Link]();
// Calling a method parent() by child object
[Link]();
}
}

Output

Hello , we are in parent method


Hello , we are in child method
Hello , we are in parent method

- - end
1
CST 205, S3, CSE MODULE 3

MODULE 3
PACKAGES AND INTERFACES

DEFINING PACKAGES
A package is a mechanism to group the similar type of classes, interfaces and sub-packages and
provide access control. It organizes classes into single unit.
In Java already many predefined packages are available, used while programming.
For example: [Link], [Link], [Link] etc.

Advantages of Packages
 Packages provide code reusability, because a package has group of classes.
 It helps in resolving naming collision when multiple packages have classes with the same name.
 Package also provides the hiding of class facility. Thus other programs cannot use the classes
from hidden package.
 Access limitation can be applied with the help of packages.
 One package can be defined in another package.

Types of Packages
There are two types of packages available in Java.
1. Built-in packages
Built-in packages are already defined in java API. For example: [Link], [Link], java,lang,
[Link], [Link], [Link], etc.
2. User defined packages
The package we create according to our need is called user defined package.

Creating a Package
We can create our own package by creating our own classes and interfaces together. The package
statement should be declared at the beginning of the program.
Syntax:
package <packagename>;
class ClassName
{
……..
……..
}

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


2
CST 205, S3, CSE MODULE 3

Example: Creating a Package

// [Link]
package p1;
class Abc
{
public void disp()
{
[Link]("Method disp..");
}
}
It can be compiled by:
Syntax:
javac –d directoryjavaFileName
Eg:-
javac –d [Link]
It can be run by:
Java [Link]

CLASSPATH
CLASSPATH is an environment variable which is used by Application ClassLoader to locate and load
the .class files. The CLASSPATH defines the path, to find third-party and user-defined classes that
are not extensions or part of Java platform. Include all the directories which contain .class files and
JAR files when setting the CLASSPATH.

You need to set the CLASSPATH if:

o You need to load a class that is not present in the current directory or any sub-directories.
o You need to load a class that is not in a location specified by the extensions mechanism.

The CLASSPATH depends on what you are setting the CLASSPATH. The CLASSPATH has a
directory name or file name at the end. The following points describe what should be the end of the
CLASSPATH.

o If a JAR or zip, the file contains class files, the CLASSPATH end with the name of the zip or JAR file.

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


3
CST 205, S3, CSE MODULE 3

o If class files placed in an unnamed package, the CLASSPATH ends with the directory that contains the
class files.
o If class files placed in a named package, the CLASSPATH ends with the directory that contains the root
package in the full package name, that is the first package in the full package name.

The default value of CLASSPATH is a dot (.). It means the only current directory searched. The default value of
CLASSPATH overrides when you set the CLASSPATH variable or using the -classpath command (for short -cp).
Put a dot (.) in the new setting if you want to include the current directory in the search path.

If CLASSPATH finds a class file which is present in the current directory, then it will load the class and use it,
irrespective of the same name class presents in another directory which is also included in the CLASSPATH.

If you want to set multiple classpaths, then you need to separate each CLASSPATH by a semicolon (;).

The third-party applications (MySQL and Oracle) that use the JVM can modify the CLASSPATH environment
variable to include the libraries they use. The classes can be stored in directories or archives files. The classes of the
Java platform are stored in [Link].

There are two ways to ways to set CLASSPATH: through Command Prompt or by setting Environment Variable.

Let's see how to set CLASSPATH of MySQL database:

Step 1: Click on the Windows button and choose Control Panel. Select System.

Step 2: Click on Advanced System Settings.

Step 3: A dialog box will open. Click on Environment Variables.

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


4
CST 205, S3, CSE MODULE 3

Step 4: If the CLASSPATH already exists in System Variables, click on the Edit button then put a semicolon (;) at
the end. Paste the Path of MySQL-Connector [Link] file.

If the CLASSPATH doesn't exist in System Variables, then click on the New button and type Variable name as
CLASSPATH and Variable value as C:\Program Files\Java\jre1.8\MySQL-Connector [Link];.;

Remember: Put ;.; at the end of the CLASSPATH.

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


5
CST 205, S3, CSE MODULE 3

ACCESS PROTECTION IN PACKAGES


Access modifiers define the scope of the class and its members (data and methods). For example,
private members are accessible within the same class members (methods). Java provides many
levels of security that provides the visibility of members (variables and methods) within the
classes, subclasses, and packages.
Packages are meant for encapsulating, it works as containers for classes and other subpackages.
Class acts as containers for data and methods. There are four categories, provided
by Java regarding the visibility of the class members between classes and packages:

1. Subclasses in the same package


2. Non-subclasses in the same package
3. Subclasses in different packages
4. Classes that are neither in the same package nor subclasses

The three main access modifiers private, public and protected provides a range of ways to access
required by these categories.

Simply remember, private cannot be seen outside of its class, public can be access from anywhere,
and protected can be accessible in subclass only in the hierarchy.
A class can have only two access modifier, one is default and another is public. If the class has
default access then it can only be accessed within the same package by any other code. But if the
class has public access then it can be access from any where by any other code.

importing Java Package


To import java package into a class, we need to use java import keyword which is used to access
package and its classes into the java program.
Use import to access built-in and user-defined packages into your java source file so that your
class can refer to a class that is in another package by directly using its name.
Eg: import [Link].*;
import [Link].*;
import [Link];

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


6
CST 205, S3, CSE MODULE 3

INTERFACES

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


7
CST 205, S3, CSE MODULE 3

IMPLEMENTING INTERFACES

SAMPLE PROGRAM

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


8
CST 205, S3, CSE MODULE 3

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


9
CST 205, S3, CSE MODULE 3

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


10
CST 205, S3, CSE MODULE 3

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


11
CST 205, S3, CSE MODULE 3

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


12
CST 205, S3, CSE MODULE 3

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


13
CST 205, S3, CSE MODULE 3

Table: Character Stream I/O Classes

READING CONSOLE INPUT

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


14
CST 205, S3, CSE MODULE 3

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


15
CST 205, S3, CSE MODULE 3

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


16
CST 205, S3, CSE MODULE 3

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


17
CST 205, S3, CSE MODULE 3

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


18
CST 205, S3, CSE MODULE 3

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


19
CST 205, S3, CSE MODULE 3

Writing Console Output in Java


Writing Console Output in Java refers to writing the output of a Java program to the console or
any particular file.

The methods used for streaming output are defined in the PrintStream class. The methods used
for writing console output are print(), println() and write().

Methods of Writing Console Output in


Java-print() and println()

Prepared by Aswathy P, Asst. Professor, Dept. of CSE, ICCS CEM


20
CST 205, S3, CSE MODULE 3

Both print() and println() methods are used to direct the output to the console. These methods are
defined in the PrintStream class and are widely used. Both these methods are used with the help
of the [Link] stream.

The basic differences between print() and println() methods are as follows:

 print() method displays the string in the same line whereas println() method outputs a newline
character after its execution.
 print() method is used for directing output to console only whereas println() method is used for
directing output to not only console but other sources also.

Now, let us understand it in a better way with the help of some examples.

Example of print() method:

1. // Sample program to display numbers from 1-10 using print method


2. class printEg
3. {
4. public static void main(String args[])
5. {
6. int a;
7. for (a=1 ; a<=10 ; a++)
8. {
9. [Link](a);
10. }
11. }
12. }

Output:

Example of println() method:

Let us take the same example above and use println() method in place of print() method.

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


21
CST 205, S3, CSE MODULE 3

1. // Sample program to display numbers from 1-10 using println method


2. class printlnEg
3. {
4. public static void main(String args[])
5. {
6. int a;
7. for (a=1 ; a<=10 ; a++)
8. {
9. [Link](a);
10. }
11. }
12. }

Output:

Observe the difference in the output.

Both these functions work best for output of strings as well. Let us have a look at another
example.

Displaying strings using print() and println() methods


It is very easy to display strings using print() and println() methods. For displaying any particular
string, the string to be displayed on screen is written within the double quotation marks (i.e. “ “).

For example: [Link](“Hello!! How are you?”);

In addition, if you want to display the value of any particular variable used in the program, then
you have to append the variable name along with the string with a plus (+) symbol.

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


22
CST 205, S3, CSE MODULE 3

Example for displaying any string output:

1. // Sample program to display sum of numbers from 1-10


2. class Eg1
3. {
4. public static void main(String args[])
5. {
6. int a, total = 0;
7. for (a=1 ; a<=10 ; a++)
8. {
9. total = total + a;
10. }
11. [Link]("Sum of first 10 numbers is: " + total);
12. }
13. }

Output:

The write() method


Alternatively, you can make use of the write() method for directing the output of your program
to the console. The easiest syntax of the write() method is:

void write(int b);

Where b is an integer of low order eight bits.

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


23
CST 205, S3, CSE MODULE 3

Let us have a look at a simple example.

class writeEg
{
public static void main(String args[])
{
int a, b;
a = 'Q';
b = 65;
[Link](a);
[Link]('\n');
[Link](b);
[Link]('\n');
}
}

Output:

PrintWriter class
It implements all of the print methods found in PrintStream. It does not contain methods for
writing raw bytes, for which a program should use unencoded byte streams.
Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of
the println, printf, or format methods is invoked, rather than whenever a newline character
happens to be output. These methods use the platform’s own notion of line separator rather than
the newline character.
Methods in this class never throw I/O exceptions, although some of its constructors may. The
client may inquire as to whether any errors have occurred by invoking checkError().
Constructor and Description
 PrintWriter(File file) : Creates a new PrintWriter, without automatic line flushing, with
the specified file.
 PrintWriter(File file, String csn) : Creates a new PrintWriter, without automatic line
flushing, with the specified file and charset.

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


24
CST 205, S3, CSE MODULE 3

 PrintWriter(OutputStream out) : Creates a new PrintWriter, without automatic line


flushing, from an existing OutputStream.
 PrintWriter(OutputStream out, boolean autoFlush) : Creates a new PrintWriter from an
existing OutputStream.
 PrintWriter(String fileName) : Creates a new PrintWriter, without automatic line
flushing, with the specified file name.
 PrintWriter(String fileName, String csn) : Creates a new PrintWriter, without automatic
line flushing, with the specified file name and charset.
 PrintWriter(Writer out): Creates a new PrintWriter, without automatic line flushing.
 PrintWriter(Writer out, boolean autoFlush) : Creates a new PrintWriter.

Methods:
 PrintWriter append(char c) : Appends the specified character to this writer
 PrintWriter append(CharSequence csq, int start, int end): Appends the specified
character sequence to this writer.
 PrintWriter append(CharSequence csq) : Appends a subsequence of the specified
character sequence to this writer.
 boolean checkError(): Flushes the stream and checks its error state.
 protected void clearError() : Clears the internal error state of this stream.
 void close() : Closes the stream and releases any system resources associated with it.
 PrintWriter format(Locale l, String format, Object… args): Writes a formatted string
to this writer using the specified format string and arguments.
 PrintWriter format(String format, Object… args): Writes a formatted string to this
writer using the specified format string and arguments.
 void print(boolean b): Prints a boolean value.
 void print(char c): Prints a character.
 void print(char[] s): Prints an array of characters.
 void print(double d) :Prints a double-precision floating-point number.
 void print(float f): Prints a floating-point number.
 void print(int i): Prints an integer.
 void print(long l): Prints a long integer.
 void print(Object obj) :Prints an object.
 void print(String s): Prints a string.
 WORKING WITH FILES
File handling is an important part of any application.

Java has several methods for creating, reading, updating, and deleting files.

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


25
CST 205, S3, CSE MODULE 3

JAVA FILE HANDLING

The File class from the [Link] package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory
name:

Example

import [Link]; // Import the File class


File myObj = new File("[Link]"); // Specify the filename

If you don't know what a package is, read our Java Packages Tutorial.
The File class has many useful methods for creating and getting information about files.
For example:
Method Type Description

canRead() Boolean Tests whether the file is readable or not

canWrite() Boolean Tests whether the file is writable or not

createNewFile() Boolean Creates an empty file

delete() Boolean Deletes a file

exists() Boolean Tests whether the file exists

getName() String Returns the name of the file

getAbsolutePath() String Returns the absolute pathname of the file

length() Long Returns the size of the file in bytes

list() String[] Returns an array of the files in the directory

mkdir() Boolean Creates a directory

1. Create a File
To create a file in Java, you can use the createNewFile() method. This method returns a
boolean value: true if the file was successfully created, and false if the file already exists.

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


26
CST 205, S3, CSE MODULE 3

Example:-

import [Link]; // Import the File class


import [Link]; // Import the IOException class to handle errors

public class CreateFile


{
public static void main(String[] args)
{
try
{
File myObj = new File("[Link]");
if ([Link]())
{
[Link]("File created: " + [Link]());
}
else
{
[Link]("File already exists.");
}
}
catch (IOException e)
{
[Link]("An error occurred.");
[Link]();
}
}
}

The output will be:

File created: [Link]


-

2. Read a File
In the following example, we use the Scanner class to read the contents of the text file

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


27
CST 205, S3, CSE MODULE 3

Example:-

import [Link]; // Import the File class


import [Link]; // Import this class to handle errors
import [Link]; // Import the Scanner class to read text files

public class ReadFile


{
public static void main(String[] args)
{
try
{
File myObj = new File("[Link]");
Scanner myReader = new Scanner(myObj);
while ([Link]())
{
String data = [Link]();
[Link](data);
}
[Link]();
}
catch (FileNotFoundException e)
{
[Link]("An error occurred.");
[Link]();
}
}
}

The output will be:

Files in Java might be tricky, but it is fun enough!


------------------------------------------------------------------------------------------------------
3. Delete a File

To delete a file in Java, use the delete() method:

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


28
CST 205, S3, CSE MODULE 3

Example:-

import [Link]; // Import the File class

public class DeleteFile {


public static void main(String[] args) {
File myObj = new File("[Link]");
if ([Link]()) {
[Link]("Deleted the file: " + [Link]());
} else {
[Link]("Failed to delete the file.");
}
}
}

The output will be:

Deleted the file: [Link]

EXCEPTION HANDLING IN JAVA


Exception handling is one of the most important feature of java programming that allows us to handle the
runtime errors caused by exceptions.

What is an exception?
An Exception is an unwanted event that interrupts the normal flow of the program. When an exception
occurs program execution gets terminated. In such cases we get a system generated error message. The
good thing about exceptions is that they can be handled in Java. By handling the exceptions we can
provide a meaningful message to the user about the issue rather than a system generated message, which
may not be understandable to a user.

Why an exception occurs?


There can be several reasons that can cause a program to throw exception. For example: Opening a non-
existing file in your program, Network connection problem, bad input data provided by user etc.

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


29
CST 205, S3, CSE MODULE 3

Exception Handling

If an exception occurs, which has not been handled by programmer then program execution gets
terminated and a system generated error message is shown to the user. For example look at the system
generated exception below:

Advantage of exception handling

Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For
example, if a program has bunch of statements and an exception occurs mid way after executing certain
statements then the statements after the exception will not execute and the program will terminate
abruptly.
By handling we make sure that all the statements execute and the flow of program doesn’t break.

Difference between error and exception


Errors indicate that something severe enough has gone wrong, the application should crash rather than
try to handle the error.

Exceptions are events that occurs in the code. A programmer can handle such conditions and take
necessary corrective actions. Few examples:

NullPointerException – When you try to use a reference that points to null.


ArithmeticException – When bad data is provided by user, for example, when you try to divide a
number by zero this exception occurs because dividing a number by zero is undefined.
ArrayIndexOutOfBoundsException – When you try to access the elements of an array out of its
bounds, for example array size is 5 (which means it has five elements) and you are trying to access the
10th element.

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


30
CST 205, S3, CSE MODULE 3

JAVA EXCEPTION KEYWORDS


There are 5 keywords which are used in handling exceptions in Java.

Keyword Description

Try The "try" keyword is used to specify a block where we should place exception code. The try block must be follo
finally. It means, we can't use try block alone.

catch The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use ca
followed by finally block later.

finally The "finally" block is used to execute the important code of the program. It is executed whether an exception is

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 oc
method. It is always used with method signature.

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


31
CST 205, S3, CSE MODULE 3

TYPES OF EXCEPTIONS
There are two types of exceptions in Java:
1) Checked exceptions
2) Unchecked exceptions

1. CHECKED EXCEPTIONS
 All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler
checks them during compilation to see whether the programmer has handled them or not.
 If these exceptions are not handled/declared in the program, you will get compilation error.
 For example, SQLException, IOException, ClassNotFoundException etc.

 for example, if you use FileReader class in your program to read data from a file, if the file
specified in its constructor doesn't exist, then a FileNotFoundException occurs, and the compiler
prompts the programmer to handle the exception.
Example: A prg with name FilenotFound_Demo.java
import [Link];
import [Link];

public class FilenotFound_Demo


{
public static void main(String args[])
{
File file = new File("E://[Link]");
FileReader fr = new FileReader(file);
}
}

If you try to compile the above program, you will get the following exceptions.
Output
Compile the prg as
javac FilenotFound_Demo.java
The error appeared as:
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or
declared to be thrown
FileReader fr = new FileReader(file);
^
1 error

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


32
CST 205, S3, CSE MODULE 3

Note − Since the methods read() and close() of FileReader class throws IOException, you can observe
that the compiler notifies to handle IOException, along with FileNotFoundException.

2. UNCHECKED EXCEPTIONS
An unchecked exception is an exception that occurs at the time of execution. These are also called
as Runtime Exceptions. These include programming bugs, such as logic errors or improper use of an API.
Runtime exceptions are ignored at the time of compilation.
Types of runtime exceptions
1. ArithmeticException
It is thrown when an exceptional condition has occurred in an arithmetic operation.
2. ArrayIndexOutOfBoundsException
It is thrown to indicate that an array has been accessed with an illegal index. The index is
either negative or greater than or equal to the size of the array.
3. ClassNotFoundException
This Exception is raised when we try to access a class whose definition is not found
4. FileNotFoundException
This Exception is raised when a file is not accessible or does not open.
5. IOException
It is thrown when an input-output operation failed or interrupted
6. InterruptedException
It is thrown when a thread is waiting , sleeping , or doing some processing , and it is
interrupted.
7. NoSuchFieldException
It is thrown when a class does not contain the field (or variable) specified
8. NoSuchMethodException
It is thrown when accessing a method which is not found.
9. NullPointerException
This exception is raised when referring to the members of a null object. Null represents
nothing
10. NumberFormatException
This exception is raised when a method could not convert a string into a numeric format.
11. RuntimeException
This represents any exception which occurs during runtime.
12. StringIndexOutOfBoundsException
It is thrown by String class methods to indicate that an index is either negative than the size
of the string

For example, if you have declared an array of size 5 in your program, and trying to call the 6 th element of
the array then an ArrayIndexOutOfBoundsExceptionexception occurs.
Example
public class Unchecked_Demo
{

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


33
CST 205, S3, CSE MODULE 3

public static void main(String args[])


{
int num[] = {1, 2, 3, 4};
[Link](num[5]);
}
}

If you compile and execute the above program, you will get the following exception.
Output
Exception in thread "main" [Link]: 5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)
1. ArithmeticException

// Java program to demonstrate ArithmeticException


class ArithmeticException_Demo
{
public static void main(String args[])
{
try
{
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
[Link] ("Result = " + c);
}
catch(ArithmeticException e)
{
[Link] ("Can't divide a number by 0");
}
}
}
Output:
Can't divide a number by 0

2. NullPointerException

//Java program to demonstrate NullPointerException


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

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


34
CST 205, S3, CSE MODULE 3

{
try
{
String a = null; //null value
[Link]([Link](0));
}
catch(NullPointerException e)
{
[Link]("NullPointerException..");
}
}
}
Output:
NullPointerException..

3. StringIndexOutOfBoundException

// Java program to demonstrate StringIndexOutOfBoundsException


class StringIndexOutOfBound_Demo
{
public static void main(String args[])
{
try
{
String a = "This is like chipping "; // length is 22
char c = [Link](24); // accessing 25th element
[Link](c);
}
catch(StringIndexOutOfBoundsException e)
{
[Link]("StringIndexOutOfBoundsException");
}
}
}
Output:
StringIndexOutOfBoundsException

4. FileNotFoundException

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


35
CST 205, S3, CSE MODULE 3

//Java program to demonstrate FileNotFoundException


import [Link];
import [Link];
import [Link];
class File_notFound_Demo
{
public static void main(String args[ ])
{
try
{

// Following file does not exist


File file = new File("E://[Link]");

FileReader fr = new FileReader(file);


}
catch (FileNotFoundException e)
{
[Link]("File does not exist");
}
}
}
Output:
File does not exist

5. NumberFormatException

// Java program to demonstrate NumberFormatException


class NumberFormat_Demo
{
public static void main(String args[])
{
try
{
// "hi" is not a number
int num = [Link] ("hi") ;

[Link](num);
}
catch(NumberFormatException e)
{
[Link]("Number format exception");

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


36
CST 205, S3, CSE MODULE 3

}
}
}
Output:
Number format exception

6. ArrayIndexOutOfBounds Exception

// Java program to demonstrate ArrayIndexOutOfBoundException


class ArrayIndexOutOfBound_Demo
{
public static void main(String args[])
{
try{
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
[Link] ("Array Index is Out Of Bounds");
}
}
}
Output:
Array Index is Out Of Bounds

MULTIPLE CATCH BLOCKS


There are few rules about multiple catch blocks with the help of examples. To read this in detail,
see catching multiple exceptions in java.
1. A single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions. Whether it is ArrayIndexOutOfBoundsException
or ArithmeticException or NullPointerException or any other type of exception, this handles all of them.

catch(Exception e)
{
//This catch block catches all the exceptions
}

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


37
CST 205, S3, CSE MODULE 3

If you are wondering why we need other catch handlers when we have a generic that can handle all. This is
because in generic exception handler you can display a message but you are not sure for which type of
exception it may trigger so it will display the same message for all the exceptions and user may not be able
to understand which exception occurred. Thats the reason you should place is at the end of all the specific
exception catch blocks

3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can hanlde ArithmeticException
catch(NullPointerException e) is a catch block that can handle NullPointerException
5. You can also throw exception, which is an advanced topic and I have covered it in separate
tutorials: user defined exception, throws keyword, throw vs throws.

Example of Multiple catch blocks


class Example2
{
public static void main(String args[])
{
try
{
int a[]=new int[7];
a[4]=30/0;
[Link]("First print statement in try block");
}

catch(ArithmeticException e)
{
[Link]("Warning: ArithmeticException");
}

catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Warning: ArrayIndexOutOfBoundsException");
}

catch(Exception e)
{
[Link]("Warning: Some Other exception");
}

[Link]("Out of try-catch block...");


}

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


38
CST 205, S3, CSE MODULE 3

}
Output:

Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks executes sequentially when
an exception occurs in try block. Which means if you put the last catch block ( catch(Exception e)) at the
first place, just after try block then in case of any exception this block will execute as it can handle
all exceptions. This catch block should be placed at the last to avoid such situations.

NESTED TRY BLOCK


class Nest
{
public static void main(String args[])
{
try //Parent try block
{
try //Child try block1
{
[Link]("Inside block1");
int b =45/0;
[Link](b);
}
catch(ArithmeticException e1)
{
[Link]("Exception: e1");
}

try //Child try block2


{
[Link]("Inside block2");
int b =45/0;
[Link](b);
}
catch(ArrayIndexOutOfBoundsException e2)
{
[Link]("Exception: e2");
}
[Link]("Just other statement");

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


39
CST 205, S3, CSE MODULE 3

} //parent try closed

catch(ArithmeticException e3)
{
[Link]("Arithmetic Exception");
[Link]("Inside parent try catch block");
}
catch(ArrayIndexOutOfBoundsException e4)
{
[Link]("ArrayIndexOutOfBoundsException");
[Link]("Inside parent try catch block");
}
catch(Exception e5)
{
[Link]("Exception");
[Link]("Inside parent try catch block");
}
[Link]("Next statement..");

} // main close
} //class nest close

Output:

Inside block1
Exception: e1
Inside block2
Arithmetic Exception
Inside parent try catch block
Next statement..

throw IN EXCEPTION
The throw keyword is used to create a custom error.

The throw statement is used together with an exception type. There are many exception
types available in
Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsExceptio
n, SecurityException, etc.

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


40
CST 205, S3, CSE MODULE 3

The exception type is often used together with a custom method, like in the example
shown below.

Example
Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":

public class MyClass


{
static void checkAge(int age)
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at least
18 years old.");
}
else
{
[Link]("Access granted - You are old enough!");
}
}

public static void main(String args[ ])


{
checkAge(15); // Set age to 15 (which is below 18...)
}
}
OUTPUT
Exception in thread "main" [Link]: Access denied - You must be
at least 18 years old.
at [Link]([Link])
at [Link]([Link])

throws IN EXCEPTION
The throws keyword indicates what exception type may be thrown by a method.

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


41
CST 205, S3, CSE MODULE 3

There are many exception types available in


Java: ArithmeticException, ClassNotFoundException, ArrayIndexOutOfBoundsExceptio
n, SecurityException, etc.

Example

Throw an exception if age is below 18 (print "Access denied"). If age is 18 or older, print
"Access granted":
public class MyClass
{
static void checkAge(int age) throws ArithmeticException
{
if (age < 18)
{
throw new ArithmeticException("Access denied - You must be at
least 18 years old.");
}
else
{
[Link]("Access granted - You are old enough!");
}
}

public static void main(String[] args)


{
checkAge(15); // Set age to 15 (which is below 18...)
}
}

OUTPUT

Exception in thread "main" [Link]: Access denied - You must be


at least 18 years old.
at [Link]([Link])
at [Link]([Link])

Differences between throw and throws:

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


42
CST 205, S3, CSE MODULE 3

Throw throws

Used to throw an exception for a method Used to indicate what exception type may
method

Cannot throw multiple exceptions Can declare multiple exceptions

Syntax: Syntax:
 throw is followed by an object (new type)  throws is followed by a class
 used inside the method  and used with the method signatur

JAVA finally BLOCK


A finally block contains all the crucial statements that must be executed whether
exception occurs or not. The statements present in this block will always execute
regardless of whether exception occurs in try block or not such as closing a connection,
stream etc.

Syntax of finally block


try
{
//Statements that may cause an exception
}
catch
{
//Handling exception
}
finally
{
//Statements to be executed
}

A Simple Example of finally block

Here we can see that the exception occurred in try block which has been handled in catch
block, after that finally block got executed.

class Example

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


43
CST 205, S3, CSE MODULE 3

{
public static void main(String args[])
{
try
{
int num=121/0;
[Link](num);
}
catch(ArithmeticException e)
{
[Link]("Number should not be divided by zero");
}

/* Finally block will always execute


* even if there is no exception in try block
*/

finally
{
[Link]("This is finally block");
}
[Link]("Out of try-catch-finally");
}
}

Output:

Number should not be divided by zero


This is finally block
Out of try-catch-finally

Prepared by GREESHMA GS, Asst. Professor, Dept. of CSE, JCET, 2020


CS205 Object Oriented Programming in

Java
Module 4 - Advanced features of Java
(Part 3)
1
Java Library

❑ Collections framework

❑ Collections overview

❑ Collections Interfaces- Collection Interface


• The contains one of Java’s most powerful
subsystems: The Collections Framework.

• The Collections Framework is a sophisticated hierarchy of


interfaces and classes that provide state-of-the-art
technology(best possible technlogy) for managing groups of
objects.

3
Figure 1 Interfaces and Classes in the Java Collections Framework
• The Java Collections Framework standardizes the way
in which groups of objects are handled by our
programs.

• The entire Collections Framework is built upon a set of


standard interfaces.

• Mechanisms were added that allow the integration of


standard arrays into the Collections Framework.
• The Collections Framework was designed to meet several
goals.
– First, the framework had to be high-performance.

• The implementations for the fundamental collections


(dynamic arrays, linked lists, trees, and hash tables) are
highly efficient.

– Second, the framework had to allow different types of


collections to work in a similar manner and with a high
degree of interoperability.

– Third, extending and/or adapting a collection had to be


easy.
• Algorithms are an important part of the collection
mechanism.

– Algorithms operate on collections and are defined as static


methods within the Collections class.

– The algorithms provide a standard means of manipulating


collections.
• Java Collections Framework provides algorithm
implementations that are commonly used such as sorting,
searching etc.
– void sort(List list)
– int binarySearch(List list, Object value)
• Another item closely associated with the Collections
Framework is the Iterator interface.

– An iterator offers a general-purpose, standardized way of


accessing the elements within a collection, one at a time.

– An iterator provides a means of enumerating the contents


of a collection.

– Because each collection implements Iterator, the elements


of any collection class can be accessed through the methods
defined by Iterator
• The framework defines several map interfaces and

classes.

– Maps store key/value pairs.

• A map cannot contain duplicate keys.

• Although maps are part of the Collections Framework,

they are not “collections” in the strict use of the term


• Collections Framework underwent a fundamental change
that significantly increased its power and streamlined its
use.

– The changes were caused by the addition of

• generics

• autoboxing/unboxing, and

• for-each style for loop.


⮚ Generics add the one feature : type safety.

– With generics, it is possible to explicitly state the type of data


being stored, and run-time type mismatch errors can be avoided.

⮚ Autoboxing/unboxing facilitates the storing of primitive


types in collections.
• IN THE PAST, if we wanted to store a primitive value, such
as an int, in a collection, we had to manually box it into its
type wrapper.
• When the value was retrieved, it needed to be manually
unboxed (by using an explicit cast) into its proper primitive
type.
– Because of autoboxing/unboxing, Java can automatically perform
the proper boxing and unboxing needed when storing or
retrieving primitive types.
The Collection Framework

• The Collections Framework defines several interfaces.


• Collection interface helps to work with group of objects

• The Collection interface is at the top of collections hierarchy.


• Collection interface is the foundation upon which the
Collections Framework is built
– because it must be implemented by any class that defines a
collection.
• Collection is a generic interface that has this declaration:

– Here, E specifies the type of objects that the collection will

hold.
• Collection extends the Iterable interface.
– This means that all collections can be cycled through by use of
the for-each style for loop.
Collection declares the core methods that all collections will have.

Several of these methods can throw an UnsupportedOperationException if a


collection cannot be modified.

A ClassCastException is generated when one object is incompatible with


another.

A NullPointerException is thrown if an attempt is made to store a null object

and null elements are not allowed in the collection.

An IllegalArgumentException is thrown if an invalid argument is used.

An IllegalStateException is thrown if an attempt is made to add an element


to a fixed-length collection that is full.
15
• Objects are added to a collection by calling add( ).

– add( ) takes an argument of type E, which means that


objects added to a collection must be compatible with the
type of data expected by the collection.
• To add the entire contents of one collection to another by
calling addAll( ).
• To remove an object call remove( ).
• To remove a group of objects, call removeAll( ).
• To remove all elements except those of a specified group by
call retainAll( ).
• To empty a collection, call clear( ).
16
• We can check whether a collection contains a specific object
by calling contains( ).
• To check whether one collection contains all the members of
another, call containsAll( ).
• To determine whether a collection is empty call isEmpty().
• The number of elements currently held in a collection can be
determined by calling size( ).
• The toArray( ) methods return an array that contains the
elements stored in the invoking collection.
⮚ Object[ ] toArray( ) returns an array of Object.
⮚ <T> T[ ] toArray(T array[ ]) returns an array of elements that
have the same type as the array specified as a parameter.
. 17
• Two collections can be compared whether they are equal or
not by calling equals( ).
• The precise meaning of “equality” may differ from collection
to collection.
– equals( ) can be implemented to compare the values of
elements stored in the collection.
– equals( ) can be implemented to compare references to
those elements.
• The method iterator( ) returns an iterator to a collection.
– Iterators help to loop through the collections.

18
• Herbert Schildt, Java: The Complete Reference, 8/e,
Tata McGraw Hill, 2011.

19
CS205 Object Oriented Programming in

Java
Module 4 - Advanced features of Java
(Part 4)
1
Topics
Java Library

❑ Collections framework

​ List Interface

​ Collections Class

​ ArrayList Class
List Interface

• The List interface extends Collection interface.

• List declares the behavior of a collection that stores a


sequence of elements.

– In Java, the List interface is an ordered collection that allows us


to store and access elements sequentially.

• Elements can be inserted or accessed by their position in the


list, using zero-based index.

• A list may contain duplicate elements.

• List is a generic interface that has this declaration:


interface List<E>

List Interface(contd.)

• List supports methods defined by Collection,


• List defines its own methods also.
• Some methods throw exceptions.
• Exceptions that are thrown by List methods are:
UnsupportedOperationException
• if the list cannot be modified
ClassCastException
• when one object is incompatible with another
IndexOutOfBoundsException
• if an invalid index is used
NullPointerException
• thrown if an attempt is made to store a null
object and null elements are not allowed in the list.
IllegalArgumentException
• if an invalid argument is used.

Methods in List interface


5
Methods in List interface (contd.)

• List has many methods:-


• add(int, E) and addAll(int, Collection)
• These methods insert elements at the specified index.
• The meaning of add(E) and addAll(Collection) defined by
Collection are changed by List. In List they add elements to
the end of the list.
• o all
with the index of the object.
• To assign a value to an element in the list, call set( ),
specifying the index of the object to be changed.
• To find the index of an object, use indexOf( ) or
lastIndexOf().
• A sublist of a list can be obtained by calling subList() ,
specifying the beginning and ending indexes of the sublist.
. 6
The Collection Classes

• The collection classes implement collection interfaces.


• Some of the collection classes provide full
implementations that can be used as-is.

• Some of the collection classes are abstract, providing


skeletal implementations that are used as starting points
for creating concrete collections.

• Collection classes are not synchronized.


– Two or more threads can access the methods of collection
class at any time.
7
The standard collection classes are

8
ArrayList Class

• The ArrayList class extends AbstractList and implements


the List interface.

• ArrayList is a generic class that has declaration:

class ArrayList<E>
– Here, E specifies the type of objects that the list will hold.

• ArrayList supports dynamic arrays that can grow as needed.

– This is needed because in some cases we may not know


how large an array we need precisely until run time.

9
ArrayList Class(contd.)

• An ArrayList is a variable-length array of object references.


– So ArrayList can dynamically increase or decrease in size.

• Array lists are created with an initial size.


– When this size is exceeded, the collection is automatically
enlarged.

– When objects are removed, the array can be shrunk.


10
ArrayList Class(contd.)

• ArrayList has following


constructors: ArrayList( )
⮚ This constructor builds an empty array list.
ArrayList(Collection<? extends E> c)
– This constructor builds an array list that is initialized with
the elements of the collection c.
ArrayList(int capacity)
– This constructor builds an array list that has the specified initial
capacity.
– The capacity is the size of the underlying array that is used to
store the elements.
– The capacity grows automatically as elements are added to an
array list.
11
ArrayList Class(contd.)

import [Link].*;
class ArrayListDemo
{
public static void main(String args[]) {
ArrayList<String> al = new ArrayList<String>();
[Link]("Initial size=" +[Link]());

[Link]("C"); [Link]("Size now="


+[Link]());
[Link]("A");
[Link]("E");
[Link]("B");
[Link]("D");
[Link]("F");
[Link](1, "A2");
[Link]("Contents : " + al); }
}
[Link]("F");
Initial size=0
[Link](2);
Size now=7
[Link]("Size=" +[Link]()); Contents : [C, A2, A, E, B, D, F]
[Link]("Contents=" +al); Size=5
Contents=[C, A2, E, B, D]
12
ArrayList Class(contd.)

• The contents of a collection are displayed using the default


conversion provided by toString( ), which was inherited from
AbstractCollection.

• We can increase the capacity of an ArrayList object manually


by calling ensureCapacity( ).

void ensureCapacity(int cap)

• If we want to reduce the size of the array that ofArrayL ist


object so that it is precisely as large as the number of items
that it is currently holding, call trimToSize( ):

13

void trimToSize( )
Obtaining an Array from an ArrayList

• To convert a collection into an array, toArray( ), which is


defined by Collection can be called.

– This is needed

• To obtain faster processing times for certain operations

• To pass an array to a method that is not overloaded to


accept a collection

• To integrate collection-based code with legacy code


that does not understand collections

• Two versions of toArray( ) are:


Object[ ] toArray( )
<T> T[ ] toArray(T array[ ])
14
ArrayList Class(contd.)

import [Link].*;
class ArrayListToArray {
public static void main(String args[]) {
ArrayList<Integer> al = new ArrayList<Integer>();

[Link]("Conte
[Link](1); nts of al: " + al);
[Link](2); Integer arr[] = new
[Link](3); Integer[[Link]()]; arr =
[Link](arr);
int sum = 0;
[Link](4);

for(int i : arr) sum += i;

[Link]("Sum is: " + sum);


}
}

Contents of al: [1, 2, 3, 4]


Sum is: 10
15
Reference

• Herbert Schildt, Java: The Complete Reference, 8/e,


Tata McGraw Hill, 2011.

6
CST205ObjectOrientedProgrammingusingJava (As
per KTU 2019 Syllabus)

Module4
MultithreadedProgramming
Definitionofthread
Athreadisasinglesequentialflowof
control within a program.

Therealexcitementsurrounding
threads is not about a single
sequential thread.

Rather,it'sabouttheuseofmultiple
threads running at the same time
and performing different tasks in a
single program

Threadsarelightweightprocesses
within a process.
Asinglethreadedprogram

begin

body

end

4
AMultithreadedProgram

start start

Threadsmayswitchorexchangedata/results
Multiple Clients Concurrently

Client1Process ServerProcess

Server
Threads

Client2Process

6
Web/InternetApplications:

ServingManyUsersSimultaneously
PC client

Internet
Server LocalAreaNetwork

PDA
7
Multithreadedprogramming
● Javaisamultithreadedprogramminglanguage
● Athreadisanindependentpathofexecutionwithinaprogram,mostofthe
programs are single threaded
● Multithreadingreferstotwoormoretasksexecutingconcurrentlywithinasingle
program.
● Manythreadscanrunconcurrentlywithina program.

● [Link] class.
● AJavaprogramcanhavemanythreads,andthesethreadscanrunconcurrently, either
asynchronously or synchronously.
AdvantagesofJavaMultithreading
■ Itdoesn'tblocktheuserbecausethreadsareindependent and
you can perform multiple operations at same time.
■ Youcanperformmanyoperationstogethersoitsaves time.
■ Threadsareindependentsoitdoesn'taffectotherthreads if
exception occur in a single thread.

■ Note:Atatimeonethreadisexecutedonly.
JavaThreadSupport
■ JavahasbuiltinthreadsupportforMultithreading
■ Synchronization
■ ThreadScheduling
■ Inter-ThreadCommunication:
■ currentThread start setPriority
■ yield run getPriority
■ sleep stop suspend
■ resume
■ JavaGarbageCollectorisalow-prioritythread.
10
LifeCycleofaThread
Statesofthethreadlifecycle
1. Newborn:Whenathreadiscreated(bynewstatement)butnotyettorun,itis called in
Newborn state. In this state, the local data members are allocated and
initialized.
2. Runnable : The Runnable state means that a thread is ready to run and is
awaitingforthecontroloftheprocessor,orinotherwords,threadsareinthis state in
a queue and wait their turns to be executed.
3. Running:Runningmeansthatthethreadhascontroloftheprocessor,itscode is
currently being executed and thread will continue in this state until it get
preempted by a higher priority thread, or until it relinquishes control.
4. Blocked :Athread is Blocked means that it is being prevented from the
Runnable(orRunning)stateandiswaitingforsomeeventinorderforitto reenter
the scheduling queue.
5. Terminated(Dead):AthreadisDeadwhenitfinishesitsexecutionorisstopped
(killed)byanotherthread
Transitionsfromrunningstate
ARunningThreadtransittooneofthenon-runnablestates,dependinguponthe
circumstances.

• Sleeping:TheThreadsleepsforthespecifiedamountoftime.

• BlockedforI/O:TheThreadwaitsforablockingoperationtocomplete.

• Blockedforjoincompletion:TheThreadwaitsforcompletionofanotherThread.

• Waitingfornotification:TheThreadwaitsfornotificationanotherThread.

• Blockedforlockacquisition:TheThreadwaitstoacquirethelockofanobject.

JVMexecutestheThread,basedontheirpriorityand scheduling.
ThreadPriorities
● EveryJavathreadhasaprioritythathelpstheoperatingsystemdetermine the
order in which threads are scheduled.
● JavathreadprioritiesareintherangebetweenMIN_PRIORITY(aconstantof 1)
and MAX_PRIORITY (a constant of 10).
● DefaultthreadpriorityisNORM_PRIORITY(aconstantof5).

● Threadswithhigherpriorityaremoreimportanttoaprogramandshouldbe
allocated processor time before lower-priority threads.
● Threadprioritiescannotguaranteetheorderinwhichthreadsexecuteand are
very much platform dependent.
MainThread
● WhenaJavaprogramstartsup,onethreadbeginsrunningimmediately.
● Thisisusuallycalledthemainthreadofourprogram,becauseitistheone that is
executed when our program begins.
● Itisthethreadfromwhichother“child”threadswillbe spawned.

● Often,itmustbethelastthreadtofinishexecutionbecauseitperforms
various shutdown actions
● Themainthreadiscreatedautomaticallywhenourprogramis started.

● Tocontrolitwemustobtainareferencetoitbycallingthemethod
currentThread()whichispresentinThreadclass.
● Thismethodreturnsareferencetothethreadonwhichitiscalled.
● ThedefaultpriorityofMainthreadis5andforallremaininguserthreads priority
will be inherited from parent to child.
Flowdiagramofmain thread
ThreadcreationinJava
Therearetwowaystocreateathread:

1. ByextendingThreadclass[[Link]]
2. ByimplementingRunnableinterface.[[Link]]

Whatistheneedforthisdual option?

Remember-Javadoesnotsupportmultipleinheritance
ThreadcreationinJava
[Link]
[Link]
interface

(objectsarethreads) (objectswithrun()body)
[a] [b]
18
CreateaThreadbyExtendingaThreadClass
Providesmoreflexibilityinhandlingmultiplethreadscreatedusingavailable methods in
Thread class.

CreateanewclassthatextendsThreadclassusingthefollowingsteps.

● Step1-Youwillneedtooverriderun()methodavailableinThreadclass.
● Thismethodprovidesanentrypointforthe thread
● Syntaxofrun()method−publicvoidrun()

● Step2-OnceThreadobjectiscreated,youcanstartitbycallingstart()
method,whichexecutesacalltorun() method.
● Syntaxofstart()method−voidstart();
Threadclass
Threadclassprovideconstructorsandmethodstocreateandperformoperations on a
thread.

• ThreadclassextendsObjectclassandimplementsRunnableinterface.

CommonlyusedConstructorsofThread class:

• Thread()

• Thread(Stringname)

• Thread(Runnabler)

• Thread(Runnabler,Stringname)

Note:Stringargumentistoassignathreadname.
Threadclassmethods
ThreadMethods-Followingisthelistofimportantmethodsavailableinthe Thread class.
• publicvoidrun():isusedtoperformactionfora thread.

• publicvoidstart():startstheexecutionofthethread. JVMcallstherun()method on
the thread.
• publicstaticvoidsleep(longmilliseconds) :Causesthecurrentlyexecuting
thread to sleep for the specified number of milliseconds.
• publicvoidjoin():waitsforathreadtodie.

• publicintgetPriority():returnsthepriorityofthe thread.
• publicintsetPriority(intpriority):changesthepriorityofthethread.
Threadclassmethods
• publicStringgetName():returnsthenameofthethread.
• publicThreadcurrentThread():returnsthereferenceofcurrentlyexecutingthread.
• publicint getId():returnstheidofthe thread.
• [Link]():returnsthestateofthethread.
• publicbooleanisAlive():testsifthethreadisalive.
• publicvoidsuspend():isusedtosuspendthethread(depricated).
• publicvoidresume():isusedtoresumethesuspendedthread
• publicvoidstop():isusedtostopthe thread(depricated).
• public boolean isDaemon() : tests if the thread is a daemon thread. Daemon
thread is a low priority thread (in context of JVM) that runs in background to perform
tasks suchasgarbagecollection(gc)etc.,theydonotpreventtheJVMfromexiting(evenif
the daemon thread itself is running) when all the user threads (non-daemon threads)
finish their execution
[Link]()&[Link]()
● InJava’smultithreadingconcept,start()andrun()arethetwomostimportant
methods.
● Whenaprogramcallsthestart()method,anewthreadiscreatedandthen the
run() method is executed.
● Butifwedirectlycalltherun()methodthennonewthreadwillbecreatedand run()
method will be executed as a normal method call on the current calling
thread itself and no multithreading will take place.
[Link]()&[Link]()
[Link]()&[Link]()
[Link]()&[Link]()
ByImplementingaRunnableInterface
IftheclassisintendedtobeexecutedasathreadthenimplementRunnable interface.

Step1-implementarun()[Link] provides
an entry point for the thread. [ public void run( ) ]

Step2-Asasecondstep,youwill instantiateaThreadobjectusingthefollowing
constructor−Thread(RunnablethreadObj,StringthreadName);

- threadObjisaninstanceofaclassthatimplementstheRunnableinterface.
- threadNameisthenamegiventothenewthread[optional].

Step3-OnceaThreadobjectiscreated,youcan startitbycallingstart()method, which


executes a call to run( ) method. [ void start(); ]
1stmethod:ExtendingThread

class

■ CreateaclassbyextendingThreadclassandoverride
run()method:

classMyThreadextendsThread
{
publicvoidrun()
{
//threadbodyofexecution
}
}

■ Createathread:

MyThreadthr1=newMyThread();

■ StartExecutionofthreads:

[Link]();
■ CreateandExecute:

new
An example
classMyThreadextendsThread{
public void run() {
[Link]("thisthreadisrunning...");

classThreadEx1{

publicstaticvoidmain(String[]args){
MyThread t = new MyThread();
[Link]();
}

31
2nd method: Threads by
implementingRunnableinterface
■ CreateaclassthatimplementstheinterfaceRunnableand
override run() method:
classMyThreadimplementsRunnable
{
.....
publicvoidrun()
{
//threadbodyofexecution
}
}
■ CreatingObject:
MyThreadmyObject=newMyThread();
■ CreatingThreadObject:
Threadthr1=newThread(myObject);
■ StartExecution:
[Link]();
32
Anexample
classMyThreadimplementsRunnable{ public
void run() {
[Link]("thisthreadisrunning...");

classThreadEx2{

publicstaticvoidmain(String[]args){
Threadt=newThread(newMyThread());
[Link]();
}

33
CreatingMultipleThreads
● Thiscanbedonebycreatingtheinstancesoftheclasseswhichareeither
extending Thread class or implementing runnable interface.
● TODO:Runasimpleprogramwhichcreatesmultiplethreadsandidentifythe
maximum number of threads possible from your program.
● Joinmethodcanjointhenewlycreatedthreadwithmainthread
Synchronization
Whenwestarttwoormorethreadswithinaprogram,theremaybeasituation when
multiple threads try to access the same resource and finally they can produce
unforeseen result due to concurrency issues.
• For example, if multiple threads try to write within a same file then they may
corruptthedatabecauseoneofthethreadscanoverridedataorwhileonethread is
opening the same file at the same time another thread might be closing the same
file.
• Sothereisaneedtosynchronizetheactionofmultiplethreadsandmakesure that
only one thread can access the resource at a given point in time.
Followingisthegeneralformofthesynchronizedstatement:

synchronized(objectidentifier)
{
//Accesssharedvariablesandothershared resources
}
Synchronization
● Thekeywordsynchronizedisusedbywhichmethod(s)orblockof
statements can be made protected from the simultaneous access.
Synchronization
● Whentwoormorethreadswantto(W)accessasharedresource,ensureonly one
thread has access to that resource at a time to avoid raise condition
● Thekeywordsynchronizedisusedbywhichmethod(s)orblockof
statements can be made protected from the simultaneous access.
● The entire time that a thread is inside of a synchronized method, all other
threadsthattrytocallanyothersynchronizedmethodonthesameinstance have
to wait.
● InJava,synchronizedkeywordcausesaperformancecost.

● AsynchronizedmethodinJavaisveryslowandcandegradeperformance.
● So we must use synchronization keyword in java when it is necessary else,
weshoulduseJavasynchronizedblockthatisusedforsynchronizingcritical
section only.
SuspendingThread
• Thesuspend()methodofthreadclassputsthethreadfromrunningtowaitingstate.
• Thismethodisusedifyouwanttostopthethreadexecutionandstartitagainwhen a
certain event occurs.
• Thismethodallowsathreadtotemporarilycease execution.
• Thesuspendedthreadcanberesumedusingtheresume()method.

Syntax
publicfinalvoidsuspend()
SuspendingThread
ResumingThread
• Theresume()methodofthreadclassisonlyusedwithsuspend()method.
• Thismethodisusedtoresumeathreadwhichwassuspendedusingsuspend()
method.
• Thismethodallowsthesuspendedthreadtostartagain.
Syntax
publicfinalvoidresume(
ResumingThread
TerminatingaThread
• Thestop()methodofthreadclassterminatesthethreadexecution.
• Onceathreadisstopped,itcannotberestartedbystart()method.
Syntax
publicfinalvoidstop()
publicfinalvoidstop(Throwableobj)
TerminatingaThread
Inter-threadCommunication
Thefirstisthrough [Link] memory
space.

Thesecondwayforthreadstocommunicateisbyusing threadcontrolmethods.

● suspend():Athreadcansuspenditselfandwaittillanotherthreadresumeit.
● resume():Athreadcanwakeupotherwaitingthread
● join():Thismethodcanbeusedforthecallerthreadtowaitforthecompletionofcalledthread.

Thethirdwayforthreadstocommunicateistheuseofthreemethods; wait(),notify(),andnotifyAll(); these are


defined in class Object of package [Link].

● wait():tellsthecallingthreadtogiveupthemonitorandmakethecallingthreadwaituntileither a time out


occurs or another thread call the same thread's notify() or notifyAll() method.
● notify():willwakeuptheonlyone(first) waitingthreadcalledwait()onthesameobject.
● notifyAll():willwakeupallthethreadsthathavebeencalledwait()onthesame object.
ProducerConsumerProblem
Strings
• InJava,[Link]
works same as Java string. For example:

char[]ch={‘h','a',‘i',‘j',‘a',‘v',‘a'}; String

s=new String(ch);

issameas:

Strings= “haijava";

• JavaStringclassprovidesalotofmethodstoperformoperationsonstringssuchas compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
Createastringobject
TherearetwowaystocreateStringobject:
• Bystringliteral
• Bynew keyword
1) StringLiteral
JavaStringliteraliscreatedbyusingdoublequotes.

ForExample:
Strings="welcome";
• Eachtimeyoucreateastringliteral,theJVMchecksthe"stringconstantpool"first.
• Ifthestringalreadyexistsinthepool,areferencetothepooledinstanceisreturned.
• Ifthestringdoesn'texistinthepool,anewstringinstanceiscreatedandplacedinthepool. For
example:
Strings1="Hello";
Strings2="Hello";//Itdoesn'tcreateanewinstance
Createastringobject
Strings1="Hello";
Strings2="Hello";//Itdoesn'tcreateanewinstance

• Intheaboveexample,onlyoneobjectwillbecreated.
• Firstly, JVM will not find any string object with the
value"Hello"instringconstantpool,thatiswhyitwillcreateanewO
bject.
• Afterthatitwillfindthestringwiththevalue"Hello"inthe

pool,itwillnotcreateanewobjectbutwillreturnthereferenceto the same


instance.
• Note:Stringobjectsarestoredinaspecialmemoryareaknownas
the "string constant pool".
● stringconstantpoolmakesJavamorememoryefficient(becausenonewobjects are
created if it exists already in the string constant pool).
● Alsoitmakesstringlite
Createastringobject
2. Byusingnewkeyword

Strings=newString("Welcome");//createstwoobjects
andonereferencevariable

• Insuchcase,JVMwillcreateanewstringobjectinnormal
(non-pool)inheapmemory,andtheliteral"Welcome"willbeplaced in the
string constant pool.
• Thevariableswillrefertotheobjectinaheap(non-pool).
Createastringobject
2. Byusingnewkeyword

Strings=newString("Welcome");//createstwoobjects
andonereferencevariable

• Insuchcase,JVMwillcreateanewstringobjectinnormal
(non-pool)inheapmemory,andtheliteral"Welcome"willbeplaced in the
string constant pool.
• Thevariableswillrefertotheobjectinaheap(non-pool).
Stringsample
STRINGCONSTRUCTORS
• ThestringclasssupportsseveraltypesofconstructorsinJavaAPIs.
The most commonly used constructors of String class are as follows:
1. String():TocreateanemptyString,[Link]: String
s = new String();
• Itwillcreateastringobjectintheheapareawithnovalue

2. String(Stringstr):Itwillcreateastringobjectintheheapareaandstoresthegiven value
in it. For example:
Strings2=newString(“HelloJava“);
Now,theobjectcontainsHelloJava.
3. String(charchars[]):Itwillcreateastringobjectandstoresthearrayofcharactersin it. For
example:
charchars[]={‘a’,‘b’,‘c’,‘d’};
String s3 = new String(chars);
Theobjectreferencevariables3containstheaddressofthevaluestoredintheheaparea.
STRINGCONSTRUCTORS
4. String(charchars[],intstartIndex,intcount)
• Itwillcreateandinitializesastringobjectwithasubrangeofacharacterarray.
• TheargumentstartIndexspecifiestheindexatwhichthesubrangebeginsandcount
specifies the number of characters to be copied.
Forexample:

charchars[]={‘w’,‘i’,‘n’,‘d’,‘o’,‘w’,‘s’}; String str =


new String(chars, 2, 3);
• The object str contains the address of the
value
”ndo”storedintheheapareabecausethestarting
index is 2 and the total number of
characterstobecopiedis3
STRINGCONSTRUCTORS
5. String(bytebyteArr[])-Itconstructsanewstringobjectbydecodingthegivenarrayof bytes
(i.e, by decodingASCII values into the characters) according to the system’s default
character set.
STRINGCONSTRUCTORS
6. String(bytebyteArr[],intstartIndex,intcount)
ThisconstructoralsocreatesanewstringobjectbydecodingtheASCIIvaluesusingthe system’s
default character set.
STRINGLENGTH
• Thejavastringlength()[Link] of
characters.

• Internalimplementat
ion public int length()
{return [Link];
}

Signature-Thesignatureofthestringlength()methodisgivenbelow
:
publicint length()
STRINGLENGTH
STRINGCOMPARISON
• Wecancomparestringinjavaonthebasisofcontentandreference
• Therearethreewaystocomparestringinjava:

Byequals()method By
= = operator
BycompareTo()method

1. Stringcomparebyequals()method
• TheStringequals()methodcomparestheoriginalcontentofthestring.
• It compares values of string for equality. String class provides two
methodspublicbooleanequals(Objectanother)comparesthisstringtothespecifiedobj
ect. public boolean equalsIgnoreCase(String another) compares this
Stringtoanotherstring,ignoringcase.
STRINGCOMPARISON
STRINGCOMPARISON
2. Stringcompareby==operator
• The==operatorcomparesreferencesnot values.
STRINGCOMPARISON
3. StringcomparebycompareTo()method
• TheStringcompareTo()methodcomparesvalueslexicographically
and returns an integer value that describes if first string is less than,
equal to or greater than second string.
[Link]: s1 ==
s2 : 0
s1 > s2 : positive value
s1<s2:negativevalue
STRINGSEARCHING
Stringcontains()
• Thejavastringcontains()methodsearchesthesequenceofcharactersinthisstring.
• Itreturnstrueifsequenceofcharvaluesarefoundinthisstringotherwisereturnsfalse.

Signature
• Thesignatureofstringcontains()methodisgivenbelow:
publicbooleancontains(CharSequencesequence)

Internalimplementation
publicbooleancontains(CharSequences)
{
returnindexOf([Link]())>-1;
}
STRINGSEARCHING
publicbooleancontains(CharSequencesequence)
STRINGSEARCHING
publicbooleancontains(CharSequencesequence)
STRINGSEARCHING
Thecontains()methodsearchescasesensitivecharsequence.
Iftheargumentisnotcasesensitive,[Link]'sseeanexamplebelow.
CHARACTEREXTRACTION
StringcharAt()
• ThejavastringcharAt()methodreturnsacharvalueatthegivenindexnumber.
• Theindexnumberstartsfrom0andgoeston-1,wherenislengthofthe string.
• ItreturnsStringIndexOutOfBoundsExceptionifgivenindexnumberisgreaterthanor
equal to this string length or a negative number.
• ThesignatureofstringcharAt()methodisgivenbelow:

publiccharcharAt(intindex)
StringIndexOutOfBoundsExceptionwithcharAt()
• Let'sseetheexampleofcharAt()methodwherewearepassinggreaterindexvalue.
• Insuchcase,itthrowsStringIndexOutOfBoundsExceptionatruntime.
charAt()example
• Thisexamplecountsthefrequencyof‘t’ingiven string
MODIFYSTRINGS
• Thejavastringreplace()methodreturnsastringreplacingalltheoldcharor
CharSequence to new char or CharSequence.
• Therearetwotypeofreplacemethodsinjavastring.

publicStringreplace(charoldChar,charnewChar)
publicStringreplace(CharSequencetarget,CharSequencereplacement)
• ThesecondreplacemethodisaddedsinceJDK1.5.
String replace(char old, char new) method
examplepublic class ReplaceExample1{
public static void main(String args[]){
Strings1="javaisaverygoodlanguage";
// replaces all occurrences of 'a' to 'e'
StringreplaceString=[Link]('a','e');
[Link](replaceString);
}}
Output:jeveisevery
MODIFYSTRINGS
• ThejavastringreplaceAll()methodreturnsastringreplacingallthesequenceof
characters matching regex and replacement string.

Internalimplementation
publicStringreplaceAll(Stringregex,Stringreplacement)
{
[Link](regex).matcher(this).replaceAll(replacement);
}
Signature
publicStringreplaceAll(Stringregex,Stringreplacement)

Regex:RegularExpression
[Link] patterns
are used by string-searching algorithms for "find" or "find and replace" operations
onstrings,orforinputvalid
StringreplaceAll()example:replacecharacter
• Let'sseeanexampletoreplacealltheoccurrencesofasinglecharacter.

publicclassReplaceAllExample1
{
public static void main(String args[]){
Strings1="javaisaverygoodlanguage";
StringreplaceString=[Link]("a","e");//replacesalloccurrences of
"a" to "e"
[Link](replaceString);

}
}

Output:jeveiseverygoodlenguege
StringreplaceAll()example:replaceword
• Let'sseeanexampletoreplacealltheoccurrencesofsinglewordorsetofwords.
StringreplaceAll()example:replacewhitespace
• Let'sseeanexampletoreplacealltheoccurrencesofwhitespaces
STRINGVALUEOFMETHOD
• ThejavastringvalueOf()methodconvertsdifferenttypesofvaluesintostring.
• BythehelpofstringvalueOf()method,wecanconvertinttostring,longtostring,boolean to
string, character to string, float to string, double to string, object to string and char array to
string.

Internalimplementation
public static String valueOf(Object obj) {
return(obj==null)?"null":[Link]();
}
STRINGVALUEOFMETHOD
• ThesignatureorsyntaxofstringvalueOf()methodisgivenbelow:
publicstaticStringvalueOf(booleanb)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)
valueOf(booleanbol)MethodExample
ThisisabooleanversionofoverloadedvalueOf()[Link]
boolean value and returns a string. Let's see an example.
valueOf()MethodExample
ImmutableStringinJava
In java, string objects are immutable. Immutable simply means unmodifiable or
[Link]'tbechangedbutanew string
object is created.
ImmutableStringinJava
[Link] object is
created with sachintendulkar. That is why string is known as immutable.
ImmutableStringinJava
• Asyoucanseeinthefigurethattwoobjectsarecreatedbutsreferencevariablestill refers
to "Sachin" not to "Sachin Tendulkar".
• Butifweexplicitlyassignittothereferencevariable,itwillreferto"SachinTendulkar"
object. For example:
Whystringobjectsareimmutableinjava
• InJava,Stringisafinalandimmutableclass,whichmakesit the
most special. It cannot be inherited, and once created, we
can not alter the object.

• Becausejavausestheconceptofstringpooltosavememory.
• Supposethereare5referencevariables,allreferstooneobject
"sachin".
• Ifonereferencevariablechangesthevalueoftheobject,itwill be
affected to all the reference variables.
• Thatiswhystringobjectsareimmutableinjava.
StringandStringBuffer
JavaStringclassobjectsareimmutable.
JavaStringBufferclassisusedtocreatemutable(modifiable)string.

[Link] changed.
StringBuffer,StringBuilder
Mutablestring-Astringthatcanbemodifiedorchangedisknownasmutablestring. StringBuffer and
StringBuilder classes are used for creating mutable string.

ImportantconstructorsofStringBuffer
StringBufferappend()method
append()methodisusedtoaddcontentsattheendofthecurrent string
StringBufferinsert()method
append()methodisusedtoaddcontentsataparticular location(index)
StringBufferreplace()method
Thereplace()methodreplacesthegivenstringfromthespecifiedbeginIndexand endIndex.
StringBufferdelete()method
Thedelete()methodofStringBufferclassdeletesthestringfrom the
specified beginIndex to endIndex.
StringBufferreverse()method
Thereverse()methodofStringBufferclassreversesthecurrentstring.
COLLECTIONSINJAVA
● [Link]’smostpowerfulsubsystems:
● TheCollectionsFramework.
● TheCollectionsFrameworkisasophisticatedhierarchyofinterfacesandclassesthat
provide state-of-the-art technology(best possible technology) for managing groups of
objects.

● TheCollectioninJavaisaframeworkthatprovidesanarchitecturetostoreand
manipulate the group of objects.

● JavaCollectionscanachievealltheoperationsthatyouperformonadatasuchas
searching, sorting, insertion, manipulation, and deletion.
● JavaCollectionframeworkprovidesmanyinterfaces(Set,List,Queue,Deque)and
classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet,
TreeSet).
Interfaces&ClassesinCollectionFramework
CollectionsOverview
● TheJavaCollectionsFrameworkstandardizesthewayinwhichgroupsofobjectsare
handled by our programs.
● TheentireCollectionsFrameworkisbuiltuponasetofstandardinterfaces.

● Mechanismswereaddedthatallowtheintegrationofstandardarraysintothe
Collections Framework.
CollectionsOverview(contd.)
TheCollectionsFrameworkwasdesignedtomeetseveralgoals.
● – First, the framework had to be high-performance. The implementations for the
fundamentalcollections(dynamicarrays,linkedlists,trees,andhashtables)arehighly
efficient.
● –Second,theframeworkhadtoallowdifferenttypesofcollectionstoworkinasimilar manner
and with a high degree of interoperability.
● –Third,extendingand/oradaptingacollectionhadtobeeasy.
CollectionsOverview(contd.)
• Algorithmsareanimportantpartofthecollectionmechanism.
– AlgorithmsoperateoncollectionsandaredefinedasstaticmethodswithintheCollections
class.
– Thealgorithmsprovideastandardmeansofmanipulatingcollections.

• JavaCollectionsFrameworkprovidesalgorithmimplementationsthatarecommonlyused
such as sorting, searching etc.
– voidsort(Listlist)

– intbinarySearch(Listlist,Objectvalue)
CollectionsOverview(contd.)
● AnotheritemcloselyassociatedwiththeCollectionsFrameworkistheIterator
interface.
● –Aniteratoroffersageneral-purpose,standardizedwayofaccessingtheelements within
a collection, one at a time.
● –Aniteratorprovidesameansofenumeratingthecontentsofa collection.

● –BecauseeachcollectionimplementsIterator,theelementsofanycollectionclass can
be accessed through the methods defined by Iterator
CollectionsOverview(contd.)
• Theframeworkdefinesseveralmapinterfacesandclasses.
– Maps store key/value pairs.
• Amapcannotcontainduplicatekeys.

• AlthoughmapsarepartoftheCollectionsFramework,theyarenot“collections”inthe
strict use of the term
RecentChangestoCollections
CollectionsFrameworkunderwentafundamentalchangethatsignificantlyincreasedits power
and streamlined its use.
– Thechangeswerecausedbytheadditionof

• generics
• autoboxing/unboxing,and
• for-eachstyleforloop.
RecentChangestoCollections
Genericsaddtheonefeature:typesafety.
– Withgenerics,itispossibletoexplicitlystatethetypeofdatabeingstored,andrun-time type
mismatch errors can be avoided.
Autoboxing/unboxingfacilitatesthestoringofprimitivetypesincollections.

• INTHEPAST,ifwewantedtostoreaprimitivevalue,suchasanint,inacollection,we had to
manually box it into its type wrapper.
• Whenthevaluewasretrieved,itneededtobemanuallyunboxed(byusinganexplicit
cast) into its proper primitive type.
– Becauseofautoboxing/unboxing,Javacanautomaticallyperformtheproperboxingand
unboxing needed when storing or retrieving primitive types.

COLLECTIONFRAMEWORKINTERFACES
Collectioninterface
• Collectioninterfacehelpstoworkwithgroupofobjects
• TheCollectioninterfaceisatthetopofcollectionshierarchy.
• CollectioninterfaceisthefoundationuponwhichtheCollectionsFrameworkisbuilt –
because it must be implemented by any class that defines a collection.
• Collectionisagenericinterfacethathasthisdeclaration:interfaceCollection<E> –
Here, E specifies the type of objects that the collection will hold.
• CollectionextendstheIterableinterface.

– Thismeansthatallcollectionscanbecycledthroughbyuseofthefor-eachstyleforloop.
ollectioninterface
Collectioninterface
Collectioninterface(contd.)
• Wecancheckwhetheracollectioncontainsaspecificobjectbycallingcontains().
• Tocheckwhetheronecollectioncontainsallthemembersofanother,callcontainsAll().
• TodeterminewhetheracollectionisemptycallisEmpty().
• Thenumberofelementscurrentlyheldinacollectioncanbedeterminedbycallingsize().
• ThetoArray()methodsreturnanarraythatcontainstheelementsstoredintheinvoking
collection.
Object[]toArray()returnsanarrayof Object.

<T>T[]toArray(Tarray[])returnsanarrayofelementsthathavethesametypeasthe array
specified as a parameter.
Collectioninterface(contd.)
Twocollectionscanbecomparedwhethertheyareequalornotbycallingequals(). The
precise meaning of “equality” may differ from collection to collection.
– equals()canbeimplementedtocomparethevaluesofelementsstoredinthecollection.

– equals()canbeimplementedtocomparereferencestothoseelements.
The method iterator( ) returns an iterator to a collection.
– Iteratorshelptoloopthroughthecollections.
LISTINTERFACE
● TheListinterfaceextendsCollectioninterface.
● Listdeclaresthebehaviorofacollectionthatstoresasequenceofelements.
● –InJava,theListinterfaceisanorderedcollectionthatallowsustostoreandaccess elements
sequentially.
● Elementscanbeinsertedoraccessedbytheirpositioninthelist,usingzero-based index.
● Alistmaycontainduplicateelements.

● Listisagenericinterfacethathasthisdeclaration:
interface List<E>
ListInterface(contd.)
ListInterface(contd.)
• Listsupportsmethodsdefinedby Collection,
• Listdefinesitsownmethodsalso.
• Somemethodsthrowexceptions.
• ExceptionsthatarethrownbyListmethodsare:
MethodsinList Interface
MethodsinList Interface
• Listhasmanymethods:-add(int,E)andaddAll(int,Collection)
• Thesemethodsinsertelementsatthespecifiedindex.
• Themeaningofadd(E)andaddAll(Collection)definedbyCollectionarechangedbyList. In
List they add elements to the end of the list.
• Toobtaintheobjectstoredataspecificlocation,callget()withtheindexoftheobject.

• Toassignavaluetoanelementinthelist,callset(),specifyingtheindexoftheobjectto be
changed.
• Tofindtheindexofanobject,useindexOf()orlastIndexOf().

• AsublistofalistcanbeobtainedbycallingsubList(),specifyingthebeginningand ending
indexes of the sublist.
LISTINTERFACE
● ListinterfaceisthechildinterfaceofCollectioninterface.
● Itinhibitsalisttypedatastructureinwhichwecanstoretheorderedcollectionof objects.
● Itcanhaveduplicatevalues.

● ListinterfaceisimplementedbytheclassesArrayList,LinkedList,Vector,andStack.
● ToinstantiatetheListinterface,wemustuse:
● List<data-type>list1=newArrayList();
● List<data-type>list2=newLinkedList();
● List<data-type>list3=newVector();
● List<data-type>list4=newStack();
● TherearevariousmethodsinListinterfacethatcanbeusedtoinsert,delete,and access
the elements from the list.
● TheclassesthatimplementtheListinterfacearegivenbelow.
● [Link]
LISTINTERFACE
● TheArrayListclassmaintainstheinsertionorderandisnonsynchronized.
● [Link]
following example.
ArrayList
● JavaArrayListclassusesadynamicarrayforstoringthe elements.
● Itislikeanarray,[Link].
● So,[Link]
package. It is like the Vector in C++.
● [Link]
interface so we can use all the methods of List interface here.
● TheArrayListmaintainstheinsertionorderinternally.

● ItinheritstheAbstractListclassandimplementsListinterface.
ArrayList
TheimportantpointsaboutJavaArrayListclass are:
● JavaArrayListclasscancontainduplicateelements.
● JavaArrayListclassmaintainsinsertionorder.
● JavaArrayListclassisnonsynchronized.
● JavaArrayListallowsrandomaccessbecausearrayworksattheindex basis.
● InArrayList,manipulationislittlebitslowerthantheLinkedListinJavabecausealotof shifting
needs to occur if any element is removed from the array list.
ArrayListExample
IteratingArrayListusingIterator
TheCollectionClasses
• Thecollectionclassesimplementcollectio
ninterfaces.
• Someofthecollectionclassesprovidefull
implementations that can be used as-is.
• Some of the collection classes are abstract,
providing skeletal implementations that are used
asstartingpointsforcreatingconcretecollections.
• Collectionclassesarenotsynchronized.

– Twoormorethreadscanaccessthemethodsof
collection class at any time
TheCollectionClasses
ArrayListClass
• TheArrayListclassextendsAbstractListandimplementstheListinterface.
• ArrayListisagenericclassthathas declaration:
classArrayList<E>
– Here,Especifiesthetypeofobjectsthatthelistwill hold.
• ArrayListsupportsdynamicarraysthatcangrowasneeded.
– Thisisneededbecauseinsomecaseswemaynotknowhowlargeanarraywe need
precisely until run time.
• AnArrayListisavariable-lengtharrayofobjectreferences.

– SoArrayListcandynamicallyincreaseordecreaseinsize.
• Arraylistsarecreatedwithaninitialsize.
– Whenthissizeisexceeded,thecollectionisautomaticallyenlarged.
– Whenobjectsareremoved,thearraycanbeshrunk.
ArrayListClass
rrayListClass(contd.)
• ArrayListhasfollowingconstructors:
ArrayList()
Thisconstructorbuildsanemptyarraylist. ArrayList(Collection<?
extends E> c)
– Thisconstructorbuildsanarraylistthatisinitializedwiththeelementsofthecollectionc.
ArrayList(int capacity)
– Thisconstructorbuildsanarraylistthathasthespecifiedinitialcapacity.

– Thecapacityisthesizeoftheunderlyingarraythatisusedtostoretheelements.
– Thecapacitygrowsautomaticallyaselementsareaddedtoanarraylist.
ArrayListClass(contd.)
ArrayListClass(contd.)
• Thecontentsofacollectionaredisplayedusingthedefaultconversionprovidedby
toString( ), which was inherited fromAbstractCollection.
• WecanincreasethecapacityofanArrayListobjectmanuallybycallingensureCapacity().
void ensureCapacity(int cap)
• IfwewanttoreducethesizeofthearraythatofArrayListobjectsothatitispreciselyas large
as the number of items that it is currently holding, call trimToSize( ):
voidtrimToSize()
ObtaininganArrayfromanArrayList
• Toconvertacollectionintoanarray,toArray(),whichisdefinedbyCollectioncanbe
called.
– Thisisneeded

• Toobtainfasterprocessingtimesforcertainoperations
• Topassanarraytoamethodthatisnotoverloadedtoacceptacollection
• Tointegratecollection-basedcodewithlegacycodethatdoesnotunderstandcollections
• TwoversionsoftoArray()are:
Object[]toArray()
<T>T[]toArray(Tarray[])
ArrayListSample
AccessingCollectionsviaanIterator
• Tocyclethroughtheelementsinacollection([Link],sumofelements
etc.), we can use iterator, which is an object that implements either
– Iteratoror

– ListIterator
AccessingCollectionsviaanIterator
• Tocyclethroughtheelementsinacollection([Link],sumofelements
etc.), we can use iterator, which is an object that implements either
– Iteratoror

– ListIterator
• Iteratorenablesyouto
– cyclethroughacollection
– obtainingorremovingelements.
• ListIteratorextendsIteratortoallow
– bidirectionaltraversalofalist,
– themodificationofelements

IteratorandListIteratoraregenericinterfaceswhicharedeclaredas:
interface Iterator<E>
interfaceListIterator<E>

– Here,Especifiesthetype
AccessingCollectionsviaanIterator
AccessingCollectionsviaanIterator
AccessingCollectionsviaanIterator
Exceptionsinmethods
• ExceptionsintheMethodsDefinedby Iterator

– NoSuchElementException
– IllegalStateException
• ExceptionsintheMethodsDefinedby ListIterator
– NoSuchElementException
– IllegalStateException
– UnsupportedOperationException
UsinganIterator
• Eachofthecollectionclassesprovidesaniterator()methodthatreturnsaniteratortothe start
of the collection.
– Byusingthisiteratorobject,wecanaccesseachelementinthecollection,oneelement at a
time.
• Touseaniteratortocyclethroughthecontentsofacollection,

– [Link]’siterator()
method.
– [Link]().

• HavetheloopiterateaslongashasNext()returns true.
– [Link],obtaineachelementbycallingnext().
UsinganIterator
IteratorvsListiterator
TheFor-EachAlternativetoIterators
• Theforloopissubstantiallyshorterandsimplertousethantheiteratorbased approach.

• Butforloopcanonlybeusedtocyclethroughacollectionintheforwarddirection,andwe can’t
modify the contents of the collection.

• Ifwedon’twanttomodifythecontentsofacollectionorobtainingelementsinreverse
order, then the for-each version of the for loop is often a more convenient alternative to
cycling through a collection than is using an iterator.
TheFor-EachAlternativetoIterators
• Theforloopissubstantiallyshorterandsimplertousethantheiteratorbased approach.

• Butforloopcanonlybeusedtocyclethroughacollectionintheforwarddirection,andwe can’t
modify the contents of the collection.

• Ifwedon’twanttomodifythecontentsofacollectionorobtainingelementsinreverse
order, then the for-each version of the for loop is often a more convenient alternative to
cycling through a collection than is using an iterator.
Programtoremoveduplicates
EventHandling
FortheusertointeractwithaGUI,theunderlyingoperatingsystemmust support
event handling.
1) operatingsystemsconstantlymonitoreventssuchaskeystrokes,mouse
clicks, voice command, etc.
2) operatingsystemssortouttheseeventsandreportthemtotheappropriate
application programs
3) eachapplicationprogramthendecideswhattodoinresponsetotheseevents
• Thereareseveraltypesofevents,–Eventscanbegeneratedby
• themouse(click,move,dragmouseetc.)
• thekeyboard(type,press,releaseetc.)
• differentGUIcontrols,suchasa–pushbutton–scrollbar–checkbox
EventHandlingisthemechanismthatcontrolstheeventanddecideswhat should
happen if an event occurs.
WhatisanEvent?
● [Link] change
in state of source.
● Aneventisanobjectthatdescribesastatechangeinasource.
● Eventsaregeneratedasresultofuserinteractionwiththegraphicaluser
interface components.
● Itcanbegeneratedasaconsequenceofapersoninteractingwiththe
elements in a graphical user interface.
● Some of the activities that cause events to be generated are pressing a
button,enteringacharacterviathekeyboard,selectinganiteminalist,and clicking
the mouse.
TypesofEvent
ForegroundEvents-Thoseeventswhichrequirethedirectinteractionofuser. They are
generated as consequences of a person interacting with the GUI.
Forexample,clickingonabutton,movingthemouse,enteringacharacter through
keyboard,selecting an item from list, scrolling the page etc.

BackgroundEvents-Thoseeventsthatrequiretheinteractionofenduserare known as
background events.
Operatingsysteminterrupts,hardwareorsoftwarefailure,timerexpires,an operation
completion are the example of background events.
Eventhandling
● EventHandlingisthemechanismthatcontrolstheeventanddecideswhat
should happen if an event occurs.
● Thismechanismhavethecodewhichisknownaseventhandlerthatis
executed when an event occurs.
● Eventsaresupportedbyanumberofpackages,including
○ [Link],[Link],[Link]
● Eventhandlingisanintegralpartinthecreationofappletsandothertypes of
GUI-based programs.
● Appletsareevent-drivenprogramsthatuseaGUItointeractwiththeuser.
● Anyprogramthatusesagraphicaluserinterfaceiseventdriven.
● Thus,wecannotwritethesetypesofprogramswithoutasolidcommandof event
handling.
EventHandlingMechanisms
• Thetwowaysinwhicheventsarehandledchangedsignificantlybetweenthe
(Two event handling mechanisms)
– originalversionofJava(1.0)eventhandling and
– modernversionsofJava(beginningwithversion1.1)eventhandling
• The1.0methodofeventhandlingisstillsupported,butitisnotrecommended for
new [Link] per this Event was propagated up the containment hierarchy
until it was handled by a component.
– Manyofthemethodsthatsupporttheold1.0eventmodelhavebeen
deprecated.
• Themodernapproachisthewaythateventsshouldbehandledbyallnew
programs
TheDelegationEventModel
• The modern approach to handling
eventsisbasedonthedelegationeventmo
del
– Itdefinesstandardandconsistent
mechanisms to generate and
process events.

• Conceptofdelegationeventmodel:
– Asourcegeneratesaneventandsendsittooneormoreregisteredlisteners.
– Inthisscheme,thelistenersimplywaitsuntilitreceivesan event.
– Onceaneventisreceived,thelistenerprocessestheeventandthenreturns.
TheDelegationEventModel
TheadvantageofDelegationEventModelisthattheapplicationlogicthat processes
events is cleanly separated
fromtheuserinterfacelogicthatgeneratesthoseevents.
Auserinterfaceelementisableto“delegate”(entrust)theprocessingofanevent to a
separate piece of code.
Inthedelegationeventmodel,listenersmustregisterwithasourceinorderto receive an
event notification.
– Benefit:Notificationsaresentonlytolistenersthatwanttoreceivethem.
Inpreviousmodels,aneventwaspropagatedupthecontainmenthierarchyuntilit was
handled by a component.
– Thisrequiredcomponentstoreceiveeventsthattheydidnotprocess,andit
wasted valuable time. The delegation event model eliminates this overhead
TheDelegationEventModel
TheDelegationEventModel
TheDelegationEventModel-Event
• Inthedelegationmodel,aneventisanobjectthatdescribesastatechangeina
source.
• Eventscanbecausedwithorwithoutuserinteraction.
• Someeventsarecausedbyinteractionswithauserinterfacesuchas:
– pressingabutton,enteringacharacterviathekeyboard,
– selectinganiteminalist,clickingthemouse.
• Eventsmayalsooccurthatarenotdirectlycausedbyinteractionswithauser
interface.
– Example:aneventmaybegenerated
• whenatimerexpires,acounterexceedsa value,
• asoftwareorhardwarefailureoccurs,anoperationiscompleted
TheDelegationEventModel–EventSources
• Aeventsourceisanobjectthatgeneratesanevent.
– Eventoccurswhentheinternalstateofthatobjectchangesinsomeway.
• Sourcesmaygeneratemorethanonetypeofevent.
• Asourcemustregisterlisteners,thenonlylistenerscanreceivenotifications
about a specific type of event.
• Eachtypeofeventhasitsownregistrationmethod.
General form of listener registration is:
publicvoidaddTypeListener(TypeListenerel)
– Typeisthenameoftheevent,andelisareferencetotheeventlistener.
– Forexample,themethodthatregistersakeyboardevent
listener is called addKeyListener( ).
– Themethodthatregistersamousemotionlisteneriscalled
addMouseMotionListener().

TheDelegationEventModel–EventSources
• Aeventsourceisanobjectthatgeneratesanevent.
– Eventoccurswhentheinternalstateofthatobjectchangesinsomeway.
• Sourcesmaygeneratemorethanonetypeofevent.
• Asourcemustregisterlisteners,thenonlylistenerscanreceivenotifications
about a specific type of event.
• Eachtypeofeventhasitsownregistrationmethod.
General form of listener registration is:
publicvoidaddTypeListener(TypeListenerel)
– Typeisthenameoftheevent,andelisareferencetotheeventlistener.
– Forexample,themethodthatregistersakeyboardevent
listener is called addKeyListener( ).
– Themethodthatregistersamousemotionlisteneriscalled
addMouseMotionListener().

TheDelegationEventModel–EventSources(contd.)
• Whenaneventoccurs,allregisteredlistenersarenotifiedandreceiveacopyof the
event object. This is known as multicasting the event.
– Inallcases,notificationsaresentonlytolistenersthatregistertoreceive them.
• [Link]
method is this:
publicvoidaddTypeListener(TypeListenerel)[Link]
ption
– Whensuchaneventoccurs,[Link]
known as unicasting the event.
TheDelegationEventModel–EventSources(contd.)
Asourcemustalsoprovideamethodthatallowsalistenertounregisteraninterest in a
specific type of event. The general form of such a method is this:
publicvoidremoveTypeListener(TypeListenerel)
• Here,Typeisthenameoftheevent,andelisareferencetotheeventlistener.

– Forexample,toremoveakeyboardlistener,call
removeKeyListener( ).
• Themethodsthataddorremovelistenersareprovidedbythesourcethat
generates events.
– Forexample,theComponentclassprovidesmethodstoaddandremove
keyboard and mouse event listeners.

TheDelegationEventModel–EventListeners
● Alistenerisanobjectthatisnotifiedwhenaneventoccurs.
● Ithastwomajorrequirements.
● First,itmusthavebeenregisteredwithoneormoresourcestoreceive
notifications about specific types of events.
● Second,itmustimplementmethodstoreceiveand
● processthesenotifications
● Themethodsthatreceiveandprocesseventsaredefinedinasetofinterfaces found
in [Link].
● –Forexample,theMouseMotionListenerinterfacedefinestwomethodsto
receive notifications when the mouse is dragged or moved.
● Anyobjectmayreceiveandprocessoneorbothoftheseeventsifitprovides an
implementation of this interface.
TheDelegationEventModel
ComponentvsContainer
● InJava,acomponentisthebasicuserinterfaceobjectandisfoundinallJava
applications.
● ThemaindifferencebetweenthemisthataContainerisasubclassof
Component.
● Containercancontainothercomponentsand containers.

● Frame,PanelandAppletareexamplesofContainer
● Button,TextFieldetcareexamplesofComponent.
EventClasses
● Theclassesthatrepresentevents(Eventclasses)areatthecoreofJava’sevent
handling mechanism.
● ThemostwidelyusedeventsarethosedefinedbytheAWTandthosedefinedby

Swing.
● AttherootoftheJavaeventclasshierarchyisEventObject,whichisin [Link].
● –EventObjectisthesuperclassforallevents.
● –Itsoneconstructoris:EventObject(Objectsrc)
● –Here,srcistheobjectthatgeneratesthisevent
EventClasses(contd.)
● EventObjectcontainstwomethods:getSource(),toString().
● ThegetSource()methodreturnsthesourceofthe event.
● Itsgeneralformis:ObjectgetSource()
● -toString()returnsthestringequivalentoftheevent.

TheclassAWTEvent,[Link],isasubclassof
EventObject.

● –Itisthesuperclass(eitherdirectlyorindirectly)ofallAWT-basedeventsused by the
delegation event model.
● –ItsgetID()methodcanbeusedtodeterminethetypeoftheevent.

● –ThesignatureofgetID()methodisintgetID()
EventClasses(contd.)
EventClasses(contd.)
EventClasses(contd.)
TheActionEventClass
● AnActionEventisgeneratedwhen
● –abuttonispressed,
● –alistitemisdouble-clicked,
● –menuitemis selected.
● TheActionEventclassdefinesfourintegerconstantsthatcanbeusedto
identify any modifiers associated with an action event:
● –ALT_MASK

● –CTRL_MASK
● –META_MASK
● –SHIFT_MASK.
● IntegerconstantACTION_PERFORMED,canbeusedtoidentifyaction
events.
TheActionEventClass(contd.)
● ActionEventhasthesethreeconstructors:
● ActionEvent(Objectsrc,inttype,Stringcmd)
● ActionEvent(Objectsrc,inttype,Stringcmd,intmodifiers)
● ActionEvent(Objectsrc,inttype,Stringcmd,longwhen,intmodifiers)
● –Here,srcisareferencetotheobjectthatgeneratedthisevent.
● –Thetypeoftheeventisspecifiedbytype,anditscommandstringiscmd.
● –Theargumentmodifiersindicateswhichmodifierkeys(ALT,CTRL,META,
and/or SHIFT) were pressed when the event was generated.
● –Thewhenparameterspecifieswhentheevent occurred.

● ToobtainthecommandnamefortheinvokingActionEvent
● objectgetActionCommand()methodcanused:
● Forexample,whenabuttonispressed,anactioneventisgeneratedthathasa
command name equal to the label on that button.
TheActionEventClass(contd.)
● ThegetModifiers()method
● –returnsavaluethatindicateswhichmodifierkeys(ALT,CTRL,META,and/or
SHIFT) were pressed when the event was generated.
● Itsformis:intgetModifiers()

● ThemethodgetWhen() method
● –[Link]’s
timestamp. The getWhen( ) method is :
● longgetWhen()
TheAdjustmentEventClass
● AnAdjustmentEventisgeneratedbyascrollbar.
● Therearefivetypesofadjustmentevents.
● TheAdjustmentEventclassdefinesintegerconstantsthatcanbeusedtoidentify them.
TheAdjustmentEventClass
● ThegetAdjustable()methodreturnstheobjectthatgeneratedtheevent.
● Itsformis;AdjustablegetAdjustable()
● ThetypeoftheadjustmenteventmaybeobtainedbythegetAdjustmentType()
method.
● ItreturnsoneoftheconstantsdefinedbyAdjustmentEvent.

● Thegeneralformis:intgetAdjustmentType()
● TheamountoftheadjustmentcanbeobtainedfromthegetValue()methodis:
● intgetValue()
● –Forexample,whenascrollbarismanipulated,thismethodreturnsthevalue
represented by that change.
TheComponentEventClass
● AComponentEventisgeneratedwhenthesize,position,orvisibilityofa
component is changed.
● Therearefourtypesofcomponentevents.

● –TheComponentEventclassdefinesintegerconstantsfor this.
TheComponentEventClass(contd.)
● ComponentEventhastheconstructor:ComponentEvent(Componentsrc,inttype)
● –Here,srcisareferencetotheobjectthatgeneratedthisevent.
● Thetypeoftheeventisspecifiedbytype.
● ComponentEventisthesuperclasseitherdirectlyorindirectlyofContainerEvent,
FocusEvent, KeyEvent, MouseEvent, and WindowEvent.
● ThegetComponent()methodreturnsthecomponentthatgeneratedtheevent

● ComponentgetComponent()
TheContainerEventClass
● •AContainerEventisgeneratedwhenacomponentisaddedtoorremovedfroma
container.
● •Therearetwotypesofcontainer events.

● •TheContainerEventclassdefinesintconstantsthatcanbeusedtoidentifythem:
● –COMPONENT_ADDED
● –COMPONENT_REMOVED.
● ContainerEventisasubclassofComponentEvent.
● Constructor:ContainerEvent(Componentsrc,inttype,Componentcomp)
● –Here,srcisareferencetothecontainerthatgeneratedthisevent.
● Thetypeoftheeventisspecifiedbytype,andthecomponentthathasbeenadded to or
removed from the container is comp.
TheContainerEventClass
• AreferencetothecontainerthatgeneratedthiseventbyusingthegetContainer()
method.

ContainergetContainer()

• ThegetChild()methodreturnsareferencetothecomponentthatwasaddedtoor
removed from the container.

ComponentgetChild()
TheFocusEventClass
● •AFocusEventisgeneratedwhenacomponentgainsorlosesinputfocus.
● •Theseeventsareidentifiedbytheintegerconstants
● –FOCUS_GAINED
● –FOCUS_LOST.
● •FocusEventisasubclassofComponentEventandhastheseconstructors:
● FocusEvent(Componentsrc,inttype)
● FocusEvent(Componentsrc,inttype,booleantemporaryFlag)
● FocusEvent(Componentsrc,inttype,booleantemporaryFlag,Componentother)
● TheargumenttemporaryFlagissettotrueifthefocuseventistemporary.
● Otherwise,itissettofalse.
● Theothercomponentinvolvedinthefocuschange,calledtheoppositecomponent, is
passed in other.
TheFocusEventClass(contd.)
● Atemporaryfocuseventoccursasaresultofanotheruserinterface operation.
● –Forexample,[Link] to adjust
a scroll bar, the focus is temporarily lost.
● ifaFOCUS_GAINEDeventoccurred,otherwillrefertothecomponentthatlost focus.
● •Conversely,ifaFOCUS_LOSTeventoccurred,otherwillrefertothecomponent that
gains focus.
● •TodeterminetheothercomponentcallgetOppositeComponent():

● ComponentgetOppositeComponent()
● –Theoppositecomponentisreturned.
● •TheisTemporary()methodindicatesifthisfocuschangeistemporary.
● booleanisTemporary()
● –Themethodreturnstrueifthechangeistemporary.
● –Otherwise,it
TheInputEventClass
● TheabstractclassInputEventisasubclassofComponentEventandisthe
superclass for component input events.
● –ItssubclassesareKeyEventand MouseEvent.

● •InputEventdefinesseveralintegerconstantsthatrepresentanymodifiers,suchas the
control key being pressed.
● InputEventclassdefinedthefollowingeightvaluestorepresentthemodifiers:

● ALT_MASK
● •ALT_GRAPH_MASK
● •BUTTON1_MASK
● •BUTTON2_MASK
● •BUTTON3_MASK
● •CTRL_MASK
● •META_MASK
● •SHIFT_MASK
TheInputEventClass
● TheabstractclassInputEventisasubclassofComponentEventandisthe
superclass for component input events.
● –ItssubclassesareKeyEventand MouseEvent.

● •InputEventdefinesseveralintegerconstantsthatrepresentanymodifiers,suchas the
control key being pressed.
● InputEventclassdefinedthefollowingeightvaluestorepresentthemodifiers:

● ALT_MASK,ALT_GRAPH_MASK,BUTTON1_MASK,BUTTON2_MASK
● BUTTON3_MASK,CTRL_MASK,META_MASK,SHIFT_MASK
● Theextendedmodifiervaluestoavoidconflictbetweenkeyboardandmouseevent
modifiers are:
● •ALT_DOWN_MASK,•ALT_GRAPH_DOWN_MASK,•BUTTON1_DOWN_MASK
● •BUTTON2_DOWN_MASK,•BUTTON3_DOWN_MASK,•CTRL_MASK
● •META_DOWN_MASK,•SHIFT_DOWN_MASK
TheItemEventClass
● •AnItemEventisgenerated when
● –acheckboxoralistitemisclickedor
● –whenacheckablemenuitemisselectedordeselected.
● •Therearetwotypesofitemevents,whichareidentifiedbythefollowinginteger
constants:
● DESELECTED-Theuserdeselectedanitem.

● SELECTED-Theuserselectedanitem.
References
● HerbertSchildt,Java:TheCompleteReference,8/e,TataMcGrawHill,2011.

● [Link]

● [Link]

● [Link]

● JavaZone-[Link]

● [Link]

● [Link]

Disclaimer-Thisdocumentcontainsimages/[Link] respective
content creators. Document is compiled exclusively for study purpose and shall not be used for
.
commercialpurpose
OOPJ

JavaSwingisapartofJavaFoundationClasses(JFC)thatisusedto
createwindow-basedapplications.
ItisbuiltonthetopofAWT(AbstractWindowingToolkit)APIand entirely
written in java
JFC
• TheJavaFoundationClasses(JFC)areasetofGUIcomponentswhich
simplify the development of desktop applications.
 The [Link] package provides classes for java swing API such as
JButton, JTextField, JTextArea, JRadioButton, JCheckbox, JMenu,
JColorChooser etc.

SWINGFUNDAMENTALS
• JavaSwingisaGUIFrameworkthatcontainsasetofclassesto provide
more powerful and flexible GUI components than AWT.
• SwingprovidesthelookandfeelofmodernJavaGUI.
• SwinglibraryisanofficialJavaGUItoolkitreleasedbySun
Microsystems.
• ItisusedtocreategraphicaluserinterfacewithJava.
• [Link]- packages.
• Java Swing provides platform-independent and lightweight
components.

1
OOPJ

Plugging:
• It has a powerful component that can be extended to provide the
support for the user interface that helps in good look and feel to
the application.
• It refers to the highly modular-based architecture that allows it to
plug into other customized implementations and framework for
user interfaces.
Manageable: It is easy to manage and configure. Its mechanism and
composition pattern allows changing the settings at run time aswell.
The uniform changes can be provided to the user interface without
doing any changes to application code.

MVC:
• They mainly follows the concept of MVC that is Model View
Controller.
• With the help of this, we can do the changes in one component
without impacting or touching other components.
• Itisknownaslooselycoupledarchitectureaswell.
Customizable:
• Swing controls can be easily customized. It canbechanged andthe
visual appearance of the swing component application is
independent of its internal representation.
RichControls:
• SwingprovidesarichsetofadvancedcontrolslikeTree,
TabbedPane,slider,colorpicker,andtablecontrols.
6

2
OOPJ

 DifferencebetweenAWTandSwing

 HierarchyofJavaSwingclasses

3
OOPJ

TheModel-View-ControllerArchitecture
• Swing uses the model-view-controller architecture (MVC) as the
fundamental design behind each of its components
• Essentially,MVCbreaksGUI componentsintothreeelements. Each of
these elements plays a crucial role in how the component behaves.
• The Model-View-Controller is a well known software architectural
pattern ideal to implement user interfaces on computers by
dividing an application intro three interconnected parts

• Main goal of Model-View-Controller, also known as MVC, is to


separate internal representations of an application from the ways
information are presented to the user.
• Initially, MVC was designed for desktop GUI applications but it’s
quickly become an extremely popular pattern for designing web
applications too.
• MVCpatternhasthethreecomponents:
Modelthatmanagesdata,logicandrulesoftheapplication
View that is used to present data to user
Controller that accepts input from the user and converts it to
commands for the Model or View.

10

4
OOPJ

• theMVCpatterndefinestheinteractionsbetweenthesethreecompone
nts like you can see in the following figure :

11

• [Link] stores
these data and updates the View.
• TheViewletstopresentdataprovidedbytheModeltotheuser.
• TheControlleracceptsinputsfromtheuserandconvertsittocommands
for the Model or the View.

12

5
OOPJ

COMPONENTS&CONTAINERS
• A component is an independent visual control, such as a push
button or slider.
• A container holds a group of components. Thus, a container is a
special type of component that is designed to hold other
components.
• [Link],
which is the root of the Swing component hierarchy.

13

 COMPONENTS
• SwingcomponentsarederivedfromtheJComponentclass.
• JComponent provides the functionality that is common to all
components. For example, JComponent supports the pluggable
look and feel.
• JComponent inherits the AWT classes Container and Component.
Thus, a Swing component is built on and compatible with an AWT
component.
• All of Swing’s components are represented by classes defined
within the package [Link].
• ThefollowingtableshowstheclassnamesforSwingcomponents

14

6
OOPJ

• JApplet
• JColorChooser • JTogglebutton
• JDialog • JViewport
• JFrame • JButton
• JLayeredPane • JComboBox
• JMenuItem • JEditorPane
• JPopupMenu • JInternalFrame
• JRootPane • JList
• JSlider • JOptionPane
• JTable • JProgressBar

15

• NoticethatallcomponentclassesbeginwiththeletterJ.
• For example, the class for a label is JLabel; the class for a push
button is JButton; and the class for a scroll bar is JScrollBar
 CONTAINERS
• Swing defines two types of containers. The first are top-level
containers: JFrame, JApplet, JWindow, and JDialog. These
containers do not inherit JComponent. They inherit the AWT
classes Component and Container.
• The second type container are lightweight and the top-level
containers are heavyweight. This makes the top-level containers a
special case in the Swing component library.

16

7
OOPJ

InJava,Containersaredividedintotwotypesasshownbelow:

17

Followingisthelistofcommonlyusedcontainerswhiledesigned
GUIusingSWING.

18

8
OOPJ

SwingExample:Awindowonthescreen.

Output

19

EVENTHANDLINGINSWINGS
• The functionality of Event Handling is what is the further step if an
action performed.
• Javafoundationintroduced“DelegationEventModel”[Link]
how to generate and control the events.
• The key elements of the Delegation Event Model are as source and
listeners.
• Thelistenershouldhaveregisteredonsourceforthepurposeof alert
notifications.
• AllGUIapplicationsareevent-driven

20

10
OOPJ

 JavaSwingeventobject
• Whensomethinghappensintheapplication,aneventobjectis created.
• For example, when we click on the button or select an item from a
list.
• Thereareseveraltypesofevents,includingActionEvent,TextEvent,
FocusEvent, and ComponentEvent.
• Eachofthemiscreatedunderspecificconditions.
• An event object holds information about an event that has
occurred.

21

SWINGLAYOUTMANAGERS
• Layout refers to the arrangement of components within the
container.
• Layoutisplacingthecomponentsataparticularpositionwithinthe
container. The task of laying out the controls is done automatically
by the Layout Manager.
• The layout manager automatically positions all the components
within the container.
• Even if you do not use the layout manager, the components are
still positioned by the default layout manager. It is possible to lay
out the controls by hand, however, it becomes very difficult
22

11
OOPJ

• Java provides various layout managers to position the controls.


Properties like size, shape, and arrangement varies from one layout
manager to the other.
• Therearefollowingclassesthatrepresentsthelayoutmanagers:
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link]
[Link] etc.
23

BorderLayout GridLayout

24

12
OOPJ

FlowLayout BoxLayout

25

CardLayout GroupLayout

26

13
OOPJ

ExampleofJButton

27

ExampleofJTextField

28

14
OOPJ

ExampleofJlabel-Itisusedforplacingtextina box

29

15
OOPJ

MODULE 5

CHAPTER 2
JDBC

Java DataBase Connectivity (JDBC)


JDBC stands for Java Database Connectivity, which is a standard
Java API for database-independent connectivity between the Java
programming language and a wide range of databases.
The JDBC library includes APIs for each of the tasks mentioned
below that are commonly associated with database usage.
Making a connection to a database
Creating SQL or MySQL statements
Executing SQL or MySQL queries in the database
Viewing & Modifying the resulting records

1
OOPJ

JDBC Architecture
JDBC Architecture consists of two layers
JDBC API: This provides the application-to-JDBC Manager
connection.
JDBC Driver API: This supports the JDBC Manager-to-Driver
Connection.
The JDBC API uses a driver manager and database-specific drivers
to provide transparent connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to
access each data source.

Following is the architectural diagram, which shows the location of


the driver manager with respect to the JDBC drivers and the Java
application

2
OOPJ

Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the
database using JDBC. These steps are as follows:
Register the Driver class
Create connection
Create statement
Execute queries
Close connection

The forName() method is used to register the driver class.


The getConnection() method of DriverManager class is used to
establish connection with the database
The createStatement() method of Connection interface is used to
create statement. The object of statement is responsible to execute
queries with the database.
The executeQuery() method of Statement interface is used to
execute queries to the database. This method returns the object of
ResultSet that can be used to get all the records of a table.
By closing connection object statement and ResultSet will be
closed automatically. The close() method of Connection interface is
used to close the connection.
6

3
OOPJ

Java Database Connectivity with MySQL


To connect Java application with the MySQL database, we need to
follow 5 following steps.
In this example we are using MySql as the database. So we need to
know following informations for the mysql database:
Driver class: The driver class for the mysql database is
[Link].
Connection URL: The connection URL for the mysql database is
jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is
the database, localhost is the server name on which mysql is
running, we may also use IP address, 3306 is the port number
and sonoo is the database name. We may use any database, in
such case, we need to replace the sonoo with our database
name.
7

Username: The default username for the mysql database is root.


Password: It is the password given by the user at the time of
installing the mysql database. In this example, we are going to use
root as the password.
Let's first create a table in the mysql database, but before creating
table, we need to create database first.
create database sonoo;
use sonoo;
create table emp(id int(10),name varchar(40),age int(3));

4
OOPJ

Example to Connect Java Application with mysql database

This example will


fetch all the records of
emp table.

Creating a sample MySQL database


create database SampleDB;
use SampleDB;
CREATE TABLE `users` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) NOT NULL,
`password` varchar(45) NOT NULL,
`fullname` varchar(45) NOT NULL,
`email` varchar(45) NOT NULL,
PRIMARY KEY (`user_id`)
);
10

5
OOPJ

Connecting to the database


String dbURL = "jdbc:mysql://localhost:3306/sampledb";
String username = "root";
String password = "secret";
try {
Connection conn = [Link](dbURL, username,
password);
if (conn != null) {
[Link]("Connected");
}
} catch (SQLException ex)
{
[Link]();
}
11

• Once the connection was established, we have a Connection object


which can be used to create statements in order to execute SQL queries.
• In the above code, we have to close the connection explicitly after finish
working with the database:
[Link]();
INSERT Statement Example
Let’s write code to insert a new record into the table Users with
following details:
username: bill
password: secretpass
fullname: Bill Gates
email: [Link]@[Link]
12

6
OOPJ

String sql = "INSERT INTO Users (username, password, fullname,


email) VALUES (?, ?, ?, ?)";
PreparedStatement statement = [Link](sql);
[Link](1, "bill");
[Link](2, "secretpass");
[Link](3, "Bill Gates");
[Link](4, "[Link]@[Link]");
int rowsInserted = [Link]();
if (rowsInserted > 0) {
[Link]("A new user was inserted successfully!");
}
13

SELECT Statement Example

Output
User #1: bill - secretpass - Bill Gates - [Link]@[Link]
14

7
OOPJ

UPDATE Statement Example

15

DELETE Statement Example


The following code snippet will delete a record whose username
field contains “bill”

16

You might also like