0% found this document useful (0 votes)
311 views190 pages

U1 Java

This document provides an introduction to the Java programming language. It discusses Java's history and development. Key points include: - Java was created in the early 1990s by Sun Microsystems and was initially called Oak before being renamed Java. - Java is a platform-independent, object-oriented language that allows programs to run on any system with a Java Virtual Machine. - Major features of Java include being compiled and interpreted, portable, robust, secure, distributed, and high performance. - Java has different editions for developing standalone applications (J2SE), enterprise applications (J2EE), and mobile applications (J2ME).

Uploaded by

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

U1 Java

This document provides an introduction to the Java programming language. It discusses Java's history and development. Key points include: - Java was created in the early 1990s by Sun Microsystems and was initially called Oak before being renamed Java. - Java is a platform-independent, object-oriented language that allows programs to run on any system with a Java Virtual Machine. - Major features of Java include being compiled and interpreted, portable, robust, secure, distributed, and high performance. - Java has different editions for developing standalone applications (J2SE), enterprise applications (J2EE), and mobile applications (J2ME).

Uploaded by

venkat m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 190

Page no -1

C
Introduction to Java h
Topics
1. **Java Features.
a
2. **How Java is Differ from C and C++. pt
3. Java and Internet.
4. Java and WWW, Web Browsers.
er
5. Hardware and Software Requirements. -
6. Java Environment.
7. **JVM
1

What is Java?
Java is a “general purpose object oriented programming language” and high-level, robust, secure and
developed by “Sun Microsystems” of USA. It is a Platform.

Platform: - any hardware and software environment in which a program runs is known as a platform.
Since java has its own runtime environment i.e. JRE [Java Runtime Environment] and API [Application
program Interface] and it is called “Platform”.

History of Java

Java was designed for the development of software for consumer electronic devices like TVs, VCRs,
and such other electronic machines.

Some important milestones in the development of java are as follows;

Year Development
1990 Sun Microsystems decided to develop special software that could be used to manipulate
consumer electronic devices.

1991 After exploring the possibilities of using the most popular object- oriented language C++, the
team announced a new language named “Oak” (a tree name)

1992 The team formed to accomplish Oak language called as Green Team, and project is called as
Green Project by Sun Microsystems. And the team consist five members. The team leader is
James Gosling and members are Mike Sheridan, Patric Naughtier, Chrriswarth, and Ed Prank.

1993 The WWW gaining more popularity. The Green Project team came up with the idea of
developing Web applets (Tiny programs) for internet.

1994 The team developed a Web Browser called “Hot Java” to locate and run applet programs on
Internet.

1995 Oak was renamed as “Java”, due to legal snags. Because Oak is a national tree in many country
like USA, France, Germany, etc.. Java is not an acronym. Many popular companies including
Netscape and Microsoft announced their support to Java.

1996 Sun Microsystems releases Java Development Kit 1.1 (JDK 1.1)

Note: Java refers to Coffee Beans produced in the Indonesian Java Island. The symbol of java is tea cup
saucer.

The most striking feature of java is a Platform-Neutral. Java is the first programming language that is
not tied to any particular hardware or operating system. The programs developed in java can be
executed anywhere on any system.

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -2

Parts of Java (OR) JAVA released to the market in three categories:

1. J2SE (JAVA 2 Standard Edition)

J2SE deals with developing standalone applications and applications for network and also
exploring java library. J2SE is basically used for developing client side applications/programs.

2. J2EE (JAVA 2 Enterprise Edition)

J2EE deals with developing business solutions for a network or internet. J2EE is used for
developing server side applications/programs.

3. J2ME (JAVA 2 Micro/Mobile Edition)

J2ME deals with developing embedded systems and wireless applications. J2ME is used for
developing server side applications/programs.

Features or Buzzwords of JAVA


The inventors of java wanted to design a language which could offer solutions to some of the
problems encountered in modern programming. They wanted the language to be not only reliable,
portable and distributed but also simple, compact and interactive.

The following are the features of the JAVA language.

1. Compiled and Interpreted.


2. Platform Independent.
3. Portable.
4. Object Oriented.
5. Robust.
6. Secure.
7. Distributed.
8. Simple, Small and Familiar.
9. Multithreaded.
10. High Performance.
11. Dynamic and Extensible.
These are explained as follows;
1. Compiled and Interpreted:
Usually every computer language is either compiled or interpreted. Java combines both these
approaches thus Java is a two-stage system. First, Java compiler translates source code into what is
known as byte code instructions. Byte codes are not machine instructions.

In the second stage, the Java interpreter generates machine code from byte code that can be
directly executed by the system. Thus Java is both compiled and interpreted language.

2. Platform Independent:

A program (or) technology is said to be platform independent, because java is “Write once run
anywhere” and java can run on all available operating systems. The language JAVA will have a
common data types and the common memory spaces on all operating systems and the JAVA
software contains the special programs which converts the format of one operating system to
another format of other operating system. Hence JAVA language is treated as platform independent
language.

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -3

3. Portable:

The most benefit of java over other languages is its “portability”. Java programs can be easily
moved from one computer to another, anywhere and anytime.

A portable language is one which can run on all operating systems and on all processors irrespective
of their architectures and providers. The languages like C, C++ are treated as non-portable languages
whereas the language Java is called Portable language.

4. Object Oriented:

Java is a true object oriented language. Almost everything in Java is an object. Any programming
language that satisfies all the principles of OOP is called as an Object Oriented Programming
Language. The Java language satisfies all the principles of OOP. Hence it is called an Object Oriented
Programming Language. Java is a true object oriented language.

5. Robust:

Java is Roust programming language. It provides many safeguards to ensure reliable code. Robust is
nothing but it doesn’t allow to crash the system.

Note: Compile time errors are occurring when the programmer is not following syntax rules of the
programming language.

6. Secure:

Security becomes an important issue for a language that is used for programming on Internet. Java
is one of the most secured programming languages. Java also ensures that no viruses are
communicated with an applet. (The absence of pointers in Java ensures that programs cannot gain
access to memory locations without proper authorization.)

To provide the security to our java real time applications, we need not write our own security code.
Since java library (API) contains readily available security programs for protecting confidential
information from unauthorized users.
7. Distributed:

Java is designed as a distributed language for creating the applications on networks. It has the
ability to share both data and programs. Java programs can open and access remote objects on
Internet as easily as they can do in a local system.

8. Simple and Small:

Java is small and simple language. Many features of C and C++ that are either redundant or
unreliable code are not part of Java. For example, Java does not use pointers, pre-processor header
files, goto statement and many others. It also eliminates operator overloading and multiple
inheritance.

9. Multithreaded:

Multithreaded means “handling multiple tasks simultaneously”. Java supports multithreaded


programming. This means that we need not wait for the application to finish one task before
beginning to another task. For example, we can listen to an audio clip while scrolling a page and at
the same time download an applet from a remote computer.

10. High Performance:

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -4

Java is one of the High Performance programming languages because of the following reasons.

 Java architecture is also designed to reduce overheads during runtime.


 Automatic memory management (Garbage Collector).
 Magic of byte code (Execution of the java application is very faster compared to other
programming language applications).
11. Dynamic and Extensible:
Java is dynamic language. Java is capable of dynamically linking in new class libraries, methods, and
objects. Java programs support functions written in other languages such as C and C++. These
functions are known as native methods. Native methods are linked dynamically at runtime.

12. Architectural Neutral

A language (or) technology is said to be architectural neutral which can run on any available
processors in the real world. The languages like C, C++ are treated as architectural dependent.

The language Java can run on any of the processor irrespective of their architecture and vendor.

**Differences between Java and C


The major difference between Java and C is that Java is an Object Oriented Programming Language
whereas the C is a Procedure Oriented Programming Language.

The following are some of the C features those does not include in the Java

1) Java does not include the size of and typedef keywords.


2) Java does not define the type modifier keywords auto, extern, register, signed, and unsigned.
3) Java does not support an explicit pointer type.
4) Java does not have a pre-processor and then we cannot use #define, #include, and #ifdef
statements.
5) Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword.
6) Java adds new operators such as instance of and >>>
7) Java adds labeled break and continue statements.
8) Java adds many features required for object oriented programming.

**Differences between Java and C++


The major difference between the Java and C++ is that, Java is a pure object oriented programming
language whereas C++ is a partially object oriented programming language.

The following are some of the C features those does not include in the Java

1) Java does not support operator overloading.


2) Java does not have template classes as in C++.
3) Java does not support multiple inheritances of classes. This is accomplished using a new
feature called “interface”.
4) Java does not support global variables. Every variable and method is declared within a class
and forms part of that class.
5) Java does not use pointers.
6) Java has replaced the destructor functions with a finalize() method.

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -5

7) There are no header files in Java.

Fig. Overlapping of C, C++, and Java

Java and Internet


Java is strongly associated with the Internet because of the fact that the first application program
written in Java was Hot Java, a web browser to run applets on Internet. Internet users can use Java to
create the applet programs and run them locally by using a web browser. Internet users can also
download the applet from a remote computer as shown in below.

Fig: Downloading of applets via internet


Due to this, Java is popularly known as Internet Language.

Java and World Wide Web


World Wide Web (WWW) is an open-ended information retrieval system designed for internet
distributed environment. This system contains the web pages that provide both information and
control. In Web page we can navigate to a new document in any direction. Web pages contain HTML
documentation.

Before Java the WWW was limited to display the images and texts. However, the incorporation of
Java into Web pages made it capable of supporting animation, graphics, games, and a wide range of
special effects. Java communicates with a Web page through a special tag called <APPLET>.

The following are the steps that illustrate the communication steps.

The user sends a request for an HTML document to the remote computer`s Web server. The Web
server is a program that accepts a request, processes the request, and sends the requested
document.

The HTML document is returned to the user`s browser. The document contains the APPLET tag,
which identifies the applet.

The corresponding applet byte code is transferred to the user`s computer. This byte code had been
previously created by the Java compiler using the Java source code file for that applet.

The Java enabled browser on the user`s computer interprets the byte codes and provide output.

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -6

Fig. Java’s interaction with the web

Web Browsers:

Web browsers are used to navigate through the information found on the net. They allow us to
retrieve the information across the Internet and display it using the Hypertext Markup Language
(HTML). Examples for Web browsers are as follows.
 Hot Java
 Netscape Navigator
 Internet Explorer
These are explained as follows;
 Hot Java
Hot Java is the web browser form the Sun Microsystems. Hot java is written entirely in Java. When
the Java language was first developed and ported to the Internet, no browsers were available that
could run Java applets.
Hot Java is currently available Windows 95, Windows NT and Windows XP.
 Netscape Navigator
Netscape Navigator, from Netscape Communications Corporation, is a general-purpose browser
that can run Java applets.
Netscape Navigator has many useful features such as visual display about downloading process and
indication of the number of bytes downloaded.
 Internet Explorer
Internet Explorer is another popular browser developed by Microsoft for Windows 95, NT and XP
Workstations. Both the Navigator and Explorer use toolbars, icons, menus and dialog boxes for easy
navigation. Explorer uses a Just-In-Time (JIT) compiler which greatly increases the speed of
execution.

Java Environment:
Java Environment includes a large number of development tools and hundreds of classes and
methods. The development tools are part of the system known as Java Development Kit (JDK) and
the classes and methods are part of the Java Standard Library (JSL), also known as the Application
Programming Interface (API).
a) Java Development Kit (JDK)
The Java Development Kit comes with a collection of tools that are used for developing and
running Java programs. They include
 appletviewer: Enables us to run Java applets.
 javac (Java Compiler): The Java Compiler, which translates Java source code to bytecode files
that the interpreter can understand.
 java (Java Interpreter): Java Interpreter, which runs applets and applications by reading and
interpreting byte code files.
 javadoc (for creating HTML documents): Creates HTML- format documentation from Java

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -7

source code files.


 javah (for C header files): Produces header files for native methods.
 javap (Java disassemble): Which enables us to convert byte code files into a program
description.
 jdb ( Java debugger): Which helps us to find errors in our programs.

Fig. Process of building and running java application program


b) Application Programming Interface (API)
The Java Standard Library includes hundreds of classes and methods grouped into several
functional packages. Most commonly used packages are
 Language Support Package: A collection of classes and methods required for implementing basic
features of java.
Ex: java.lang.*
 Utility Package: A collection of classes to provide utility functions such as date and time
functions.
Ex: java.util.*
 Input/output Package: A collection of classes required for input/output manipulations.
Ex: java.io.*
 Networking Package: A collection of classes for communicating with other computers via
Internet.
Ex: java.net.*
 AWT Package: The Abstract Window Tool Kit package contains classes that implements platform
independent graphical user interface.
Ex: java.AWT.*
 Applet Package: This includes a set of classes that allows us to create Java applets.
Ex: java.applet.*

Java Runtime Environment:


The Java Runtime Environment (JRE) facilitates the execution of java programs. It primarily
comprises of the following:

1) Java Virtual Machine (JVM): It is a program that interprets the intermediate Java byte code and
generates the desired output.

2) Runtime Class Libraries: These are a set of core class libraries that are required for the execution
of java programs.

3) User Interface Tool Kit: AWT and Swing are example of toolkits that support varied input
methods for the users to interact with the application program.

4) Deployment Technologies: JRE comprises the following key deployment technologies.

I. Java plug-in: Enables the execution of a Java applet on the browser.

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -8

II. Java Web Start: Enables remote-deployment of an application. With Web Start, users
can launch an application directly from the Web browser without going through the
installation procedure.

***What is Java Virtual Machine(JVM) & its Architecture:


Java Virtual Machine (JVM) is the heart of the entire Java program execution process. It is
responsible for taking the .class and converting each byte code instruction into the machine
language instruction that can be executed by the microprocessor.

First of all, the .java program is converted into a .class consisting of byte code instructions by the
java compiler for a machine called Java Virtual Machine as shown in below. The JVM exists only
inside the computer memory.

The byte code is not a machine specific code (machine code). The machine code is generated by the

Java Interpreter by acting as an intermediary between the virtual machine and the real machine as
shown in below.

JVM Architecture:
Now in this JVM lession, let’s understand the Architecture of JVM. JVM architecture in Java contains
classloader, memory area, execution engine etc.

1) Class Loader

The class loader is a subsystem used for loading class files. It performs three major functions viz.
Loading, Linking, and Initialization.

2) Method Area

JVM Method Area stores class structures like metadata, the constant runtime pool, and the
code for methods.

3) Heap

All the Objects, their related instance variables, and arrays are stored in the heap. This memory
is common and shared across multiple threads.

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -9

4) JVM language Stacks

Java language Stacks store local variables, and its partial results. Each thread has its own JVM
stack, created simultaneously as the thread is created. A new frame is created whenever a
method is invoked, and it is deleted when method invocation process is complete.

5) PC Registers

PC register store the address of the Java virtual machine instruction which is currently executing.
In Java, each thread has its separate PC register.

6) Native Method Stacks

It contains all the native methods used in the application..

7) Execution Engine

It is a type of software used to test hardware, software, or complete systems. The test
execution engine never carries any information about the tested product.

8) Native Method interface

The Native Method Interface is a programming framework. It allows Java code which is running
in a JVM to call by libraries and native applications.

9) Native Method Libraries

Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the Execution
Engine.

C
h
2. Naming Conversion and Data_type a
p
Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science
t
r

–Page no -10

What is naming Conversion: 2

Java developers have followed some naming conventions.

 Names of all public methods and instance variables start with a leading lowercase letter.

Examples: average
total
 When more than one words are used in a name, the second and subsequent words are marked
with a leading uppercase letters.
Examples: firstDayOfMonth
totalMarks

 All private and local variables use only lowercase letters combined with underscores.

Examples: length
batch_strength
 All classes and interfaces start with a leading uppercase letter (and each) subsequent word with
a leading uppercase letter.

Examples: Student
HelloJava
 Variables that represent constant values use all uppercase letters and underscores between
words.
Examples: TOTAL
F_MAX
It should be remembered that all these are conventions and not rules. We may follow our own
conventions as long as we do not break the basic rules of naming identifiers.

Java Applications:
1. Stand- Alone applications

Stand-alone applications are programs written in java to carry out certain tasks on local
computer. In fact java can be used to develop programs for all kinds of applications, which earlier
were developed using languages like C and C++. Executing a stand-alone java program involves two
steps:

 Compiling source code into byte code using javac compiler.


 Executing the byte code program using java interpreter.
2. Web- Applications (Applets)
 Applets are small java programs developed for internet applications. An applet on a distant
computer (Server) can be downloaded via Internet and executed on local computer (Client)
using a java capable browser.

 We can develop applets for doing everything from simple animated graphics to complex games
and utilities.

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -11

 Since applets are embedded in an HTML documents and run inside a webpage, creating and
running applets are more complex than creating an application. An applet can only run within
a Web Browser.

Fig. Two ways of using java program

Q). Structure of a Java Program


To write a java program, we first define classes and then put them together. A Java program may
contain one or more sections as shown in below

.
Fig. Structure of Java Program

1. Documentation Section
The documentation section contains a set of comment lines giving the name of the program,
the author and other details. Comments must explain why and what classes and how of
algorithms.
Java provides a special type of comments they are multiline comments “/* ……. */” and single
line comments “//” these are called documentation comments. This form of comment is used
for generating documentation automatically.
2. Package Statement
The first statement allowed in a java file is a package statement. This statement declares a
package name and informs the compiler that the classes defined here belong to this package.
“The package statement is optional”.
Example: package student;
3. Import Statement
The next statement after a package statement may be a number of import statements. This is
similar to the #include statement in C language. Using import statements; we can have access
to classes that are part of other named packages.
Example: import java.lang.System; , import java.io.*;
This statement instructs the ‘interpreter’ to load the ‘System’ class contained in the ‘lang’
Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science
Page no -12

package under the ‘java’ main package.


4. Interface Statements
An interface statement is like a class but include a group of method declarations. This is also an
optional section and is used only when we wish to implement the multiple inheritance
features in the program.
5. Class Definitions
A Java program may contain multiple class definitions. Classes are the primary and essentials
of a Java program. These classes are used to map the objects of real-world problems. The
number of classes used depends on the complexity of the problem.
6. Main Method Class
Since every Java stand-alone program requires a main method as its starting point of the
program, this class is the important part of a java program. A simple java program may contain
only this part. The main method creates objects of various classes and establishes
communications between them. On reaching the end of main, the program terminates and the
control passes back to the operating system.
Simple Java Program
The following is a simple java program
//Sample.java
Package welcome;
Import java.io.*;
Class Sample
{
Public static void main (String args[])
{
System.out.println(“Welcome to Java Programming Language……”);
} //…….. End of main method
} //……. End of Sample class
The above simple java program contains the following.

The first three lines document section and package section and import section and the program
will starts from the class section these three sections are optional.

1. Class Declaration
The program starting fourth line
class Sample
Declares a class, which is an object oriented construct. Java is a true object-oriented programming
language and therefore, everything must be placed inside a class.
Class: - is a keyword used to declare a new class definition.
Sample: - is a java identifier that specifies the name of the class.
2. Opening Brace

Every class definition in java begins with an opening brace “{“and ends with a matching closing
brace“}”.

3. The Main Line


The sixth line
Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science
Page no -13

public static void main(String args[])


Defines a method named main. Every Java application program must include the main () method.
This is the starting point of the interpreter to begin the execution of the program. A Java program
can have any number of classes but only one of them must include a main method to initiate the
execution.
This line indicates a number of keywords, public, static and void

public The keyword public is an Access Specifier that declares the main method as
unprotected and therefore making it accessible to all other classes. This is similar
to the C++ public modifier.
static The keyword static declares this method as one that belongs to the entire class
and not a part of any objects of the class. The main must always be declared as
static since the interpreter uses this method before any objects are created.
void This keyword states that the main method does not return any value.

4. The Output line

The executable statement in this program is,


System.out.println(“ Welcome to Java Programming Language……”);
This is similar to the printf() statement in C. Since java is a true object oriented language, every
method must be a part of an object. The println() method is a member of out object, which is a
static data member of System class. This line prints the string
“Welcome to Java Programming Language…….” on the screen. The method println() always
append a new line character to the end of the string.
1. Write a java program to print a welcome message.

/*Java program to print a welcome note */


// Sample.java
import java.lang.*;
class Sample
{
public static void main(String args[])
{
System.out.println("Welcome to Java Programming Language……. ");
}
}

Output:
E:\WINDOWS\system 32\cmd.exe

C:\Java Programs> javac Sample.java


Welcome to Java Programming Language…..
C:\JavaPrograms>

Java Comments
There are three types of comments in java – single line, multi line, and Java documentation.

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -14

1. Single line Comment

These comments are for making a single line as a comment. These comments start with double slash
symbol (//) and after this, whatever is written till the end of the line is taken as a comment.
Example: // This is my comment of one line

2. Multi-line Comment

These comments are used for representing several lines as comments. These comments start with /*
and end with */. In between /* and */ , whatever is written is treated as a comment.
Example:

/* This is first line This is second line */


3. Java Documentation Comments

These comments start with /** and end with */. These comments are used to provide description
for every feature in a java program.

Q). Java Tokens


The smallest individual units in a program are called as tokens. The compiler recognizes them
for building up expressions and statements.
In simple terms, a java program is a collection of tokens, comments and white spaces. Java
language includes five types of tokens. They are
1. Reserved keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
These are explained as follows;
1. Reserved Keywords

Keywords are an essential part of a language definition and it is a special type of reserved words.
They implement the specific features of the language. The Java language has reserved 50 words
as keywords as shown in the below table.

Since the keywords have specific meaning in java, we cannot use them as names for variables,
classes, methods and so on. All keywords are to be written in lower-case letters.

Java Keywords

Abstract assert boolean break byte


Case catch char class const

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -15

continue default do double else


Enum extends final finally float
For goto if implements import
instanceof int interface long native
New package private protected public
Return short static strictfp super
Switch synchronized This throw throws
transient try Void volatile while

2. Identifiers

Identifiers are program designed tokens. They are used for naming the classes, methods,
variables, objects, labels, packages and interfaces in a program.

Java identifiers follow the following rules:

 They can have alphabets, digits and the underscore (_) and dollar ($) sign
characters.

 They must not begin with a digit.


 Uppercase and lowercase letters are distinct.
 They can be of any length.

Identifiers must be meaningful, short enough to be quickly typed and easily read. Java developers
have followed some naming conventions.
 Names of all instance variables and methods start with a leading lowercase letter. One or
more than one word is used in a name, the second and subsequent words are marked with a
leading uppercase letters.
Example: int average
float sum
float dayTempature shorttotalMarks
char firstDayOfMonth

Example: void average()


void sum()
void dayTemprature() inttotalMarks()
 All private and local variables use only lowercase letters combined with underscores.
Example: int length
int total_marks
 Variables that represent constant values use all uppercase letters and underscore between
words.
Example:

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no -16

TOTAL PI
PRINCIPAL_AMOUNT

Prepared By M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 17

3. Literals

Literals in java are a sequence of characters that represent constant values to be stored in
variables.
Java language specifies five major types of literals. They are
 Integer literals
 Floating point literals
 Character literals
 String literals
 Boolean literals
4. Operators
An operator is a symbol that takes one or more arguments and operates on them to
produce a result.

5. Separators

Separators are symbols used to indicate where groups of code are divided and arranged. They
basically define the shape and function of our code. The following are the list of separators and
their functions.
Name Its function
Parentheses ( () ) Used to enclose the parameters in method definition and invocation, also used
for defining precedence in expressions.

Braces ( { } ) Used to contain the values of automatically initialized arrays and to define a
block of code for classes, methods and local scopes

Brackets ( [ ] ) Used to declare array types and for dereferencing the array values.
Semicolon ( ; ) Used to separate the statements
Comma ( , ) Used to separate the consecutive elements in a variable declaration

Period ( . ) Used to separate package names from sub-packages and classes, also used to
separate a variable method from a reference variable.

Java Statements
The statements in java are like sentences in natural languages. A statement is an executable
combination of tokens ending with a semicolon (;) mark. Statements are usually executed in the
sequence in the order in which they appear.
The following diagram illustrates the types of java statements.

Fig: Classification of Java Statements

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 18

1. Expression Statements

Most statements are expression statements. Java has seven types of Expression statements.
 Assignment
 Pre-increment
 Pre-decrement
 Post-increment
 Post-decrement
 Method call
 Allocation expression
2. Labeled Statement

Any statement may begin with a label. Such labels must not be keywords. In java they are used
as the arguments of jump statements.
3. Control Statements

In java, it is possible to control the flow of execution. Java language provides three types of
control structures. Those are discussed below
a. Selection Statement
These select one of several control flows. There are three types of statements in java.
Those are if, if-else and switch
b. Iteration Statement

These specify how and when looping will take place. There are three types of iteration
statements in java. Those are while, do and for.
c. Jump Statement
Jump statements pass the control to the beginning or end of the current block, or to a
labeled statement. The four types of jump statements are break, continue, return and
throw.
4. Synchronization Statement

These are used for handling issues with multithreading.

5. Guarding Statement

Guarding statements are used for safe handling of code that may cause exceptions. These
statements use the keywords try, catch and finally.

Procedure for implementing a java program


Implementation of a Java application program involves a series of steps. They include

I.Create program

Consider the following program


//Test.java class Test
{

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 19

public static void main(String args[])


{
System.out.println(“Welcome to the world of Java…”);
}
}
Save this program using a file name Test.java. This file is called the source file. All the
java source files will have the extension .java.

II.Compile program

To compile the java program, we must use the java compiler javac along with the source file
name on the command line as shown in below.
C:/> javac Test.java
If everything is OK, then java compiler creates a .class file containing the byte code of the
program (Test.class).

II. Run programme


Fig: Compiling Java Program with different Interpreters

To run a stand-alone application we need to use the java interpreter on the command prompt
as shown in below.
C:/> java Test
Now, the interpreter looks for the main method in the program and begins execution from there.
When the program is executed the above program displays the output…
Hellow !
Welcome to the world of Java…

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 20

Constants, Variables and Data types


Constants (Identifier)
A constant is an identifier which takes a fixed value during the execution of the program. Java
supports several types of constants. Following diagram shows different constants.

Fig: Java Constants


Java has 4 types of constants are as follows;
1. Integer Constants
An integer refers to a sequence of digits. Integer constant is formed with integers including
zero, which can take positive and negative. There are three types of integers, namely,
decimal integer, octal integer and hexadecimal integer.

1) Decimal Integer: - consists of a set of digits, o through 9, preceded by an optional


minus sign.
Example: 123, -12, 0, 22

Spaces, commas, and non-digit characters are not permitted between digits.
Example: 1 5, 20.001, 1$0 are illegal numbers.
2) Octal Integer:- consists of any combination of digits from the set 0 through 7,
with a leading 0.

Example: 055, 0, 0345, 045556

3) Hexadecimal Integer:- A sequence of digits preceded by 0x or 0X is considered as


Hexadecimal Integer. They may also includes alphabets ‘A’ through ‘F’ (A—10,…..,F--
15).
We rarely use octal and hexadecimal numbers in programming.
2. Real Constants
A constant which is formed with real values including fractional part apart from integers is
called Real Constants.
Example: 12.5, -12.0, 3.14, 6.1

1) It is possible that the number may not have digits before the decimal point or digits
after the decimal point
Example: 215. .95 -.127
2) The real numbers are formed with two parts known as mantissa and exponent
where mantissa is either decimal (or) integer and exponent is an integer either
positive (or) negative

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 21

Example: 26.506 26.506e-2 -26.506e3

3) Exponential notation is useful for representing numbers that are either very
large or very small in magnitude.

For example 430000 may be written as 4.3e5 or 43e4. Similarly, -0.00000234 is equivalent
to -.e5234.
3.Character Constants
A Character constant is a single character i.e., enclosed within a pair of single quotes.

Example: ‘a’, ’8’, ’4’ , ’_’, ’c’

Every character is having integer values known as ASCII (American standard code for
information interchange) values.

4. String Constants

A group of characters combined within a pair of double quotes is known as string constants.
Example: “SURYA”, ” INDIA”, “3”, “+..*!”, “3+1”, “U”, “Standard Java”

Backslash Character Constants


Java supports some special backslash character constants that are used in output methods.
There are numerous backslash character constants each of them represents one character.
These characters combinations are known as Escape Sequences.
Consta Meaning
nt
‘ \b ’ Back space
‘ \f ’ Form feed
‘ \n ’ New line
‘ \r ’ Carriage return
‘ \t ’ Horizontal tab
‘ \’ ’ Single quote
‘ \“ ’ Double quote
‘ \\ ’ Backslash
Table: Backslash character constants
//Write a java program to illustrate about Backslash character constants in java
class Back
{
public static void main(String args[]) throws IOException
{
int a=1000;
System.out.println("welcome to java:" +'\b' +a);
System.out.println("welcome to java:" +'\f' +a);
System.out.println("welcome to java:" +'\n' +a);
System.out.println("welcome to java:" +'\r' +a);
System.out.println("welcome to java:" +'\t' +a);
System.out.println("welcome to java:" +'\'' +a + '\'');
System.out.println("welcome to java:" +'\"' +a + '\"');
System.out.println("welcome to java:" +'\\' +a + '\\');
}
}
Output:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 22

Variables
“A variable is a named memory location and identifiers that can store the value of the
program”. A Variable is an identifier this takes different values at different times during the
program execution. A variable name can be chosen by the programmer in a meaningful, shorter
form.
 average
 height
 total_height
 sum
Variable names may consist of alphabets, digits, the underscore ( _ ) and dollar character ( $ ).
While declaring the variable we should follow some precautions.
Rules for defining variables:
1) They must begin with a character including underscore(_).
2) They should not start with digits(0-9).
3) They can take any of length.
4) Keywords names are shooed not used in the variable names.
5) Upper case and lower case are distinct i.e., sum & SUM are not the same.

In java language a variable can be declared as follows;


Syntax: Data Type <variable name>;
Example:
 Byte roll_no;
 Short no;
 Int marks_1,total;
 Float average;
 Char x;
 Long area;
 Double volume;

Declaration of Variables
In java, the variables are the names of the storage locations. After designing the variable
name, we must declare them to the compiler. It tells three things.
1) It tells the compiler what the variable name is

2) It specifies what type of data the variable will hold.

3) Place of declaration statement decides the scope of the variable.

A variable must be declared before it is used in the program variable can be used to store a
value of any data type. That is, name has nothing to do with the type. Java allows any
properly formed variable to declared as a type.

The declaration statement defines the type of the variable. The general form of the declaration is

Syntax:- <data type name> <variable-name>

Ex:- int count;

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 23

Giving Values to Variables


A variable must be given a value after it has been declared. This can be achieved in two ways.
1) Assignment statement
2) Read statement
These are explained as follows;
1. Assignment statement:
The syntax for giving a value to the variable is as follows.
Syntax:- <variable name>=<value>

Ex: int x; x=10; (or) int x=10;

Data Types
Data types specify the size and type of values that can be stored. Java language supports
numerous data types. Every variable in java has a data type. Data types are used for
representing the data in main memory of the computer. The variety of data types are available
allow the programmer to select the type appropriate to the program.

Fig: Data types in java


Data Types are categories as Primitive types also called as built-in types and Derived types
are also called as Reference types (classes, Interfaces and Arrays). Primitive types are also
classified as Numeric (Integer and Floating point) and Non-Numeric (Character and Boolean).

Java has eight data types which are grouped in four groups. They are Integer category Data
types, Floating point category data types, Character category data types, Boolean category data
types.

1. Integer Category Types

Integer types can hold whole numbers such as 112, -234, and 566. They are used to
represent integer data. Java supports four types of integers. Java values are signed meaning
they can be positive or negative.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 24

The following table shows memory size and range of all integer types.

Data type Size Minimum Value Maximum Value  


Byte 1 byte -128 -2 7
127 (27-1)
Short 2 bytes -32,768 -215 32,767 (215-1)
Int 4 bytes -2,147,483,648 -231 2,147,483,647 (231-1)
long 8 bytes -9,223,372,036,854,770,000 -263 +9,223,372,036,854,775,807 (263-1)

It should be remembered that data types require more time for manipulation, and therefore
it is advisable to use smaller data types, whenever possible. This process will improve the
speed of execution of the program.

Whatever the data type we should not exceed the predefined value.

We can make integers long by appending the letter L or 1 at the end of the number.

Example: 123L or 1231

2. Float Category Types

Float category data types are used for representing the data in the form of scale, precision
i.e., these category data types are used for representing numbers with fractional part. There
are two types of floating point storage in java.
We must append f or F to float numbers.
Example: 1.23f (or) 1.23F456.67e3f

The following table shows memory size and range of all float types.

Data type Size Minimum Value Maximum Value

float 4 bytes 3.4 e-038 (231) 1.7 e+0.38 (231-1)

double 8 bytes 3.4 e-038 (263) 1.7 e+308 (263-1)


Whenever we take any decimal constant directly in a Java program it is by default treated as
highest data type in float category i.e., double.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 25

3. Character Category Types

A character is an identifier which is enclosed within single quotes. To represent character


data, java uses a data type called char. This data type takes two bytes since it follows
UNICODE character set.
char
.

C/CPP JAVA

1 byte 2 bytes

English 18 International languages

ASCII UNICODE
The following table shows memory size and range of all character type.

Data type Size Minimum Value Maximum Value


Char 2 -32768 (215) +32767 (215 -1)

UNICODE character set is one which contains all the characters which are available in 18
international languages and it contains 65536 characters.

4. Boolean Category Types

Boolean category data types is used for representing logical values i.e., TRUE or FALSE values.
To represent logical values we use a keyword called boolean. This data type takes one bit of
memory space.

Scope of Variables
Java variables are actually classified into three kinds.

1) Instance variables
2) Class variables
3) Local variables
1. Instance Variables:
Instance variables are declared and created when the objects are instantiated. They take
different values for each object.

2. Class Variables:

Class variables are those which are present within the class and belongs to entire set of
objects that class creates. Only one memory location created for each class variable.

3. Local Variables:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 26

Local variables are the variables that are present within the method. They are not available
outside of the method. These variables are visible within the method where it is defined.

We cannot declare a variable to have same name again. For example if you declare x variable
in one block is not repeated in another block within the same class (this is perfectly legal in
C and C++).

Symbolic Constants
A Numeric value is not always clear, to the sense that it means different things at different places.
For example 50 may mean number of students at one place, and the pass marks at the other
place.

Assignment of a symbolic name to such constants frees us from these problems. For example
we may use the name strength to denote the number of students. “pass-mark “to denote the
pass marks required in a subject.

A constant is declared as follows.

Final <data types> <symbolic-name> = value


Example: final int STRENGTH=50;

 Symbolic names take the same form as variable names. But they are generally
written in capitals to distinguish from the normal variable names.

 After declaration they should not be assigned any value.

 Ex: STRENTH=200; is illegal

 They should not be declared inside a method. They should be used only as class
data members in the beginning of the class.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 27

Operators and Expressions


1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Precedence of Arithmetic Operators
6. Operator Precedence and Associativity

Operators in Java
Java supports a rich set of operators. An Operator is a symbol that tells the computer to
perform certain mathematical or logical manipulations. Operators are used in programs to
manipulate data and variables.
Java Operators are classified into a number of related categories as shown in below.

1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Increment and Decrement Operators
6. Conditional Operators
7. Bitwise Operators
8. Special Operators

These are explained as follows:


1) Arithmetic Operators
Arithmetic operators are used to construct mathematical expressions as in algebra. Java
provides all the basic arithmetic operators. These can operate on any built-in numeric data
type of java.

Operator Meaning
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulo Division

Table: Arithmetic Operators

Arithmetic Operators are used as follows: a + b, a – b, a * b, a / b, a % b


Here a and b are may be variables (or) constants and are known as Operands.
// Java program on Arithmetic Operators
import java.lang.*;
class ArithOpe
{
public static void main(String args[])
{
float a=10.23F,b=.345F;
System.out.println ("Entered a value:"+a);
System.out.println ("Entered b value:"+b);

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 28

System.out.println ("a+b="+ (a+b));


System.out.println ("a-b="+ (a-b));
System.out.println ("a*b="+ (a*b));
System.out.println ("a/b="+ (a/b));
System.out.println ("a%b="+ (a%b));
}
}

Output:

2) Relational Operators
We often compare two quantities, and depending on their relation, take certain decisions.
These comparisons can be done with the help of relational operators. An expression
containing a relational operator is termed as a Relational Expression. The value of relational
expression is either TRUE or FALSE.
The list of operators as shown in below

Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
Table: Relational Operators
A simple relational expression contains only one relational operator and is of the following
form.
Syntax : exp1 rel_operator exp2
Example: 1 < 2
Here exp1 and exp2 are any two arithmetic expressions, which may be simple constants,
variables or combination of them. When arithmetic expressions are used on either side of a
relational operator, the arithmetic expressions will be evaluated first and then the results
compared. That is, arithmetic operators have a higher priority over relational operators.
Expression Value
3<2.5 FALSE
61< = 51 – 10 FALSE
-3> -22 TRUE
3 + 2 >= 6 FALSE
a + b == c + d TRUE **
4 * 2 != 7 TRUE
** Only if sum of values of a and b is equal to the sum of values of c and d.
The following program illustrates Relational Operators.
// Java program on Relational Operators
import java.lang.*;
class RealOpe
{
public static void main(String args[])
{
Int a=20, b=10;
System.out.println ("a =b " + (a==b));

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 29

System.out.println ("a >=b " + (a>=b));


}
}
Output:

3) Logical Operators

In addition to relational operators, java has three logical operators listed below in the table.

Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
The logical operators && and || are used when we want to form compound conditions by
combining two or more relations.
Example: a > b && b < c
An expression of this kind which combines two or more relational expressions is termed as a
Logical Expression or a Compound Relational Expression. Like the simple relational
expressions, a logical expression also yields a value of TRUE or FALSE, according to the truth
table AND and OR. Logical NOT operator is negate the result from true to false and vice
versa.
exp1 exp2 exp1 && exp2 exp1 || exp2
True True True True
True False False True
False True False True
False False False False
The following program illustrates Logical Operators.
// Java program on Logical Operators
import java.lang.*;
class LogicalOpe
{
public static void main(String args[])
{
int a=10, b=5, c=20;
System.out.println ("a<b && a<c is " + (a<b && a<c));
System.out.println ("a<b II a<c is " + (a<b II a<c));
System.out.println ("a<b ! a<c is " + (a<b ! a<c));
}
}
Output:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 30

4) Assignment Operators

Assignment Operators are used to assign the value of an expression to a variable. We have
seen the usual assignment operator, ‘=’. In addition to that java has a set of Shorthand
assignment operators which are used in the form
Var op= exp;
Where var is a variable, exp is an expression and op is a java binary operator. The operator
‘op=’ is known as
shorthand assignment operator. Assignment operators are +=, -=, *=, /=, ^=, %=.

Statement with simple Statement with shorthand


assignment operator operator
a=a+1 a += 1
a=a–1 a -= 1
a = a * (n + 1) a *= n+1
a = a / (n + 1) a /= n+1
a=a%b a %= b

Example - 1: a += 1;
When this statement is executed, 1 is added to a, if old value of a is 10, then new
value of x is 11. This actually means;
a = a + 1;
Example - 2: x += y+4;
This actually means, x = x + (y+4);
Some of the commonly used shorthand assignment operators are listed below.

There are three advantages using the shorthand operators, they are
o What appears on the left hand side need not be repeated and therefore it becomes
easier to write.
o The statement is more concise and easier to read.
o Use of shorthand operator’s result in a more efficient code.

5) Increment and Decrement Operators


Java has two very useful operators called the increment (++) and decrement (--) operators.
The operator ++ adds one to the operand while the operator – subtracts one. Both are unary
operators.
Example: ++a, a++, --a, a--.
 ++a is called as pre increment and a++ is called post increment.
 Though ++a and a++ mean the same thing when they form statements independently, they
behave differently when they are used in expressions on the right hand side of an
assignment statement.
 Example: a=5; b=++a; // first ++ adds 1 to ‘a’ and the result is added to b.
o Result of a=6, b=6; a=5;
• b=a++; first ‘a’ value is assigned to ‘b’ then ‘a’ value is incremented by 1.
o Result of a=6, b=5;
 A prefix operator first adds one to the operand and then the result is assigned to the variable
on left.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 31

// Java program on Increment Operators

import java.lang.*;
class IncOpe
{
public static void main(String args[])
{
int a=15, x;
// Pre increment
System.out.println ("Pre_Increment");
x = ++a;
System.out.println ("a = " + a);
System.out.println ("x = " + x);
System.out.println ();
// Post increment
System.out.println ("Post_Increment");
x= a++;
System.out.println ("x = " + x);
System.out.println ("a = " + a);
}
}

Output:

Decrement operator – follows same concept as Increment operators, but it is decremented by 1.


Pre and post Decrement is same as Increment.

6) Conditional Operator

The character pair ?: is a ternary operator available in java. This operator is used to
construct conditional expressions of the form

exp1 ? exp2 : exp3


Where exp1, exp2 and exp3 are all expressions.
Here first the expression exp1 was evaluated, if it is true, exp2 is evaluated. If it is false, exp3
is evaluated. However, it has to be clearly understood that among both exp2 and exp3, only
one of it is evaluated at any time.
Example:
a=10; b=15;
x=(a>b) ? a : b;
In this example, x will be assigned the value b.
// Java program on Biggest of two numbers by using ternary operator

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

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 32

{
int a=10, b=20, x;
System.out.println ("a = " + a);
System.out.println ("b = " + b);
System.out.println ();
x = (a>b)? a : b; // logic for biggest of two numbers
System.out.println ("Biggest of two numbers is " + x);
}
}

Output:

7) Bitwise Operators

Java has numerous bitwise operators for manipulation of data at bit levels. These operators
are used to testing the bits, or shifting them to the right or left. Bitwise operators may not be
applied to float or double.
Java supports the following operators:

a. Bitwise Logical Operators


Bitwise Logical Operators are binary operators and they require two integer-type operands,
these operators work on their operands bit by bit starting form least significant (i.e. the
rightmost) bit. Truth table for Bitwise Logical Operators:

Op-1 Op-1 Op-1 & Op-2 Op-1 | Op-2 Op-1 ^ Op-2

1 1 1 1 0

1 0 0 1 1

0 1 0 1 1

0 0 0 0 0

There are three Bitwise Logical Operators are as follows:

Bitwise AND ( & )


The Bitwise AND operator is represented by a single ampersand ( & ) and is
surrounded on both sides by integer expressions. The result of AND is 1 if both the
bits have a value of 1; otherwise it is 0.
Example: a= 10, b= 8
a = 0000 0000 0000 1010 --- 10
b = 0000 0000 0000 1000 --- 8

If we execute statement
c = a & b;
c = 0000 0000 0000 1000 --- 8

Bitwise operator often used to test whether a particular bit is 1 or 0.


Bitwise OR ( | )
The Bitwise OR operator is represented by vertical bar ( | ) and is surrounded on both

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 33

sides by integer expressions. The result of OR is 1 if at least one of the bit has a value
of 1; otherwise it is 0.
Example: a= 10, b= 8
If we execute statement
c = a | b;
c = 0000 0000 0000 1010 --- 10

Bitwise Exclusive OR ( ^ )
The Bitwise exclusive OR operator is represented by ( ^ ) symbol and is surrounded on
both sides by integer expressions. The result of exclusive OR is 0 if all of the bits has same
value i.e. both bits (0 , 0 or 1 ,1); otherwise it is 1.
Example: a= 10, b= 8
If we execute statement
c = a ^ b;
c = 0000 0000 0000 0010 --- 2
b. Bitwise Compliment Operator( ~ )
The compliment operator ( ~ ) also called the one’s compliment is an unary operator
and inverts all the bits represented by its operand. That is 0s become 1s and 1s
become as 0s.
Example -1: a = 10;
~ a = -11;
8) Special Operators
Java supports some special operators are as follows:
a. instanceof Operator
This operator is used to test if an object belongs to a class or not. The word instance
means an object. This operator can also be used to check if an object belongs to an
interface or not.
Example: Boolean x = emp instanceof Employee;
Here we are testing if emp is object of Employee class or not.
b. new new Operator
operator often used to create objects to classes. Objects are created on heap
memory by JVM, dynamically at runtime.
Syntax: class_name obj = new class_name();
Example: Employee emp = new Employee();
c.Member (Dot) Operator:
member operator is also called as dot operator since its symbol is a . (dot or period).

Arithmetic Expression
1. An Arithmetic expression is a combination of variables and operators arranged as per the
syntax of the language. Java can handle any complex mathematical expression.
2. Expressions are evaluated using an assignment statement of the form
variable=expression;
3. Variable is any valid java variable name. When the statement is encountered, the
expression is evaluated first and the result then replaces the previous value of the
variable on the left hand side.
Example:
x=a*b-c;

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 34

Precedence of Arithmetic Operators


An arithmetic expression without any parentheses will be evaluated from left to right using
the rules of precedence of operators. There are two distinct priority levels of arithmetic
operators in java.
High Priority * / %
Low Priority + -

The basic evaluation procedure includes two left to right passes through the expression.
During the first pass, the high priority operators are applied and during the second pass, the
low priority operators are applied. Consider the following evaluation statement
x= a – b / 3 + c * 2 -1
when a=9, b=12 and c=3, the statement becomes x= 9 – 12 /3 + 3 *2 -1 and is evaluated as
follows.
First pass
Step1: x=9-4+3*2-1 ………………..(12/3 evaluated)
Step2: x=9-4+6-1 …………………….(3*2 evaluated)
Second pass:
Step3: x=5+6-1 ……………………….(9-4 evaluated)
Step4:x=11-1 ………………………….(5+6 evaluated)
Step5: x=10 …………………………….(11-1 evaluated)

Operator precedence and Associativity


Each operator in java has a precedence associated with it. The Precedence is used to
determine how an expression involving more than one operator is evaluated. There are
different levels of precedence and an operator may belong to one of the levels. The
operators at the higher level of precedence are evaluated first.

The operators of the same precedence are evaluated either from left to right or from right to
left, depending on the level. This is known as the Associativity property of an operator.
The following table provides complex lists of operators, their precedence levels, and their
rules of association.

Operator Description Associativity Rank


. Member selection Left to Right 1
() Function call
[] Array element reference
- Unary minus Right to left 2
++ Increment
-- Decrement

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 35

! Logical negation
~ Ones complement
(type) Casting
* Multiplication Left to right 3
/ Division
% Modulus
+ Addition Left to right 4
- Subtraction
<< Left shift Left to right 5
>> Right shift
>>> Right shift with zero fill
< Less than Left to right 6
<= Less than or equal to
> Greater than
>= Greater than or equal to
instanceof Type comparison
== Equality Left to right 7
!= In equality
& Bitwise AND Left to right 8
^ Bitwise XOR Left to right 9
| Bitwise OR Left to right 10
&& Logical AND Left to right 11
|| Logical OR Left to right 12
?: Conditional Operator Right to left 13
= Assignment operator Right to left 14
op= Shorthand assignment

1. Consider the following conditional statement if(x==10 + 15 && y<10)


2. The precedence rules says that the addition operator has high priority than the logical
operator (&&) and the relational operators (== and <). Therefore, the addition of 10 and 15
is executed first.
3. This is equivalent to if (x==25 && y<10) Assume that x=20 and y=5, then X==25 is false
and y< 10 is true Finally we get, If(False && True)

4. Because one of the conditions is false, the compound condition is false.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 36

Decision Making and Branching - Decision Making and Looping


1. Two way Branching
2. Multi-way Branching
3. Conditional Operator
4. While Loop
5. Do-While Loop
6. For Loop
7. Enhanced For Loop
8. Labeled For Loop

Decision Making and Branching


A java program is a set of statements, which are normally executed sequentially in the order in
which they appear.

When a program breaks the sequential flow and jumps to another part of the code, it is called
Selection or Branching. When the branching is based on a particular condition, it is known as
conditional branching. If branching takes place without any condition, it is known as
Unconditional Branching.

Java language possesses such decision making capabilities and supports the following
statements known as Control or Decision Making Statements.

1. if statement
2. switch statement
3. Conditional operator statements

1) Decision Making with IF Statement

The if is a powerful decision making statement and is used to control the flow of execution of
statements. It is two – way decision statement (two – way branching statement). It allows the
computer to evaluate the expression (test condition) first and depending upon the value of
the test condition is ‘true’ or ‘false’, it transfers the control to the particular statement.

Fig: Two- Way Branching


If the condition is true then statement or set of statements of true is executed. Otherwise (if
the condition evaluates to false) it will come out of the block.

The if statement may be implemented in different forms depending on the complexity of


conditions to be tested.

1. Simple if statement
2. if-else statement

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 37

3. Nested if-else statement


4. else if ladder

1. Simple IF Statement

The syntax of the if statement is shown below


Syntax:
if(condition){  
//code to be executed  
}  
Where a Statement – block may consist of a single statement, a compound statement, or
nothing. If the test expression is true, the Statement – block is executed, otherwise
Statement – block will be skipped and the execution will jump to the Statement-x. When
condition is true both the Statement – block and the Statement-x are executed.
Flowchart:

Fig: Flow chart of simple if control

// Java program to check age for vote casting by using simple if statement

Example:

//Java Program to demonstate the use of if statement.  
public class IfExample 
{  
public static void main(String[] args) 
{  
  int age=20;   //checking the age  
     if(age>18)
{  
         System.out.print("Age is greater than 18");  
    }  
}  
}  

Output:

2. The IF-ELSE statement

The if…else statement is an extension of simple if statement. The syntax of the if-else
statement is the following:
Syntax:
if(condition)
{  
//code if condition is true  
}
Else

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 38

{  
//code if condition is false  

If the Test condition is true, then the True-block Statement(s) will be executed and then
Statement-x and so on (if any) executed in order. If the Test condition is false, False-block
Statement(s) will be executed and then Statement-x and so on (if any) executed in order. In
either case, only one of the statements True- block Statement(s) or False-block Statement(s)
is executed, but not both.
Flowchart:

Fig: Flow chart of if…else control


//A Java Program to demonstrate the use of if-else statement.  
//It is a program of odd and even number.  
public class IfElseExample 
{  
public static void main(String[] args) 
{  
    int number=13;  
    if(number%2==0)
{  
         System.out.println("even number");  
   }
Else
{  
       System.out.println("odd number");  
    }  

Output:

Nested IF-ELSE Statement

Once if consists another if condition called as Nested If. When a series of decisions are
involved, we may have to use more than one if statements in nested as follows.
Syntax:

if(condition){    
    //code to be executed    
    if(condition){  
  //code to be executed    
 }    
}

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 39

Flowchart:

Example:
//Java Program to demonstrate the use of Nested If Statement.  
public class JavaNestedIfExample 
{    
public static void main(String[] args) 
{    
    int age=20;  
    int weight=80;    //Creating two variables for age and weight  

    if(age>=18) //applying condition on age and weight  
{    
        if(weight>50){  
            System.out.println("You are eligible to donate blood");  
        }    
    }    
}}
Output:

3. ELSE IF ladder
A common programming construct in the java is the if-else-if ladder, which is often also called
the if- else-if staircase because of its appearance.
Syntax:
if(condition1){  
//code to be executed if condition1 is true  
}else if(condition2){  
//code to be executed if condition2 is true  
}  
else if(condition3){  
//code to be executed if condition3 is true  
}  
...  
else{  
//code to be executed if all the conditions are false  
}

This construct is known as the ELSE IF LADDER. The conditions are evaluated from the top of
the ladder. As soon as the true condition is found, the statement associated with it is
executed and the control is transferred to the statement-x (skipping the rest of the ladder).
When all the n conditions become false, then the final else containing the default-statement

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 40

will be executed.

Flow chart:

Example:
//Java Program to demonstrate the use of If else-if ladder.  
//It is a program of grading system for fail, D grade, C grade, B grade, A grade and A+.  

public class IfElseIfExample {  
public static void main(String[] args) {  
    int marks=65;  
      
    if(marks<50)
{  
        System.out.println("fail");  
    }  
    else if(marks>=50 && marks<60)
{  
        System.out.println("D grade");  
     }  
    else if(marks>=60 && marks<70)
{  
        System.out.println("C grade");  
     }  
    else if(marks>=70 && marks<80)
{  
        System.out.println("B grade");  
     }  
    else if(marks>=80 && marks<90)
{  
        System.out.println("A grade");  
     }
else if(marks>=90 && marks<100)
{  
        System.out.println("A+ grade");  
     }
Else
{  
        System.out.println("Invalid!");  
     }  
}  
}

Output:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 41

2).SWITCH Statement
Java provides a Multi-Way Branch decision statement known as switch. The switch statement
tests the value of a given variable (or expression) against a list of case values and when a
match is found, the block of statements associated with that case are executed.
Syntax:
switch(expression){    
case value1:    
  //code to be executed;    
 break;   //optional  
case value2:    
  //code to be executed;    
 break;   //optional  
......    
    
default:     
 code to be executed if all cases are not matched;    

The expression is an integer expression (or) characters. value-1, value-2,…are constants and
are known as case labels. Each of these values should be unique within a switch statement.
block-1, block-2,.. are statement lists and may contain zero or more statements. There is no
need to put braces around these blocks but it is important to note that case labels end with a
colon (:).

When the switch is executed, the value of the expression is successively compared against the
values value-1, value-2,… if match is found, then the block of statements that follows the case
are executed.

The break statement at the end of each block signals the end of a particular case and causes
an exit from the switch statement, transferring the control to the statement-x following the
switch.

The default is an optional case.

Flow chart:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 42

Example:
//Example Program to print days of the week using Switch statements?

class WeekDays
{
    public static void main(String s[])
    {
        int day = 2;
        
        switch(day)
        {
            case 1:
                System.out.println("Monday");
                break;
            case 2:
                System.out.println("Tuesday");
                break;
            case 3:
                System.out.println("Wednesday");
                break;
            case 4:
                System.out.println("Thursday");
                break;
            case 5:
                System.out.println("Friday");
                break;
case 6:
    System.out.println("Saturday");
     break;
case 7:
   System.out.println("Sunday");
   break;
default:
   System.out.println("Noweekday");
   break;
}
}
}
Output:

3). The ?: Operator


This operator is called ternary operator because it acts on 3 variables. The other name for this
operator is conditional operator, since it represents a conditional statement. Two symbols are
used for this operator ? And :

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 43

Syntax: variable = expression1 ? expression2 : expression 3

First the compiler evaluates the expression1 if it is true expression 2 will be executed by ignoring
the expression 3 i.e, expression 2 will become the resultant value for the entire expression. If the
expression 1 is false expression 3 will be executed by ignoring expression 2 i.e, expression 3 will
become the resultant value of the entire expression.

Example:

The program segment,


if ( x < 0)
result = 0;
else
result = 1;
Can be written as
result = (x < 0) ? 0 : 1;
Example: biggest of two numbers
big = (a>b) ? a : b;

/* Java Program to find biggest of two numbers by using conditional


operator*/
import java.lang.*;
import java.io.*;
class ConOpe
{
public static void main(String args[])
{
int a=10, b=25, c;
c = (a > b) ? a : b;
System.out.println(big+ " is Big Number");
}
}
Output:

Decision Making and Looping


The process of repeatedly executing a block of statements is known as looping. The statements in
the block may be executed any number of times, from zero to infinite number of times. If a loop
continues forever, it is called an infinite loop.

A Program loop consists of two segments, one known as control statement and other known as
body of the loop. The control statement tests certain condition and then directs the repeated
execution of the statements contained in the body of the loop.

Depending on the position of the control statement in the loop, a control structure may be
classified either as the Entry-Controlled Loop (or) Exit Controlled Loop.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 44

Fig: Loop Control Structure


In the Entry-Controlled Loop, the control conditions are tested before the start of the loop
execution. The body of the loop is executed till the test condition is true. If the conditions are
not satisfied, then the body of the loop will not be executed.

In Exit Controlled Loop, the test condition is performed at the end of the body of the loop and
therefore the body is executed unconditionally for the first time. The body of the loop is
executed till the test condition is true.

A Looping process includes the following steps:


 Initialization of variable.
 Execution of the statements in the body of the loop.
 Test for a specified condition for execution of the loop.
 Incrementing or decrementing the variable.
The Java Language provides three constructs for performing loop operations. They are

1. while construct
2. do construct
3. for construct
Now we are discussing features and applications of these looping statements.

1. WHILE Statement

The while is an Entry Controlled Loop statement. The test condition is evaluated and if the
condition is true, then the body of the loop is executed. After execution of the body, the test
condition is once again evaluated and if it is true, the body is executed once again. This process
is repeated until the test condition returns a false value and the control are transferred out of
the loop.
The body of the loop may have one or more statements. The braces are needed only if the body
contains two or more statements. It is good practice to use braces even if the body has only one
statement.
The basic format of the while statement is as follows;
Syntax:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 45

while(condition){  
//code to be executed  
}
Flow chart:

Consider the following code segment


int i;
while ( i <= 5)
{
System.out.println(i+” :welcome to while loop”);
i++;
}
The body of the loop executed 5 times from i=1,2,…5. Each time printing “i” value and “welcome
to while loop” then “i” value incremented inside the loop.
//Write a program to print numbers from 1 to 10 by using while Loop
import java.lang.*;
class While_Loop2
{
public static void main(String args[])
{
int i=1;
while(i<=10)
{
System.out.println(i);
i++;
}
System.out.println("loop repeated 10 times only");
}}

Output:

2. DO..WHILE Statement
On reaching the do statement, the program proceeds to execute the body of the loop first. At
the end of the loop, the test condition in the while statement is evaluated. If the condition is
true, the program continues to evaluate the body of the loop once again. This process
continues as long as the condition is true. When the condition is false, the loop will be
terminated.
Since the test condition is evaluated at the bottom of the loop, the do…while constructs
provides an Exit- Controlled Loop and therefore the body of the loop is always executed at
least once.
The following is the syntax for the do statement;
do{  
//code to be executed  
}while(condition);

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 46

Flow Chart:

Consider the following code segment Example.


public class DoWhileExample {  
public static void main(String[] args) {  
    int i=1;  
    do{  
        System.out.println(i);  
    i++;  
    }while(i<=10);  
}  
}  
Output:

The body of the loop executed first time and display “i” value and “welcome to while loop”
then “i”
value incremented inside the loop and checks while loop. do block executed 5 number of
times from i = 1…5.

Difference between while and do…while constructs

While Do…while
It is a looping construct that will It is a looping construct that will
execute execute at least once
only if the test condition is true. even if the test condition is false.
It is entry controlled loop. It is an exit controlled loop.
It is generally used for It is typically used for implementing
menu based
implementing common looping
programs where the menu is
situations.
required to be printed at least
once.

3. FOR Statement(LOOP)

The for loop is another entry controlled loop that provides a more concise loop control
structure. The general form of the loop is as follows.

A simple for loop is the same as C/C++. We can initialize the variable, check condition and
increment/decrement value. It consists of four parts:

1. Initialization:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 47

It is the initial condition which is executed once when the loop starts. Here, we can initialize
the variable, or we can use an already initialized variable. It is an optional condition.

2. Condition:

It is the second condition which is executed each time to test the condition of the loop. It
continues execution until the condition is false.

3. Statement:

The statement of the loop is executed each time until the second condition is false.

4. Increment/Decrement:

It increments (or) decrements the variable value. It is an optional condition.

Syntax:

for(initialization; condition; incr/decr)


{  
//statement or code to be executed  
}  
Flow Chart:

The execution of the for statement is as follows

 Initialization of the variable is done first, using assignment statements such as i=1 and
count=0. The variables i and count are known as loop-control variables.
 The value of the control variable is tested using the test condition. If the test condition is true,
the body of the loop is executed; otherwise the loop is terminated.
 When the body of the loop is executed, the control is transfer back to the for statement after
evaluating the last statement in the loop. Now, the control variable is incremented (or)
decrement.
Consider the following segment of a program
……………
……………
int x;
for(x=0; x<=9; x++)
{
System.out.println(x + “: Welcome to For loop”);
}
……………………..

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 48

This for loop is executed 10 times and prints the digits 0 to 9 and Welcome to For loop 10 times.

Comparison of the Three loops

FOR loop WHILE loop DO-WHILE loop


int i; int i; int i;
for(i=1; i<=10; i++) while(i <= 10) do
{ { {
System.out.println(i); System.out.println(i); System.out.println(i);
} i++; i++;
  } } while(i <= 10);

Additional Features of a for Loop

The for loop has several capabilities that are not found in other loop constructs. They are
1. More than one variable can be initialized at a time in the for statement. The statements
Sp=1;
for(n=0;n<10;n++)
Can be written as
for(p=1,n=0;n<10;n++)

Note that the initialization section has two parts p=1 and n=0 are separated by comma.

2. Like the initialization section, the increment section may also have more than one part. For
example
for(n=1,m=50 ; n<=m ; n++,m--)
3. The test condition may have any compound relation and the testing need not be limited only
to the control variable. Consider the following
sum=0;
for(i=1; i<20 && sum<100; i++)
{
………………
……………..
}
4. Another unique aspect of for loop is that one or more sections can be omitted, if necessary.
However the semicolons separating the sections must remain. Consider the following example

…………..
………….
m=5;
for( ; m!=100 ; )
{
System.out.println(m);
m=m+5;
}

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 49

………….
………….
5. We can also set up time delay loops using the null statement as follows;
for(j=10;j<=100;j++);
This loop is executed 90 times without producing any output; it simply causes a time delay.
Notice that the body of the loop contains only a semicolon, known as empty statement.

Java for-each Loop

The for-each loop is used to traverse array or collection in java. It is easier to use than simple for loop
because we don't need to increment value and use subscript notation.

It works on elements basis not index. It returns element one by one in the defined variable.

Syntax:

for(Type var:array){  
//code to be executed  
}  

Example:

//Java For-each loop example which prints the  
//elements of the array  
public class ForEachExample {  
public static void main(String[] args) {  
    //Declaring an array  
    int arr[]={12,23,44,56,78};  
    //Printing array using for-each loop  
    for(int i:arr){  
        System.out.println(i);  
    }  
}  
}  

Java Labeled For Loop

We can have a name of each Java for loop. To do so, we use label before the for loop. It is useful if
we have nested for loop so that we can break/continue specific for loop.

Usually, break and continue keywords breaks/continues the innermost for loop only.

Syntax:

labelname:  
for(initialization;condition;incr/decr){  
//code to be executed  
}  
Example:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 50

//A Java program to demonstrate the use of labeled for loop  
public class LabeledForExample {  
public static void main(String[] args) {  
    //Using Label for outer and for loop  
    aa:  
        for(int i=1;i<=3;i++){  
            bb:  
                for(int j=1;j<=3;j++){  
                    if(i==2&&j==2){  
                        break aa;  
                    }  
                    System.out.println(i+" "+j);  
                }  
        }  
}  
}  
Output:

Jumps in Loops
Java permits a jump from one statement to the end or beginning of a loop as well as a jump out
of a loop.

Jumping Out of loop (break statement)

When the break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop. When the loops are
nested, the break would only exit from the loop containing it. The break will exit only a single
loop.
The format of break statement is simply:
break;
This statement can also be used within while, do or for loops as illustrated below.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 51

Fig: Exiting a loop with break statement


// Java program by using break statement
class Break
{
public static void main(String args[])
{
for (int i=1;i<=10;i++)
{
if (i == 5)
break;// exit from the loop
System.out.println(i +" ");
}
}
}
Output:

Skipping a part of a Loop (continue statement)


Like the break statement java supports another similar statement called continue statement.
Whenever the continue statement is encountered within the loop, that causes the loop to be
continued with the next iteration after skipping any statements in the loop.

The continue statement tells the compiler “SKIP THE FOLLOWING STATEMENTS AND CONTINUE
WITH THE NEXT ITERATION”.
The format of continue statement is simply:
continue;

The use of the continue statement in loops is illustrated below.

//Java Program to demonstrate the use of continue statement  
//inside the for loop.  
public class ContinueExample {  
public static void main(String[] args) {  
    //for loop  
    for(int i=1;i<=10;i++){  
        if(i==5){  
            //using continue statement  
            continue;//it will skip the rest statement  
        }  
        System.out.println(i);  
    }  
}  
}  

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 52

Fig: Bypassing and continuing in loops


In while and do loops, continue causes the control to go directly to the test condition and
then to continue the iteration process. In case of for loop, the increment section of the loop is
executed before the test condition is evaluated.

Input and Output


1. Explain about stream?
A stream represents flow of data from one place to another place. It is like a water pipe
where water flows. Like a water-pipe carries water from one place to another, a stream
carries data from one place to another place. A stream can carry data from keyboard to
memory (or) from memory to printer (or) from memory to a file. A stream is always required if
we want to move data from one place to another.

All streams are represented by classes in java.io (input and output) package. This package
contains a lot of classes, all of which can be classified into two basic categories: input streams
and output streams.

Keyboard is represented by a field, called in System class. When we write System.in, we are
representing a standard input device, i.e., keyboard, by default. System class is found in
java.lang (language) package and has three fields as shown below. All these fields represent
some type of stream:

1. System.in:

This represents Input Stream object, which by default represents standard input device,
i.e., keyboard.

2. System.out:

This represents PrintStream object, which by default represents standard output device,
i.e., monitor.

3. System.err:

This field also represents PrintStream object, which by default represents monitor.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 53

2. What is the difference between System.out and System.err?


System.out and System.err both represent the monitor by default and hence can be used to
send data or results to the monitor.

But System.out is used to display normal messages and results whereas System.err is used to
display error messages.

3. Explain accepting input from the keyboard?


To accept data from the keyboard, i.e., System.in, we need to connect it to an input stream as
some input stream is needed to read data.

Figure shows the working in detail.

Reading Data from Keyboard

1. Connect the keyboard to an input stream object. Here, we can use InputStreamReader that
can read data from the keyboard.

InputStreamReader obj = new InputStreamReader (System. in);

In this statement, we are creating InputStreamReader object and connecting the Keyboard
(System. in) to it.

2.Connect InputStreamReader to Buffered Reader, which is another input type of stream. We


are using BufferReader as it has got methods to read data properly, coming from the stream.

BufferredReader br = new BufferedReader (obj);

Here, we are creating BufferedReader object (br) and connecting the InputStreamReader
object (obj) to it.

In the above two steps, can be combined and rewritten in a single statement as:

BufferedReader br =new BufferedReader(new InputStreamReader(System.in));

3. Now, we can read the data coming from the keyboard using read() and readLine() methods

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 54

available in BufferedReader class.

4. Write about Accepting a single character from the keyboard?


Accepting a Single character from the Keyboard: Now, follow the steps in order to accept a
single character from the keyboard.

1. Create a BufferedReader class object (br).


2. Then, read a single character from the keyboard using red() method as:
char ch= br.read();

Here, the read() method reads a single character from the keyboard but it returns its ASCII
number, which is an integer. Since, this integer number cannot be stored into character type
variable ch, we should convert it into char type by writing (char) before the method as:

char ch= (char)br.read();

Here, int data type is converted into char type.

Program: To accept and display a character from the keyboard

import java.io.*;
class Accept
{
public static void main(String args[]) throws IO Exception
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print(“Enter a character:”);
char ch= (char)br.read():
System.out.println(“You entered:” +ch);
}
}
Output:
Enter a character: A

You entered: A.

5. Write about Accepting a string from keyboard?


Accepting a String from Keyboard: Observe the statement, where readLine () method is called
using BufferedReader object (br);

String str= br.readLine();

Here, readLine() method accepts a string from the keyboard and returns the string into str. In
this case, casting is not needed since readLine() is taking a string and returning the same data
type. But this method can give rise to the runtime error: IOException, which can be thrown out
without handling by using the statement:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 55

throws IOException.

Program: Accepting a name (string) from the keyboard

import java.io.*;
class Accept
{
public static void main(String[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a name:");
String.name br.readLine();
System.out.println("You entered: "+name);
}
}
Output:
Enter a name: Rohith
You entered: Rohith

6. Write about Accepting an integer value from the keyboard?


Accepting an Integer value from the keyboard : Now, let us follow these steps to accept an
integer from the keyboard.

1. First, we should accept the integer number from the keyboard as a string, using readLine() as :

String str = br.readLine();

2. Now, the number is in str, i.e., in form of a string. This should be converted into an int by
using parseInt() method of Integer class as :

int n = Integer.parseInt(str);

If needed, the above two statements can be combined and written as:

int n = Integer.parseInt(br.readLine());

Here, parseInt() is a static method in Integer class, so it can be called using class name as
Integer.parseInt()

Program: Accepting an integer from keyboard.

import java.io.*;
class Accept
{
public static void main(String arg[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter an int value:");
int num= Integer.parseInt(br.readLine());
System.out.println("You entered: "+num);

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 56

}
}

Output:
Enter an int value: 457890 You entered: 457890

7. Explain how to Accepting a float value from keyboard?


Accepting a Float value from Keyboard : Just like an integer value, we can also accept a float
value in the following way:

float n Float.parseFloat(br.readLine());

In this statement, we are accepting a float in the form of a string using br.readLine() and then
passing the string to Float parseFloat() to convert it into float.parseFloat is a static method in
Float class.

Program: Accepting a float number.


import java.io.*;
class Accept
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader (System.in));
System.out.print("Enter a float value: ");
float n= Float.parseFloat(br.readLine());
System.out.println("You entered: "+n…
}

Output:

Enter a float value : 44.556


You entered: 44.556

9. Explain about Accepting other type of values from keyboard?

Accepting other types of values: Similarly, we can write different statements to accept many
other data types from the keyboard as follows:

1. To accept a byte value:

byte n = Byte.parseByte(br.readLine());

2. To accept a short value:

short n=Short.parseShort(br.readLine());

3. To accept a long value:

long n=Long.parseLong(br.readLine())

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 57

4. To accept a boolean value:

boolean n=boolean.parseBoolean(br.readLine())

9. Write about accepting different types of inputs in a line?


Accepting different types of inputs in a Line: We can use StringTokenizer class of
java.util(utility) package. StringTokenizer is useful to break a string into small pieces called
tokens. Let us follow these steps to understand how it is done.

1. First receive a string str from the keyboard, which contains different types of inputs.
Assume that the inputs are separated by commas.

String str = br.readLine();

2. Pass this string str to StringTokenizer object, so that it will be broken into pieces wherever a
comma is found. These tokens will be stored in StringTokenizer object st.

StringTokenizer st = new StringTokenizer(str, ", ");

In the above statement, str is the string which is split into tokens and which represents the
character from where to split the string. This comma is also called delimiter. Suppose we want
to split the string where a space is found, we can use a space as delimeter as:

StringTokenizer st = new StringTokenizer(str," ");

3. Collect the individual tokens from st using nextToken() method of StringTokenizer class.

String token = st.nextToken();

These individual tokens represent the different types of inputs given. These tokens can be
converted into corresponding data types and can be used in the program.

//Accepting different inputs in a line

import java.io.*;
import java.util.*;
class Different
{
public static void main(String args[])
{
String str= br.readLine();
StringTokenizer st = new StringTokenizer(str, ",");
String s1= st.nextToken();
String s2= st.nextToken();
s1=s1trim();
$2-$2.trim():
double n1 = Double.parseDouble(s1);
double n2 = Double.parseDouble(s2);
System.out.println("Result of additon:" + (n1+n2));
System.out.println("Result of subtraction: "+ (n1-n2));
System.out.println("Result of multiplication:" + (n1*n2));

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 58

System.out.println("Result of division: "+(n1/n2));


}
}

Output:

Enter two numbers: 20.5, 10


Result of addition : 30.5 Result of subtraction : 10.5
Result of multiplication: 205.0
Result of division: 2.05

10. Explain about scanner class in Java?


Reading Input with java.util.Scanner Class: We can use Scanner class of java.util package to
read input from the keyboard (or) a text file. When the Scanner class receives input, it breaks
the input into several pieces, called tokens. These tokens can be retrieved from the Scanner
object using the following methods.

Method Use
next() To read a string
nextByte() To read byte value
nextInt() To read integer balue
nextFloat() To read floating value
nextLong() To read long value
nextDouble() To read double value

To read input from keyboard, we can use Scanner class as:

Scanner sc= new Scanner(System.in);

Program: To read different types of data separated by space, from the keyboard using the Scanner
class.

//Scanner to scan the input from keyboard

import java.util.Scanner;
class Examplel
{
public static void main(String arg[])
{
System.out.print("Enter id name sal: ");
Scanner s=new Scanner(System.in);
int id=s.nextInt());
String name=s.next();
float sal= s.nextFloat();
System.out.println("Id="+ id);
System.out.println("Name="+ name);
System.out.println("Sal" + sal);

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 59

}
}

Output:

Enter id name sal : 10 Rohan 8900.50


Id=10
Name Rohan
sal=8900.5

11. How to display formatted output with string.format()


Displaying Formatted Output with String.format(): If we want only a string that consists of
formatted output, then we can take the help of format() method of String class. The format
characters supported by System.out.printf() are also usable with format() method. Since,
format() is a static method, we can call it as: String.format().

This method returns a string that contains the formatted output which can be processed and
used as the programmer wants it.

Program: Understanding format() method to obtain a string that consists of formatted .

Output:

class Example2
{
public static void main(String arg[])
{
int i=65;
String s ="Hai";
char ch = 'A':
String str=String.format("i-%d %ns=%s%nch=%c", i, s, ch);
System.out.println(str);
}
}

Output:

I=65
Hai
ch-A

12. Explain about System.out.printf()


Displaying Output with System.out.printf(): To format and display the output, printf() method is
available in PrintStream class. This method works similar to printf() function in C.

We know that System.out returns PrintStream class object, so to call the printf() method, we can
use: System.out.printf().

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 60

The following format characters can be used in printf();

Character Meaning
%s String
%c Char
%d Decimal integer
%f Float number
%o Octal number
%b, %B Boolean value
%x, %X Hexadecimal number
%e, %E Number is scientific notation
%n New line character

Program: To understand the use of printf(), let us write a Java program.

class Example3
{
public static void main(String arg[])
{
String s1="Hello";
int n=65;
float f=15.1234f;
System.out.printf("String=%s%n num=%d%n hexa decimal =%x%n float=%f", s1, n, n, f);
}
}

Output:
String=Hello
Num=65
hexa decimal=41
float=15.123400.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 61

Arrays
1. Arrays
2. Strings
3. Vectors
4. Wrapper Classes

Arrays Definition
“An array is a collection of contiguous (or) similar data items with same name and same data
type”.

For example we can define an array name regno to represent a set of register numbers of a
class. A particular value is indicated by writing a number called index number or subscript in
brackets after the array name.

All the elements in the array are of the same data type. Array elements are accessed
individually using the index. The index value starts with 0 (zero). An array can have one (or)
more dimensions. Arrays can be any variable type.

Note that an array always starts from its index values “0” to “n-1”. Suppose we want to
access fifth element from the above elements, then we have to use 4th index because 5th
element stored in 4th index. The no. of elements and types are identified by its subscripts.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 62

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

a[0]=10, a[1]=20, a[2]=30, a[3]=40, a[4]=50;

Array Types:
An array can be classified in two types in java.

1. One Dimensional array.

2. Two Dimensional array.

3. Multi or Three Dimensional array.

1. One Dimensional Array


The list of elements can be given to one variable name using only one subscript and such a
variable is called a Single-Dimensional/Subscripted Variable or a One-Dimensional Array.

A one dimensional (1 D) array represents a row (or) a column of elements.

Creating an array
Arrays must be declared and created in the computer memory before they are used.
Creation of an array involves three steps:
1) Declaring of an array.
2) Initialization of an array.
3) Accessing of an array.

1)Declaration of array
An array must be declared before they are used, so the computer can allocate space for
them in memory. The general syntax of one-dimensional array is.

Syntax-1: Syntax for declaring an array variable is:


type <array-name> [ ];
type [ ] <array-name>;

Here, type is data type of the array and array-name is any valid identifier.
Examples:
int marks[];
float []average;

After declaring an array, we need to create it in memory. Java allows us to create arrays using
new operator only.

Syntax for allocating memory for an array:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 63

<array-name> = new type [size];

Here, new – keyword used to allocate memory for the array, and size – number of elements
that the array would hold.

Examples:
marks = new int[5];

Now the variable marks refers to 5 integers values. We can combine both the steps
declaration and creation into a single one as shown below:
type <array-name> [ ] = new type [size];

Example:
int number [ ] = new int [5];

2)Initialization of an Arrays
Assigning the values to an array is known as Initialization. This is done using array subscript
because; every array element is accessed using its index number.

Syntax for initializing the array elements is:

<array-name>[index number] = value;

Example:
int marks[ ] = {10, 20, 30, 40};
marks [0]= 10;
marks [1]= 20;
marks [2} = 30;

 Note that array starts the subscript with 0 and ends with a value one less than the size
specified. i.e. 0 to ( n- 1)

 The following are valid statements:

 int n = marks [0] + marks [20];


 int m = n + marks [10];
 int marks [10] = a[7] + a[25] * 40;
 There is another way for initializing array elements automatically in the same way as ordinary
variables when they are declared as shown below:

Example:

int regno [ ] = {101, 102, 103, 104, 105};

3)Accessing elements of an Arrays

For accessing an individual element of an array, we use array subscript.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 64

Example:
//Java Program to illustrate how to declare, instantiate, initialize  
//and traverse the Java array.  

class Testarray{  
public static void main(String args[])
{  
int a[]=new int[5]; //declaration and instantiation  
a[0]=10; //initialization  
a[1]=20;  
a[2]=70;  
a[3]=40;  
a[4]=50;  
//traversing array  
for(int i=0;i<a.length;i++) //length is the property of array  
System.out.println(a[i]);  
}} 
Output:

Array Length
In java, all arrays store the allocated size in a variable named length. We can obtain the
length of the array using the length. This information will be useful in the manipulation of
arrays when their size is required.

Example:
int number[] = {10, 20, 30, 40, 50};
int n = number.length; //Here n value is 5

Two-Dimensional Array
An array use two subscripts of two index are called two dimensional array. A two dimensional
array represents several rows and columns of data. For example, the marks obtained by a group
of students in different subjects can be represented by a 2D array.
1)Declaration of 2D array
A two dimensional array is declared as shown below:

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

‘a’ is a two dimensional array which can hold 12 elements in 3 rows and 4 columns.

2)Initialization of an 2D Array
Initialization of two dimensional array elements is done using the index values:

int a[ ][ ] = {{1,2,3}, {4,5,6}, {7,8,9}};

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 65

a[0][0] = 1;
a[0][1] = 2;
a[1][0] = 3;
a[1][1] = 4;
The following diagram is a representation of a two-dimensional array in memory.

We can directly initialize the elements of a two dimensional array as shown below:

Alternative way of declaring a two dimensional array is:


int [ ] [ ] products = {
{34, 56, 78},
{12, 23, 34},
{10, 100, 1}
};
Here complier will create table array with 3 rows and 3 columns.

3)Accessing of an 2D Array

Example:
//Java Program to demonstrate the addition of two matrices in Java  
class Testarray5{  
public static void main(String args[])
{   //creating two matrices  
int a[][]={{1,3,4},{3,4,5}};  
int b[][]={{1,3,4},{3,4,5}};  
//creating another matrix to store the sum of two matrices  
int c[][]=new int[2][3];    //adding and printing addition of 2 matrices  

for(int i=0;i<2;i++){  
for(int j=0;j<3;j++){  
c[i][j]=a[i][j]+b[i][j];  
}
}
for(int i=0;i<2;i++){  
for(int j=0;j<3;j++){  
System.out.print(c[i][j]+" ");  
}  
System.out.println(); //new line  
}  

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 66

}}
Output:

Three Dimensional Array

Three dimensional array are also called space array. In this space rows and columns are
taken. Three dimensional array will required subscript i.e., three pairs of square brackets.
1. Declare 3D

Similar to 1D and 2D array must be declared before used. The declaration of 3D is


Arr name[][][]=new [size][size][size];

2. Initialization of 3D
You can initialize a three dimensional array in similar way like a two dimensional array.

Example:

int ar[2][3][4]={{{1,2,3,4},{5,6,7,8},{9,10,11,12}},{13,14,15,16},{17,18,19,20},{21,22,23,24}};

3. Accessing elements of the 3D:

3D contains array contains 3 subscripts, we will use three for loops to access the elements.

Example:

Class ThreeD
{
Public static void main(String args[])
{
int a[][][]= new int [2][2][2],I,j,k,m=1;
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
for (k=0;k<2;k++0
{
a[i][j][k]=m;
m++;
}
}
System.out.println(“3D is”);
for (i=0;i<2;i++)
{
for (j=0;j<2;j++)
{
for (k=0;k<2;k++0
{
System.out.println(a[i][j][k]+“ ”);
}
System.out.println();
}
System.out.println();

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 67

}
}
}
Output:

Command Line Argument:


Command line arguments are parameters that are supplied to the application program at the
time of invoking it for execution.

We can write Java programs that can received and use the arguments provided in the
command line. The signature of the main() method.

public static void main(String args[])

Here, args is declared as an array of strings (known as string objects). Any arguments provided
in the command line (at the time of execution) are passed to the array args as its elements. We
can simply access the array element and use them in the program as we wish.

For example consider the command line

java Test BASIC FORTRAN C++ Java

This command line contains Two arguments. These are assigned to the array args as follows:

BASIC →args [0]

FORTRAN→ args[1]

C++ →args[2]

Java → args[3]

Example Program for command line arguments :

class Sample
{
public static void main(String args[])
{
int i;
System.out.println ("command line arguments are ...");
for (i=0; i< args.length; i++)
{
System.out.println (args[i]);
}
}
}

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 68

Compile and Run the program with command line as follows: javac Sample .java

:java Sample c cpp java

The output of the program would be as follows

command line arguments are.....

cpp

java

UNIT-II, STRINGS
Q). What is a String? How to creating strings in java?

“A group of characters is called a string”. In C/C++ languages, a string represents an array of


characters, where the last character will be '\0'. But this is not valid in java. In Java a string is an
object of String class.

Creating strings: There are three ways to create strings in Java:

1. We can create a string just by assigning a group of characters to a string type variable:

String s; //declare String type variable

s="Hello"; //assign a group of characters to it

The two statements can be combined and written as:

String s="Hello";

2. We can create an object to String class by allocating memory using new operator. This is just
like creating an object to any class, like given here:
String s= new String("Hello");

Here, we are doing two things. First, we are creating object using new operator.

Then, we storing the string: "Hello" into the object.

3. The third way of creating the strings is by converting the character arrays into strings. Let us
take a character type array: arr[] with some characters, as :

char arr []= ('c', 'h', 'a', 'i', 'r', 's'};


Now create a string object, by passing the array name to it, as:

String s= new String(arr);

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 69

Now the String object 's' contains the string: "chairs". This means all the characters of the array
are copied into the string. If we do not want all the characters of the array into the string, then we
can also mention which characters we need, as:

String s= new String(arr, 2, 3);

Here, starting from 2nd character a total of 3 characters are copied into the strings.

Q). Immutability of strings:

Immutability of strings:

We can divide objects broadly as, mutable and immutable objects.

Mutable:- Mutable objects are those objects whose contents can be modified.

Immutable:- Immutable objects are those objects, once created cannot be modified.

And String class objects are immutable. Let us take a program to understand whether the String
objects are immutable or not.

Program: Write a program to test the immutability of strings.

class Test
{
public static void main(String arg[])
{
string s1="data";
string s2=new string("base");
s1=s1 + s2
System.out.println(s1);
}
}

Output:
C:> javac Test.java
C:\>java Test
Database

Q). String Methods (Methods of String class):

In java Strings are class objects and implemented using two classes, namely String and
StringBuffer. A java string is an instantiated object of the string class. A java string is not a
character array and not a NULL terminated. String may be declared and created as follows

Syntax:

String string_name= new String(“string”);


Example:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 70

String country= new String(“India”);

String Methods:

The String class defines a number of methods that allow us to accomplish a variety of string
manipulation tasks. Some most commonly used string methods.
Method Call Task Performed
s2 = s1.toLowerCase(); Converts the String s1 to all lowercase
s2 = s1.toUpperCase(); Converts the String s1 to all Uppercase
s2 = s1.replace(‘x’, ‘y’); Replace all appearances of x with y
s2 = s1.trim(); Remove white spaces at the beginning and
end of String s1
s1.equals(s2) Returns ‘true‘ if s1 is equal to s2
s1.equalsIgnoreCase(s2) Returns ‘true‘ if s1=s2, ignoring the case of
characters
s1.length() Gives the length of s1
s1.CharAt(n) Gives nth character of s1
s1.compareTo(s2) Returns negative value if s1<s2, positive value
if s1>s2, and
0 if s1 is equal s2
s1.compareToIgnoreCase(s2) Returns negative value if s1<s2, positive value
if s1>s2, and
0 if s1 is equal s2, ignoring the case of
characters
s1.concat(s2) Concatenates s1 and s2
s1.subString(n) Gives the substring starting from nth character
s1.subString(n, m) Gives the substring starting from n th character
up to m
(excluding m)
s1.startsWith(‘x’) Returns true if s1 starts with ‘x’
s1.endsWith(‘x’) Returns true if s1 ends with ‘x’

Write a Java Program illustrates the concept of String class methods


import java.lang.*;
class StringMethods
{
public static void main(String ar[])
{
String s1 = new String(" JAVA IS SECURE ");
String s2 = new String(" Java is robust");

System.out.println(s1);
System.out.println(s2);
System.out.println(s1.toLowerCase());
System.out.println(s1.toUpperCase());
System.out.println(s1.replace('I', 'i'));

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 71

System.out.println(s1.trim());
System.out.println(s1.equals(s2));
System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.length());
System.out.println(s1.charAt(3));
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareToIgnoreCase(s2));
System.out.println(s1.concat(s2));
System.out.println(s2.substring(4));
System.out.println(s2.substring(0,6));
System.out.println(s2.startsWith(" "));
System.out.println(s2.endsWith(" "));
}

Output:

StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.
Method Task
s1.setCharAt(n, ‘x‘) Modifies the nth character to x
s1.append(s2) Appends the string s2 to s1 at the end
s1.insert(n, s2) Inserts the string s2 at the position n of the string s1

// Java program on StringBuffer class methods


import java.lang.*;
class StringManipulation
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer(" JAVA");
System.out.println(s);
System.out.println(s.length());
System.out.println(s.append("DataStructures"));
System.out.println(s.insert(3, "v"));
System.out.println(s.reverse());
}
}
Output:

Java String compare

In java we can’t use (>,<,>=,<=) symbols for string comparison, We can compare String in Java on
the basis of content and reference. It is used in authentication.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 72

There are three ways to compare String in Java:

1. equals() Method
2. Using == Operator
3. compareTo() Method

1) equals() Method

The String class equals() method compares the original content of the string. It compares values of
string for equality. String class provides the following two methods:

 public boolean equals(Object another) compares this string to the specified object.


 public boolean equalsIgnoreCase(String another) compares this string to another string,
ignoring case.

Teststringcomparison1.java

class Teststringcomparison1
{  
 public static void main(String args[])
{  
   String s1="Virat";  
   String s2="Virat";  
   String s3=new String("Virat");  
   String s4="Kohli";  
   System.out.println(s1.equals(s2)); //true  
   System.out.println(s1.equals(s3)); //true  
   System.out.println(s1.equals(s4)); //false  
 }  
}  
In the above code, two strings are compared using equals() method of String class. And the
result is printed as boolean values, true or false.
2) == operator

The == operator compares references not values.

eststringcomparison3.java
class Teststringcomparison3
{  
 public static void main(String args[])
{  
   String s1="Virat";  
   String s2="Virat";  
   String s3=new String("Virat");  
   System.out.println(s1==s2); //true (because both refer to same instance)  
   System.out.println(s1==s3); //false(because s3 refers to instance )   
}  
}
3) compareTo() method

The String class compareTo() method compares values lexicographically and returns an
integer value that describes if first string is less than, equal to or greater than second string.

Suppose s1 and s2 are two String objects. If:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 73

 s1 == s2 : The method returns 0.


 s1 > s2 : The method returns a positive value.
 s1 < s2 : The method returns a negative value.

Teststringcomparison4.java

class Teststringcomparison4
{  
 public static void main(String args[])
{  
   String s1="Virat";  
   String s2="Virat";  
   String s3="Kohli";  
   System.out.println(s1.compareTo(s2)); //0  
   System.out.println(s1.compareTo(s3)); //1(because s1>s3)  
   System.out.println(s3.compareTo(s1)); //-1(because s3 < s1 )  
 }  
}  

Introduction to OOPs

Object-Oriented Programming

Definition:
Object-Oriented Programming is an approach that provides a way of modularizing programs
by creating partitioned memory area for both data and methods that can be used as
templates for creating copies of such modules on demand.

Object-Oriented Paradigm
The major objective of Object-Oriented approach is to eliminate some of the Drawbacks
encountered in the Procedural approach. OOP treats data as critical element in the program
development and does not allow the data to flow freely around the system. “It ties data more
closely to the methods that operate on it and protects it from accidental modification from
outside functions”.

The data of an object can be accessed only by the methods associated with the object. However
methods of one object can access the methods of other objects.

OOP allows us to decompose a problem into a number of entities called Objects. The
combination of data and methods make up an object.

Some of the features of Object-Oriented Paradigm are as follows:


 Emphasis is on data rather than procedure.
 Programs are divided into what are known as Objects.
 Data is hidden and cannot be accessed by external functions.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 74

 Objects may communicate with each other through methods.


 New data and methods can be easily added whenever necessary.
 Follows bottom-up approach in program design.

Fig. Organization of data and methods in OOP

OOP’s Principles (or) OOP’s Concepts


The data in the Object Oriented Programming language is secure. Examples of Object Oriented
Programming Languages are (LISP, ADA, ALGOL, SMALLTALK, OBJECT COBAL, OBJECT PASCAL,
CPP, JAVA, DOT NET, etc).
In order to say any language is an Object Oriented Programming Language it has to satisfy the
following principles of OOPs.

1. Object
2. Class
3. Data Abstraction and Data Encapsulation
4. Inheritance
5. Polymorphism
6. Dynamic Binding
7. Message Passing

1. Object
Objects are the real word entity (or) runtime entities in an object-oriented system. Objects are
closely matched with real world objects. Object may represent a person (or) a place, (or) table
of data (or) any item that can be handled by program. In order to store the data for the data
members of the class, we must create an object.

An object contains properties and actions.


Properties are represented by variables (data) memory location.
Actions are represented by methods.

Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 75

Definitions of an Object
 Instance of a class is known as an object.
 Class variable is known as an object.
 Real world entities are called as Objects.
The following figure is the representation of an object
Object: student
Data:
name;
regdno;

Methods:
marks();
total();
avg();
result();

Fig: Representation of an Object


While the program is running, the objects interact by sending messages to one another.

2. Class
“Collection of objects is called class”. It is a logical entity. A class is model for an object, and it is
a blue print of an object.
Once class has been defined, we can create any number of objects belongs to that class. Each
class is associated with data and methods.

For example mango, apple and banana are objects of fruit class. The syntax used to create
object is no different than the syntax used to create an integer object in C.
 If fruit has been defined as a class, then the statement
 fruit mango; // will create an object mango belonging to the class fruit.

Fig. Representation of class

Syntax for defining a class

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 76

Note: Any JAVA program can be developed with respect to Class only i.e., without Class there
is no JAVA program.

3. Data Abstraction and Data Encapsulation


Data Abstraction is a mechanism of representing essential features without including the
background details (or) explanations. It is a Technique of creating Abstract Data Type(ADT).

(Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, weight and cost, and methods that operate on these attributes)

Ex:- While driving a car, you don’t have to concern with its internal working details, here we
need to concern about the parts like Steering, wheels, accelerators, Breaks, etc.

Data Encapsulation
The wrapping up (Combining) of data and methods into a single unit is known as
Encapsulation. Encapsulation is the most important feature of a class.

The data is not accessible to the outside world, but this Encapsulation provides direct access to
data. By this direct access the program is called data hiding or information hiding.

Ex:- In a college a student cannot exist without a class.


4. Inheritance
Inheritance is the process by which one class objects acquire the properties of another class
objects. i.e. one child object acquire the properties of parent class object, it is also called
parent child relationship b/w two classes.
Inheritance supports the concept of hierarchical classification. The concept of inheritance
provides the idea of reusability. This means that we can add additional features to an existing
class without modifying it. This is possible by deriving a new class from the existing class.
The new class will have the combined features of both existing and new class. Inheritance
avoids the redundant code.

AKNU
COURSES

COLLEGE-2 COLLEGE-3
COLLEGE-1
COURSES COURSES
COURSES
Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science
Page no- 77

UG PG UG PG UG PG
COURSES COURSES COURSES COURSE COURSE COURSES
S S
Fig. Inheritance

5. Polymorphism
Polymorphism is another important OOP concept. Polymorphism, a Greek term, it means the
ability to take more than one form is called Polymorphism.
The word Polymorphism means combining the two words i.e Poly & Morphism, poly means
many, morphism means availability.

For example, an operation may exhibit different behavior in different instances. The behavior
depends upon the types of data used in the operation. It supports two concepts.

a. Operator Overloading:
The process of making an operator to exhibit different behaviors in different instances is
known as operator overloading i.e. a single operator can perform different operations.
Ex. If the operands are two numbers then the operator is sum i.e., 2 + 3= 5.
If the operands are strings then the operator is concatenation.
b. Function Overloading:
A single function name is used to perform different types of tasks is known as function
overloading. The following is an example for polymorphism concept.

Fig. Polymorphism
6. Dynamic Binding
Binding refers if the code is associated with class function, we can’t identify that until the code
has been executed in run time, it is also called Dynamic binding. It is associated with the
polymorphism and inheritance.

7. Message Passing

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 78

The OOP’s consists of a set of objects that communicate with each other. Objects
communicate with one to another by sending and receiving information.
Exchanging the data between multiple objects is known as Message Passing. Objects
communicate with one another by sending and receiving information much the same way as
people pass message to one another.

Q). Benefits of OOP


The following are the some of the benefits of Object Oriented Programming language
 Through Inheritance, we can eliminate redundant code and extend the use of existing
class.
 The data is designed in simple approach.
 OOPs provide easy understanding and clear module structure for programe.
 By using inheritance we can get the reusability.
 The principle of data hiding helps the programmer to build the secure programs.
 It is easy to partition the work in a project based on objects.
 Object oriented systems can be easily upgraded from small to large systems.
 Software complexity can be easily managed.
Disadvantages:-
 It require more data protection.
 Inadequate for concurrent problems.
 Inability to work existing system.
 Compile time and runtime overheads.
 Unfamilarized causes tracing overheads.
 Data and operations are separated.

Applications of OOP
OOPS applications are very important because of it is used in many areas like windows has
a more popular application in the OOPS. It is designed by interface with oops. The number of
windows systems developed by oops technique, like business system and commercial systems, etc
The following are some of areas of Object Oriented Programming
 Real-Time systems
 Simulation and modeling
 Object oriented databases
 Hypertext, hypermedia and expert text.
 Parallel programming.
 AI and expert systems.
 Designing supports
 Cam//Cad
 Neural networks and parallel programming.
 Decision support and office automation systems.

Difference Between Procedural and Object-Oriented Programming

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 79

Procedural-Oriented Programming Object-Oriented Programming


1. It is a procedural oriented 1. It is a object based programming
programming language. language.
2. It is known as POP 2. It is known as OOP.
3. Top-down approach. 3. Bottom-up approach.
4. Access modifiers are not 4. Access modifiers are supported.
supported.
5. Functions are preferred over data. 5. Security and accessibility is preferred.
6. Runs faster than OOP. 6. Runs slower the POP.
7. If size of the problem is small, POP 7. If the size of the problem is big, OOP
is preferred. is preferred.
8. In POP overloading is not possible 8. In OOP overloading is possible
9. POP does not have hiding 9. OOP has hiding security, so it is a
security, so it is less security highly secured

Q). What are the limitations of procedural programming?

The limitations of procedural programming are:

1. Procedural programming mainly focuses on procedures (or) functions. Less attention is given
to the data.
2. The data and functions are separate from each other.
3. Global data is freely moving and is shared among various functions. Thus, it becomes difficult
for programmers to identify and fix issues in a program that originate due to incorrect data
handling.
4. Changes in data types need to be carried out manually all over the program and in the
functions using the same data type.
5. Limited and difficult code reusability.
6. It does not model real-world entities (e.g., car, table, bank account, loan) very well where we
as a human being, perceive everything as an object.
7. The procedural programming approach does not work well for large and complex systems.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 80

Classes and Objects


1. Classes
2. Objects
3. Initializing the instance variables
4. Access specifier
5. Constructors

Classes, Objects

1. Defining a Class

“The process of binding the ‘data members’ and ‘member functions’ into a single unit is
called as a class”. In other words a class is a user defined data type. Once the class type has
been defined, we can create “variables” of that type. In java these variables are termed as
instances of class, which are the actual objects.
The basic form of a class definition is as follows;

class <sub_classname> [extends <super_classname>]


{

[fields declaration;]

[methods declaration]
}

Here, sub_classname and super_clsname are any valid java identifiers. The keyword extends
indicates that the properties of the super_classname class are extended to the sub_classname
class. This concept is called as Inheritance.
Everything inside the square brackets is optional. This means that the following would be a
valid class definition.
class <class-name>
{

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 81

Here, the body of the class is empty; this does not contain any properties and therefore cannot
do anything.

i). Field Declaration(Adding variables)


Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called Instance Variables because they are created whenever an object of
the class is Instantiated.

We can declare the instance variables exactly the same way as we declare the local variables.

Syntax:
type < variable1,…… >

Example:
class Rectangle
{
int length; // Instance variable declaration
int width; // Instance variable declaration
}

The class Rectangle contains two integer type instance variables (length, width). Here, these
variables are only declared and therefore no storage space has been created in the memory.
Instance variables are also known as Member Variables.

ii). Methods Declaration


A class with only data fields has no life. The objects created by no data field class cannot
respond to any messages. Methods are declared inside the body of the class but immediately
after the declaration of instance variables. The general form of a method declaration is as
follows.
type method_name( parameter_list)
{
Method-body;
}

Method declaration has four basic parts:


1. type:- defines the type of the value.
2. method_name:- defines the name of the method.
3. parameter_list:- defines the list of parameters.
4. Method-body:- defines the body of the method.

Let us consider a Rectangle class example as follows:


class Rectangle
{
int length, width;

void getData( int x, int y) // Method declaration


{

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 82

length=x;
width=y;
}

int rectArea() // Method Declaration


{
Int area=length*width;
return(area);
}
}
Here the getData method is declared to provide values to the instance variables.

(Note: In class we will have many numbers of variables and methods. Instance variables and methods in classes are accessible
by all the methods in the class but a method cannot access the variables declared in other methods.

Example:

class Check
{
int x;
void method1()
{
int y;
x=10; //legal
y=x; //legal
}
void method2()
{
int z;
x=20; //legal
z=10; //legal
y=5; //illegal
method1(); //legal
}
} )

OBJECT
1. Creating of an Object:
Object is a real word entity. “An instance of a class is called as an Object”. An object in java
is a block of memory that contains space to store all the member variables. Crating an
object is also referred to as Instantiating an object.

Objects in java are created using the new operator. The new operator creates an object for
the specified class and returns a reference to that object.
Here is an example of creating an object of type Rectangle.

Rectangle R1; //Declaring the object


R1 = new Rectangle(); // Instantiating the object

 The first statement declares a variable to hold the object reference(R1) and the second

Rectangle R1 = new Rectangle();


Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science
Page no- 83

one actually creates an object and assigns the object reference to the variable R1. The
variable R1 is now an object of the Rectangle class. Both statements can be combined
into one as shown below.

 The method Rectangle( ) is the Default Constructor of the class. We can create any
number of objects of Rectangle.
Example:

 Each object has its own copy of the instance variable of its class. This means if any changes in
variables of one object that cannot effect on the other variables.

 It is also possible to create two or more references to the same object as shown in below.

Rectangle R1 = new Rectangle ();


Rectangle R2 = R1;

Accessing Class Members


To access the instance variables and the methods from the outside of that class, we must use
the concerned object and the dot ( . ) operator as shown in below.

<object_name> . <variable_name> = value;


<object_name> . <method_name>(parameter_list);

1. Here, object_name is the name of the object and variable_name is the name of the
instance variable inside the object.

2. Method_name is the method that we wish to call.

3. parameter-list is separated by comma, and that must match in type and number with
the parameter list of the method name declared in the class.

1. First approach for accessing instance variables:

The instance variables of the Rectangle class may be accessed and assigned values as
follows:
R1.length = 10;

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 84

R1.width = 20;
R2.length = 30;
R2.width = 40;
Note that the two objects R1 and R2 store different values as shown below:

This is one way to assigning values to the variables in the objects.

2. Second approach for accessing Instance variables:

In our case getData() method can be used to do this. We can call this getData() method by
using objects R1/R2 as follows:
R1.getData(1,2); // calls getData method and pass values 1, 2 to parameters x, y of the method getData
R2.getData(10,20);//calls getData method and pass values 10, 20 to parameters x, y of the method getData

The following is the program that illustrates the concepts discussed so far.
import java.lang.*;
class Rectangle // Declaration of class
{
int len, wid; // Declaration of instance variables

void getData(int x, int y) //Declaration of method


{
Ien=x;
wid=y;
}

void rectArea() //Declaration of another method


{
int area;
area=len*wid;
System.out.println("Area from Method =" + area);
}
}

class RectArea // class with main method


{
public static void main(String args[])
{
int area1;
Rectangle r1=new Rectangle(); // Creating objects1
Rectangle r2=new Rectangle(); // Creating objects2
r1.len=15; //Accessing Variables
r1.wid=10;
area1=r1.len * r1.wid;
r2.getData(20,12); //Accessing methods
r2.rectArea();
System.out.println(area1);
}
}

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 85

Output:

Constructors in Java

A constructor in Java is similar to a method, which is invoked when an object of the class is
created. Unlike Java methods, a constructor has the same name as that of the class and does not
have any return type.
For example,

class Test //Class created


{
Test() //Constructor creating
{
// constructor body
}
}

Here, Test() is a constructor. It has the same name as that of the class and doesn't have a return
type.

 It is a special type of method which is used to initialize the object. Every time an object is
created using the new() keyword, at least one constructor is called.

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

The following program illustrates the concept of constructors in java.

Program To find the area of a rectangle.

class Main
{
private String name;

Main() // constructor
{
System.out.println("Constructor Called:");
name = "Programiz";
}

public static void main(String[] args)


{
Main obj = new Main(); // constructor is invoked, while creating an object of the Main class
System.out.println("The name is " + obj.name);
}

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 86

Output:
Constructor Called:
The name is Programiz

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor
1. Java Default Constructor

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

Syntax of default constructor:

<class_name>
()
{

}  

Example of default constructor

In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.

//Java Program to create and call a default constructor  
class Bike
{  
Bike() //creating a default constructor  
{
System.out.println("Bike is created");
}  

public static void main(String args[]) //main method  
{  
Bike1 b=new Bike1();   //calling a default constructor  
}  
}  

2. Java Parameterized Constructor

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 87

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


Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects. However,
you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.  
class Main
{
String lang;

Main(String language) // constructor accepting single value


{
lang =language
System.out.println(lang);
}

public static void main(String[] args)


{
Main obj1 = new Main("Java"); // call constructor by passing a single value
Main obj2 = new Main("Python");
Main obj3 = new Main("C");
}
}

Q). Constructor Overloading in Java

In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.

1) Constructor overloading in Java is a technique.


2) It’s having more than one constructor with different parameter lists.

3) They are arranged in a way that each constructor performs a different task.

4) They are differentiated by the compiler by the number of parameters in the list and
their types.

Example of Constructor Overloading


//Java program to overload constructors  
class Student
{  
    int id;  
    String name;  
    int age;  

    Student(int i, String s)      //creating two arg constructor  


{  
   id = i;  

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 88

     name = s;  
     }  
    Student(int i, String s, int a) //creating three arg constructor  
{  
     id = i;  
     name = s;  
     age=a;  
     }  
    void display()
{
System.out.println(id+" "+name+" "+age);
}  
   
    public static void main(String args[])
{  
     Student s1 = new Student(111,"Karan");  
     Student s2 = new Student5(222,"Aryan",25);  
     s1.display();  
     s2.display();  
    }  

Q).How to initializing the instance variables?


It is the duty of the programmer to initialize the instance variables, depending on his
requirements.

Examplel: A program to initialize the Person class instance variables in Demo class.
//Initializing the instance variables
class Person
{
public String name; //public Instance variable

int age ; //Default instance variable

void disp()
{
System.out.println("Hello lam " + name);
System.out.println("My age is " + age);
}

public static void main(String args[])


{
Person P = new Person();
P.name="Raju";
P.age=5;
P.disp();
}
}

Output:
Hello lam Raju
My age is 5

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 89

Q). Access Specifier (or)Modifiers in Java

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

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

There are four types of Java access modifiers:

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

Q). Difference between constructor and method in Java:

There are many differences between constructors and methods. They are given below.

Java Constructor Java Method


1.A constructor is used to initialize the 1. A method is used to expose the behavior of an
state of an object. object.
2.A constructor must not have a return 2. A method must have a return type.
type.
3.The constructor is invoked implicitly. 3. The method is invoked explicitly.
4.The Java compiler provides a default 4. The method is not provided by the compiler in
constructor if you don't have any any case.
constructor in a class.
5.The constructor name must be same as 5. The method name may or may not be same as
the class name. the class name.

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 90

Methods in JAVA

Explain about methods in Java?


A method is a block of code (or) collection of statements (or) a set of code grouped together to
perform a certain task (or) operation. It is used to achieve the reusability of code. “We write a
method once and use it many times”. We do not require to write code again and again.

Methods must be declared inside the body of the class but immediately after the declaration of
instance variables.

Declaration:

type method_name (parameter_list)


{
method body
}

A method has two parts


1. Method header (or) method prototype
2. Method body

1. Method header (or) method prototype:


It contains method name, method parameters and method return data type. Method prototype
is written in the form:

return_datatype method_name(parameter 1, parameter 2,...)

Here, method name represents the name given to the method. After the method name, we
write some variables in the simple braces. These variables are called parameters. Method
parameters are useful to receive data from outside into the method.

Example
int sqrt (int num)

Here, sqrt is the method name, num is method parameter that represents that this method
accepts a int type value.

2. Method Body:

Below the method header, we should write the method body Method body consists of a group
of statements which contains logic to perform the task. Method body can be written in the
following format:

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 91

int method_name(parameter_list)
{
//statements;
}
For example, we want to write a method that calculates sum of two numbers. It may contain
the body, as shown here:

int sum(int a, int b)


{
int c = a + b;
System.out.println("Sum of two = "+c);
}
If a method returns some value, then a return statement should be written within the body of
the method, as :
return x; // return x value

A method can never return more than one value.

Program: Write a program for a method with two parameters and return type.
class Sample
{
int sum(int num1, int num2)
{
int res=num1 + num2;
return res; //return result

}
}

class Methods
{
public static void main(String args[])
{
Sample s = new Sample();
int x=s.sum (10, 22);
System.out.println("Sum="+x);
}
}

Output:
C:\>javac Methods.java
C:\> java Methods

Static Members
The variables and methods in the class are called as instance variables and instance methods.
This is because every time the class is instantiated, a new copy of each of them is created.
They are accessed using the objects (with dot operator).

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 92

Let us assume that we want to define a member that is common to all the objects and
accessed without using particular object.

i.e. the member belongs to the class as a whole rather than the objects created from the class.
Such members can be defined as follows:

static int cout;


static void get(float x, int a);

The members that are declared with the keyword static are called as static members. Since
these members are associated with the class itself rather than individual objects, the static
variables and static methods are often referred to a class variables and class methods.
Static variable:

1. It is a variable which belongs to the class and not to object(instance)


2. Static variables are initialized only once, at the start of the execution. These variables
will be initialized first, before the initialization of any instance variables.
3. A single copy to be shared by all instances of the class.
4. A static variable can be accessed directly by the class name and doesn’t need any
object
The following is the syntax for accessing a static variable.
Syntax:
<class-name>.<variable-name>;

static method:

1. It is a method which belongs to the class and not to the object(instance)


2. A static method can access only static data. It cannot access non-static data (instance
variables)
3. A static method can call only other static methods and cannot call a non-static method
from it.
4. A static method can be accessed directly by the class name and doesn’t need any object

The following is the syntax for accessing a static variable

Syntax :

<class-name>.<variable-name>;
<class-name>.<method-name>;.

The following program illustrates the concept of static members in java.


class Result
{
static int a,b; // declaration of static variables

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 93

static void getc(int x,int c) // declaration of static method


{
a=x;
b=c;
}E 182
}
class Stat
{
public static void main(String ar[]) // calling static method with class name
{
Result.getc(10,20); // calling static variables with class name
System.out.println(Result.a + " " + Result.b);
}
}
Output:

Note: main () method is static, since it must be accessible for an application to run, before any
instantiation takes place.

Q). Write about the keyword this?

The keyword 'this': 'this' is a keyword that refers to the object of the class where it is used. In
other words, 'this' refers to the object of the present class. Generally, we write instance
variables, constructors and methods in a class.

All these members are referenced by 'this'. When an object is created to a class, a default
reference is also created internally to the object, as shown in the Figure. This default reference
is nothing but 'this'. So 'this' can refer to all the things of the present object.

The keyword 'this' is a reference to class object

Let's understand the problem if we don't use this keyword Student s1=new Student(111,"ankit",5000f);  


by the example given below: Student s2=new Student(112,"sumit",6000f);  
s1.display();  
class Student{   s2.display();  
int rollno;   }}  
String name;   In the above example, parameters (formal
float fee;   arguments) and instance variables are same. So, we
Student(int rollno,String name,float fee){   are using this keyword to distinguish local variable
rollno=rollno;   and instance variable.
name=name;  
fee=fee;  
}   Solution of the above problem by this keyword
void display(){System.out.println(rollno+" "+name+" 
"+fee);}  
}   class Student{  
class TestThis1{   int rollno;  
public static void main(String args[]){  

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 94

String name;  
float fee;  
Student(int rollno,String name,float fee){  
this.rollno=rollno;  
this.name=name;  
this.fee=fee;  
}  
void display()
{
System.out.println(rollno+" "+name+" "+fee);}  
}  
  
class TestThis2{  
public static void main(String args[]){  
Student s1=new Student(111,"ankit",5000f);  
Student s2=new Student(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  

Prepared by: M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no- 95

Output:

Explain instance methods with example?

Instance methods: Instance methods are the methods which act upon the instance variables. To call
the instance methods, object is needed, since the instance variables are contained in the object. We
call the instance methods by using objectname.methodname(). The specialty of instance methods is
that they can access not only instance variables but also static variables directly.

There are two types of instance methods:


1. Accessor methods.
2. Mutator methods.

Accessor methods are the methods that simply access or read the instance variabiles. They do not
modify the instance variables.
Mutator methods not only access the instance variables but also modify them.

Example program of Accessor and mutator methods

class Person
{
private String name;
private int age;
public void setName(String name) //mutator methods to store data
{
this.name =name;
}
public void setAge(int age)
{
this.age= age;
}
public void setAge(int age)
{
this.age=age;
}
public String getName() // Accessor metods to read data
{
return name;
}
public int getAge()
{
return age();
}
}
class Methhods
{
public static void main(String args[])
{
Person p1=new Person();
p1.setName(“Raju”);
p1.setAge(20);
System.out.prinntln(“Name=”+p1.getName());
System.out.prinntln(“Age=”+p1.getAge());
}
}

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 96

Output:

Explain about passing primitive data types to methods?

Primitive data types (or) fundamental data types represent single entities (or) single values. For
example, char, byte, short, int, long, float, double and boolean are called primitive data types,
because they store single values. They are passed to methods by value.

This means when we pass primitive data types to methods, a copy of those will be passed to
methods. Therefore, any changes made to them inside the method will not affect them outside the
method. In the following program, we pass two integer numbers 10 and 20 to the swap method. Let
us display the output to know whether they are interchanged or not.

Program:

//Primitive data types are passed to methods by value

class check
{
vold swap (int n1, int n2)
{
int temp;
temp=n1;
n1=n2;
n2=temp;
}
}

class PassPrimitive
{
public static void main(String args[])
{
int n1= 10, n2=20;
check ck= new check ();
System.out.println(n1+ " " +n2);
ck.swap(n1, n2);
System.out.println(n1+" " +n2);
}
}

Output:
C> javac PassPrimitive.java
C:>java PassPrimitive
10 20
10 20

Passing objects to Methods:


We can also pass class objects to methods, and return objects from the methods. For example,
Employee myMethod(Employee obj)
{
Statements;
return obj;
}

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 97

Here, myMethod() is a method that accepts Employee class object. So reference of Employee
class is declared as parameter in myMethod()). After doing some processing on the object, if it
returns the same object, we can write a statement like:
return obj;
Program : Write a program to interchange the values inside an object, since the same object data is
modified, we can see the data has been interchanged. Interchanging the values should be done in a
single object
class Employee
{
int id1, id2;
Employee (int id1, int id2)
{
this.id1 = id1;
this.id2=id2;
}
}

class Check
{
value swap(Employee obj)
{
int temp;
temp=obj.id1;
obj.id1 = obj.id2;
obj.id2=temp;
}
}
class PassObjects
{
public static void main(String args[])
{
Employee obj1 = new Employee(10, 20);
Check obj = new check();
System.out.println(obj1.id1+""+obj1.id2);
obj.swap(obj1);
System.out.println(obj1.id 1+"\t"+obj1.id2);
}
}
Output:
C: javac Pass Objects.java
Objects Pass Objects

10 20
2019

How passing arrays to methods? Explain.

Just like the objects are passed to methods, it is also Possible to pass arrays to methods and return
arrays from methods. In this case, an array name should be understood as an object reference. For
example,
int [] myMethod(int arr[])

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 98

This is the way, we can pass a one dimensional array 'arr' to 'myMethod()'. We can also return a one
dimensional array of int type as shown in the preceeding statement.
int[] [] myMethod(int arr[][])
Here, we are passing and returning a two dimensional array of int type.
Example:
class Array
{
public int[] sortArr (int a [], int len)
{
for(i=0; i<len; i++)
for (j=i+1; j<len;j++)
{
if (a[i]>a[j])
{
temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
return a;
}
public static void main(String args[])
{
int a[]={10, 40, 30, 20, 50);
int b[]=obj.sortln(a,a.lengt);
System.out.println("sorted array elements are");
for(int i=0;i<b.length;i++)
System.out.println(b[i] +’’);
}
}

Output:
sorted array elements are
10 20 30 40 50

Java static block

A static block is a block of statement declared as “static”, some thing like tis:
static
{
Statement;
}

JVM execute a static block on a highest priority basis. This means JVM first goes to static block even
before it looks for the main() method in the program.
Example:
Class Test
{
Static
{
System.out.println(“Static block”);
}
public static void main(String args[])
{
System.out.println(“Static method”);
}

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 99

}
Output:

What is Recursion? Explain with example?


Recursion: A method calling itself is known as 'recursive method' and that phenomenon is called
'recursion'. It is possible to write recursive methods in Java.

Program: Write a program to find factorial value with using recursion.

//Factorial with Recursion

class Recursion
{
static long factorial(int num)
{
long result;
if (num==1)
return 1;
result =factorial (num-1)*num;
return result;
}
public static void main(String args[])
{
System.out.println("Factorial of 5:");
System.out.println(Recursion.factorial(5));
}
}
Output:
C:\>javac Recursion.java
C:\>java Recursion
Factorial of 5;
120

What are factory methods?

A factory method is a method that creates and returns an object to the class to which it belongs.
A single factory method replaces several constructors in the class by accepting different options
from the user, while creating the object.

To understand how to use a factory method, let us take an example program to calculate the
area of a circle.

Example a program for calculating and displaying area of a circle.

class Circle
{
public static void main(String arg[])
{
final double PI = (double)22/7;
double r= 15.5; //radius
double area = Pl*r*r;
System.out.println("Area = " + area);
}
}
Output:
C:>javac Circle.java
C:\> java Circle

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 100

Area-755.0714285714286

Inheritance in Java
Inheritance in Java 

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

The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship

Parent (Properties)

Parent Properties Inherited to Child

Child (Parent Properties


+
(Child Properties) Now Child have Parent properties +
His / her own properties.

Fig: Inheritance
 The class which is giving members (variables and methods) to some other class is known as
base class / super class / parent class.

 The class which is retrieving or obtaining members (variables and methods) is known as
derived class / sub class / child class.

 The inheritance allows subclasses to inherit all the variables and methods of their parent
classes. A Derived class contains its own properties (members) plus base class properties
(members).

Advantages of Inheritance

 Application development time is reduced.


 Application memory space is reduced.
 Redundancy (Repetition) of the code is reduced.
 Reusability.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 101

Syntax for INHERITING the features from base class to derived class:

class <sub_classname> extends <super_classname>


{
Variable declaration; Method declaration;
}

 The keyword extends signifies that the properties of the super_classname are extended to
the sub_classname.
 The subclass will now contain its own variables and methods as well those of the super
class.
 This kind of situation occurs when we want to add some more properties to an existing
class without actually modifying it and also improves functionality of derived class.

Types of Inheritances (Reusable Techniques)


Based on getting the features from one class to some other class, java have the following types of
reusable techniques.
1. Single Inheritance (only one super class, one sub class)
2. Multilevel Inheritance ( Derived from derived class)
3. Hierarchical Inheritance (one super class, many sub classes)
4. Multiple Inheritance (several super classes)

1. Single Inheritance

In Single Inheritance single base class is derived to a single derived class. If one child class is
inheriting the properties of the parent class without any intermediate class, then it is called as
“Single Inheritance”.

A subclass acquires the properties from the super class is also called as “Single inheritance”. For
example C2 class is derived from C1 class; Now C2 access all the properties of C1 and itself. It is
shown in below.
Fig: Single Inheritance
Example:

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 102

class c1
{
---------
}
class c2 extends c1
{
---------
}

The following program illustrates the concept of Single Inheritance.


Aim: Program to find the area of the room and the volume of a bed room.
Program
class Animal
{  
void eat()
{
System.out.println("eating...");
}  
}  

class Dog extends Animal
{  
void bark()
{
System.out.println("barking...");
}  
}  

class TestInheritance
{  
public static void main(String args[])
{  
Dog d=new Dog();  
d.bark();  
d.eat();  
}}
Output:

2. Multilevel Inheritance
Multilevel Inheritance contains one base class and one derived class, and multiple
intermediate base classes.

A Child class(Derived class) acquire the properties of Parent class(intermediate class), and
Parent class(intermediate class) acquire the properties of grandparent class(Base class). It is
also called multilevel inheritance.

For example C2 class is derived from C1, C3 class is derived C2, and C4 class is derived C3; Now
C2 access C1 class members and itself only, C3 access C2 and C1 class members and itself only,

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 103

and C4 can access C3,C2,C1class members and itself only. It is shown in below.

Fig:- Multilevel inheritance:

Example:

class c1
class Animal {
---------
{  
---------
void eat() }
{ class c2 extends c1
System.out.println("eating..."); {
}   ---------
---------
}   }
class c3 extends c2
class Dog extends Animal{   {
void bark() ---------
{ ---------
}
System.out.println("barking..."); class c4 extends c3
}   {
}   ---------
---------
class BabyDog extends Dog }
{  
void weep()
{
System.out.println("weeping...");
}  
}  

class TestInheritance2
{  
public static void main(String args[])
{  
BabyDog d=new BabyDog();  
d.weep();  
d.bark();  
d.eat();  
}
}  

Output:

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 104

3. Hierarchical Inheritance

Hierarchical Inheritance contains a single base class and multiple derived classes. In hierarchical
inheritance multiple subclasses acquire the properties of only single super class, it is also called
as hierarchical inheritance.

Fig: Hierarchical Inheritance

For example C2, C3, C4, classes are derived from C1 class; Now C2, C3, C4 classes can access C1
class members and itself only. It is shown in below.

Syntax:
class c1
{
---------
---------
}
class c2 extends c1
{
---------
---------
}
class c3 extends c1
{
---------
---------
}
class c4 extends c1
{
---------
---------
}

Example:
class Animal
{  
void eat()
{System.out.println("eating...");}  
}  

class Dog extends Animal
{  
void bark()
{
System.out.println("barking...");
}  
}  

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 105

class Cat extends Animal
{  
void meow()
{System.out.println("meowing...");}  
}  

class TestInheritance3
{  
public static void main(String args[])
{  
Cat c=new Cat();  
c.meow();  
c.eat();  
//c.bark();//C.T.Error  
}}
Output:

4. Multiple Inheritance

Multiple Inheritance contains multiple base classes and a single derived class. For example C4
class is derived from C1, C2, and C3 Base classes; Now C4 can access C1, C2, C3 members and
itself. It is shown in below.

Fig: Multiple Inheritance


The concept of multiple inheritances is not supported in java directly but it can be supported
through the concept of interfaces. Because if class C1 and C2 contains some variable, Now from
which class the same variable is Inherited to C4 class. It leads to confusion.

Super keyword
Subclass Constructor (‘super’ keyword)
A Subclass constructor is used to construct the instance variables of both the subclass and the
super class. The subclass constructor uses the keyword super to invoke the constructor method
of the super class. The super keyword is used subject to the following conditions.

 super may only be used within a subclass constructor method.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 106

 The call to super class constructor must appear as the first statement within the
subclass constructor.
 The parameters in the super call must match the order and type of the instance
variables declared in the super class.

Write about the protected specifier?

The Protected Specifier: The private members of the super class are not available to sub classes
directly. But sometimes, there may be a need to access the data of super class in the sub class.

For this purpose, protected specifier is used. Protected is commonly used in super class to make the
members of the super class available directly in its sub classes.

Example: Program to understand private members are not accessible in subclass, but protected
members are available in sub class.

//private and protected

class Access
{
private int a;
protected int b;
}

class Sub extends Access


{
public void get()
{
System.out.println(a); //error-a is private
System.out.println(b);
}
}

class Test
{
public static void main(String args[])
{
Subs= new Sub ();
s.get();
}
}

Output:

javac Test java


Test.java:11: a has private access in Access
System.out.println(a);
1 error

UNIT-3, Polymorphism and Typecasting


Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 107

Q). Polymorphism
The word polymorphism is a combination of two words i.e. ploy and morphs. The word poly
means many and morphs means different forms. In short, a mechanism by which we can perform a
single action in different ways.

Let's understand the meaning of polymorphism with a real-world example.

A person in a shop is a customer, in an office, he is an employee, in the home he is husband/


father/son, in a party he is guest. So, the same person possesses different roles in different places.
It is called polymorphism.

Polymorphism with Variables


When using variables, sometimes inherently the data type of the result is decided by the compiler
and accordingly execution proceeds. For example, in the statement:

System.out.println (a+b) ;

Java compiler decides the data type of the result of the expression a+b depending on the data
types of a and b. If a and b are int type, then a + b will also be taken as int type. If a and b are float
type variables, then a+b will be taken as float type. If a is int and b is float, then the compiler
converts a also into float and then sum is found. Thus, the result a + b is exhibiting polymorphic
nature. It may exist as an int or as a float or as some other data type depending on the context.
This is also called 'Coercion'.

Types of Polymorphism
There are two types of polymorphism in Java:
1. Static Polymorphism (Compile Time Polymorphism)
2. Dynamic Polymorphism (Run Time Polymorphism)

1. Static Polymorphism:
The polymorphism exhibited at compilation time is called static polymorphism. Polymorphism that
is resolved during compiler time is known as static polymorphism. Method overloading is an
example of compile time polymorphism.

1. Method overloading :

The process of defining methods with same name but with different functionalities is termed
method overloading.
To create an overloaded method, several different method definitions are created in the class with
the same name but with different parameter lists. Java differentiates overloaded methods based
on the number and type of parameters and not on the return type of the method.
A compiler error would occur when two methods with the same name and same parameter list
but different return types are created.

Example program for Method Overloading:

class MethodOverload
{
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 108

public static void first()


{
System.out.println("without any arguments");
}

public static void first(int a, int b)


{
System.out.println(a+b);
}

public static void main(String args[])


{
first();
first(10,20);
}
}

Output

2. Dynamic Polymorphism:
The polymorphism exhibited at runtime is called dynamic polymorphism. This means when a
method is called, the method call is bound to the method body at the time of running the
program, dynamically. In this case, Java compiler does not know which method is called at the
time of compilation. Only JVM knows at runtime which method is to be executed. Hence, this is
also called 'runtime polymorphism' or 'dynamic binding'.

1. Method Overriding:

Method overriding means both the super class method and sub class methods having the same
name, same signature. i.e., number of parameters and types of parameters should be same.
Method overriding is allowed only in inheritance. Method overriding is an example of
polymorphism.

//Java Program to illustrate the use of Java Method Overriding  
//Creating a parent class.  

class Vehicle
{  
 
  void run()  //defining a method  
{System.out.println("Vehicle is running");}  
}  
//Creating a child class  
class Bike2 extends Vehicle
{  
  
  void run() //defining the same method as in the parent class  
{System.out.println("Bike is running safely");}  
  
  public static void main(String args[])
{  
  Bike2 obj = new Bike2(); //creating object  

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 109

  obj.run(); //calling method  
  }  
}  

Output:
Bike is running safely
Bike is running safely

1. Polymorphism with Static Methods:

A static method is a method, one single copy in memory is shared by all the objects of the class. Static
methods belong to the class rather than to the objects. So they are also called class methods. When
static methods are overloaded or overridden, since they do not depend on the objects, the Java
compiler need not wait till the objects are created to understand which method is called.

Program: Write a program to use super class reference to call the calculate () method.

//static polymorphism

class One
{
static void calculate (double x)
{
system.out.println("square value="+(x*x));
}
}
class Two extends One
{
static void calculate (double x)
{
System.out.println("square root="+ Math.sqrt(x));
}
}

class Poly
{
public static void main(String args[])
{
one o= new Two ();
o.calculate (25);
}
}
Output:

C:\> javac poly.java


C:\>javac poly
square value =625.0

2. Polymorphism with Private Methods:

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 110

Private methods are the methods which are declared by using the access specifier 'private. This
method is not to be available outside the class. So other programmers cannot access the private
methods.

Even private methods are not available in the sub_classes. This means there is no possibility to
override the private methods of the super_class in its sub_classes. So only method overloading is
possible in case of private methods.

Example:
class Hello
{
private void call ()
{
system.out.println (“Hello world!”);
}
public static void main (String args [])
{
Hello h1=new Hello();
h1.call ();
}
}
Here in this code we have a private method -call() and we try to access this method under the main
method which lies in the same class Hello. Hence we get the desired output.

But if you try to call this private method - call() in some other class then you won't get the desired
output. Because when you write a method as private then it's accessibility is limited to that
particular class only.

3. Polymorphism with final methods and classes :

The Specifier final is used to finalize classes, methods and variables. Finalizing a thing effectively
'freezes the implementation or value of that thing. More specifically, here is how final works with
classes, variables and methods, respectively:

1. When the Specifier final is applied to a class, it means that the class cannot be inherited.
2. When final is applied to a variable, it means that the variable is constant.
3. When final is applied to a method in a class, it means that the method cannot be overridden in
the sub-classes. .

1. Finalizing classes:
In order to finalize a class, the Specifier final is added to the class definition. Typically, it is added
after protection Specifiers such as private (or) public. This is done as shown below:

public final class FinalClass1


{
………………
}
A class is declared final for the following reasons:
 To prevent inheritance

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 111

 For better efficiency. Final classes allow programmers to rely on instances of only that class
and optimize those instances

2. Finalizing variables:
The value of a finalized variable cannot be changed. It is then, effectively, a constant. To declare
constants in Java, final variables with initial values are used. This declaration can be done in a
program as follows:

public class FinalClass2


{
public static final int ConstantInteger = 100;
public final String ConstantString = “JAVA BOOK”;
}
Local variables (those inside blocks of code surrounded by braces; for example, in while or for
loops) cannot be declared final.

3. Finalizing methods:
Methods that cannot be overridden are known as finalized methods. The implementations of
final methods cannot be redefined in sub-classes. The syntax for declaring a method final is the
following.

public class FinalMethodClass


{
public final void One ()
{
……
}
}
Declaring methods final improves their efficiency.

Q). Explain about casting primitive data types?


Casting Primitive Data Types:

It is possible to convert one primitive data type into another primitive data type. This is done in
two ways, widening and narrowing. The primitive data types are classified into two types, lower
types and higher types naturally, the lower types are the types which use less memory and which
can represent lesser number of digits in the value. The higher types use more memory and can
represent more number of digits. To recognize the lower and higher types, the following diagram
is useful:

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

Lower ------------------------------higher

Thus, char is a lower type than int. float is a higher type than long, boolean is not included earlier,
because it cannot be converted into any other type.

1. Widening in Primitive Data Types:

Converting a lower data type into a higher data type is called wide examples:

char ch = 'A' ;

int num= (int)ch; //num contains 65, the ASCII value

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 112

Here, we are converting char type variable 'ch' into used the cast operator by writing 'int' in the
simple. Now that ch is converted into int type, it can be is an example for widening.

int x=9500;

float sal = (float)x; //sal contains

Here, we are converting int type variable 'x' into float. So, we wrote (float) before the variable x.
Widening is safe because there will not be any loss of data or precision or accuracy.

2. Narrowing in Primitive Data Types:

Converting a higher data type into a lower data type is called 'narrowing'. Take the examples:

int n=66;

char ch= (char) n; //ch contains 'B'.

Here, we are converting int type n value into char type. The value of n is 66 which is when
converted into char type represents the character 'B', since 66 is the ASCII value of 'B'. This
character is stored into ch.

double d=12.6789; //n stores 12.


int n= (int) d:
Observe, we are converting double type into int type by using the cast operator (int) before the
variable d. The value in d is 12.6789. Since it is converted into int type, the fraction part of the
number is lost and only 12 is stored in n. Here, we are losing some digits. So narrowing is not
safe.

Q). Reference Type Casting


Objects of classes also can be type cast into objects of other classes when the source and
destination classes are related by inheritance and one class is a subclass of the other.

The type_cast can be to its own class type or to one of its subclass or super_class types or
interfaces. There are compile-time rules and runtime rules for casting in java. There are two types
of Reference Type Casting in Java, they are:

1. Up Type_casting
2. Down Type_casting

Up Type_casting is casting to a super_type, while down Type_casting is casting to a subtype.


Super Type_casting is always allowed, but sub Type_casting involves a type check and can throw a
ClassCastException.

1. Up Type_casting:

 A subtype object into a supertype and this is called up Type_cast. In Java, we need not add an
explicit cast and you can assign the object directly. Compiler will understand and cast the value to
supertype. By doing this, we are lifting an object to a generic level. If we prefer, we can add an
explicit cast and no issues.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 113

2. Down Type_casting:

A  supertype to a subtype is called down Type_cast. This is the mostly done cast. By doing this we
are telling the compiler that the value stored in the base object is of a super type. Then we are
asking the runtime to assign the value. Because of down Type_cast, we get access to methods of
the subtype on that object. When performing down Type_casting, that you’re well aware of the
type of object you’ll be casting.

Q). 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, known as
upcasting.

Let's take an example, there is getObject () method that returns an object but it can be of any type
like Employee, Student etc, we can use Object class reference to refer that object. For example:

Object obj=getObject (); //we don't know what object will be returned from this method  

The Object class provides some common behaviors to all the objects such as object can be
compared, object can be cloned, object can be notified etc.

Methods of Object class


The Object class provides many methods. They are as follows:

Method Description
public final Class getClass() returns the Class class object of this object. The Class
class can further be used to get the metadata of this
class.
public int hashCode() returns the hashcode number for this object.
public boolean equals() compares the given object to this object.
protected Object clone() creates and returns the exact copy (clone) of this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
public final void wait(long timeout) causes the current thread to wait for the specified
milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).

protected void finalize() is invoked by the garbage collector before object is being
garbage collected.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 114

Abstract Classes & Interfaces

What is an abstract method and abstract class?

An abstract method does not contain any body. It contains only the method header, So we can say it
is an incomplete method. An abstract class is a class that generally contains some abstract methods.
Both the abstract class and the abstract methods should be declared by using the key word 'abstract'.

Abstract class in Java


A class which is declared as abstract keyword is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.

Points to Remember

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


2.It can have abstract and non-abstract methods.
3.It cannot be instantiated.
4.It can have constructors and static methods also.
5.It can have final methods which will force the subclass not to change the body of the
method.
Example of abstract class

abstract class A
{

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

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

 abstract keyword is used to declare the method as abstract.

 You have to place the abstract keyword before the method name in the method declaration.

 An abstract method contains a method signature, but no method body. Instead of curly braces
an abstract method will have a semoi colon(;) at the end.

Example program for Abstract Class and Methods:

In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.

abstract class Bike

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 115

{  
  abstract void run();  
}  

class Honda4 extends Bike
{  
void run()
{
System.out.println("running safely");
}  

public static void main(String args[])
{  
 Bike obj = new Honda4();  
 obj.run();  
}  
}  

Interface in java
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 116

Interface in java

An interface in java is a blueprint of a class. It has static constants and abstract methods.

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods
in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance
in Java.

In other words, you can say that interfaces can have abstract methods and variables. It cannot
have a method body.

Defining Interface

An interface is like a fully abstract class, except that it cannot have any concrete method (or)
instance variables. It is a collection of abstract method declarations and constants that is static
final variables.

 This means that interfaces do not specify any code to implement these methods.
 Any class that implements an interface must implement all of the methods specified in that
interface.
 A class can implement many interfaces but can extend only one class.

The general syntax for defining interface is:

interface InterfaceName
{
variable declaration;
method declaration;
}
Here interface is a keyword and interfaceName is any valid Java variable.

Example:
interface Item
{
static final int code = 1001;
static final String name = "fan";
void display();
}

 Variables are declared as constants using static final keywords.


 Note that the code for display() is not included in the interface. The class that implements this
interface must define the code for the method.

Extending Interfaces
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 117

Interfaces can also be extended as a classes. The new sub_interface will inherit all the members of
the super_interface in the manner similar to subclasses.

interface ItemConstants
{
int code = 1000;
String name = "Fan";
}
interface Item extends ItemConstants
{
void display();
}
Output:

 While interfaces are allowed to extend to other interfaces, sub interfaces cannot define the
method declared in the super interface. Instead, it is the responsibility of any class that
implements the derived interface to define all the methods.
 Interfaces can have access Specifiers of public or blank, just like classes.
 An interface can be defined as extending another interface, similar to class hierarchy, but there is
no base interface analogous to the Object class.

Interface - Extending Interface:

import java.io.*;
interface inter1
{
int a = 100;
final static int b = 200;
}
interface inter2 extends inter1
{
void show();
}
class interclass implements inter2
{
public void show()
{
int c = a + b;
System.out.println("Sum="+c);
}
}
class ExtendingInterface
{
public static void main(String args[])
{
interclass obj = new interclass();
obj.show();
}
}
Output :

Implementing Interfaces

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 118

Interfaces are used as "superclasses" whose properties are inherited by classes. It is, therefore,
necessary to create that inherits the given interface.

class classname extends superclass


implements interface1, interface2,.............
{
}

As shown in the figure given below, a class extends another class, an interface extends another
interface, but a class implements an interface.

Class can extend another class while implementing interface.

Implementing Interface:
import java.io.*;
interface inter //interface define
{
void show();
}
class interclass implements inter // implement the interface
{
public void show()
{
System.out.println("Hello Java - Interface");
}
}
class ImplementingInterface
{
public static void main(String args[])
{
interclass obj = new interclass();
obj.show();
}
}
Output:

Q). Implementing Multiple Inheritances using Interface:

Java does not support multiple inheritances. This means that a class cannot extend more than one
class. Therefore, following is illegal

public class extends Animal, Mammal{}

However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritance. The extends keyword is used once, and the parent interfaces are
declared in a comma-separated list.

For example, if the C interface extended both A and B, it would be declared as −

public interface C extends A, B

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 119

If a class implements multiple interfaces, or an interface extends multiple interfaces, it is known as


multiple inheritance.

Example:
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A4 implements Printable, Showable
{
public void print()
{System.out.println("Hello");}
public void show()
{System.out.println("Welcome");}

public static void main(String args[])


{
A4 obj = new A4();
obj.print();
obj.show();
}
}

Q). Difference between abstract class and interface

Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.

But there are many differences between abstract class and interface that are given below.

Abstract class Interface


1) Abstract class can have abstract and 1) Interface can have only abstract methods.
non-abstract methods. Since Java 8, it can have default and static
methods also.
2) Abstract class doesn't support 2) Interface supports multiple inheritance.
multiple inheritance.
3) Abstract class can have final, non- 3) Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the 4) Interface can't provide the implementation

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 120

implementation of interface. of abstract class.


5) The abstract keyword is used to 5) The interface keyword is used to declare
declare abstract class. interface.
6) An abstract class can extend another 6) An interface can extend another Java
Java class and implement multiple interface only.
Java interfaces.
7) An abstract class can be extended 7) An interface can be implemented using
using keyword "extends". keyword "implements".
8) A Java abstract class can have class 8) Members of a Java interface are public by
members like private, protected, etc. default.
9) Example: 9) Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }

PACKAGES
Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science
Page no- 121

Packages (Putting classes together)

If we need to use classes from other programs without physically copying them into the program
under development, this can be accomplished in java by using packages a concept similar to “class
libraries” in another languages.

A package is a collection of related classes and interfaces. done according to functionality.


Packages are containers for classes.

1. Advantages of packages:

 The classes contained in the packages of other programs can be easily reused.

 Two classes in two different packages can have the same name. They can be uniquely
identified by packagename.classname.

 Packages provide a way to hide classes.

 Packages provide a way for separating design from coding.

Thus a Package is a collection of classes, interfaces and sub-packages. A Sub package in turns
divides into classes, interfaces and sub-sub-packages, etc.

Types of Packages:
In java the packages are classified into two categories. They are

1. Java API packages ( Predefined Packages)


2. User defined Packages.

1. Java API packages (or) Predefined Packages


Java API provides a large number of classes grouped into different packages according to
their functionalities. Most of the time we use the packages available with the Java API.
The packages are divided based on functionality as below.

Fig: Frequently used

They are shown in below.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 122

Package Name Package Description


Java.lang.*; Language support classes. These are classes that java compiler itself uses
and therefore they are automatically imported. This package is default
package in java. They include classes for primitive types, strings, math
functions, threads and exceptions.
Java.util.*; Language support classes such as vectors, hash tables, date etc. This
package is used for developing quality or reliable applications in java. This
package contains various classes and interfaces which improves the
performance of J2ME applications.
Java.io.* Input and Output support classes. They provide facilities for the input and
output data.
Java.awt.* Set of classes for implementing graphical user interface. They include
(abstract window
classes for windows, buttons, lists, menus and so on.
toolkit)
Java.applet.*; Classes for creating and implementing applets. This package is used for
developing browser oriented applications. In other words this package is
used for developing distributed applications. An applet is a java program
which runs in the context of www or browser.
Java.net.*; Classes for networking. They include classes for communicating with local
computers as well as with internet servers. This package is used for
developing client server applications.

2. User defined packages:

User-defined packages are those packages that are designed (or) created by the developer
(user) to categorize classes and packages. They are much similar to the built-in that java
offers. It can be imported into other classes and used the same as we use built-in packages

Defining & Creating a package:

Creating our own packages (or) user defined packages involves the following steps:
Step1:
1. To create a package, simply include a package command as the first statement in a Java
source file. First declare the name of the package using package keyword followed by a
package name.

2. This must be first statement in java source file (except any comment or white spaces).

3. Any class you declare within that file will belong to the specified package.

Example: package mypack;

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 123

Step 2:

1. Next define the class that is to be put in the package and declare it as public.
package mypack; // package declaration
public class FirstClass // class definition
{
…………
………… // Body of class
…………
}

Step 3:
1. Now store the classname.java file as same as normal java programs save.
Step 4:
1. File is to be compiled as fallows.

Example: C:\> javac –d . FirstClass.java

Which creates FirstClass.class file and stores it in the mypack directory created under current
directory by -d. Java also supports the package hierarchy, which allows grouping related
classes into a package and then grouping related packages into a larger package. We can
achieve this by specifying multiple names in a package statement, separated by dot.

Using (or) Accessing Package

A java system package can be accessed either by using a fully qualified class name or by using
import statement. We generally use import statement.
Syntax:

Here pack1 is the top level package, pack2 is the package which is inside in pack1 and so on.
In this way we can have several packages in a package hierarchy. We should specify explicit

class name finally. Multiple import statements are valid. * indicates that the compiler should
search this entire package hierarchy when it encounters a class name.

Explain about interfaces in a package?

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 124

It is also possible to write interfaces in a package. But whenever, we create an interface the
implementation classes are also should be created. We cannot create object to the interface
but we can create objects for implementation classes and use them. We write an interface to
display system date and time in the package mypack as shown in the following program.

Program: //Create MyDate interface in the package mypack

package mypack;
public interface MyDate
{
void showDate();
}
Output:
C:\> javac -d. MyDate.java

C:\>

Compile the preceding code and observe that the Java compiler creates a sub directory with the
name mypack and stores MyDate.class file there. This MyDate.class file denotes the byte code of
the interface.

Program: Write a program to create an implementation class for the MyDate interface with the
name DateImpl and storing it in the same package mypack.

//This is implementation class of MyDate interface

package mypack; //store DateImpl class also in mypack'


import my pack.MyDate;
import java.util.*;
public class DateImpl implementation MyDate
{
public void showDate()
{
Date d=new Date ();
System Out println(d);
}
}
Output:
C:\> javac -d. DateImpl.java
C:\>

When the preceding code in completed, Datelmpl.class file is created in the same package mypack.
Datelmpl class contained showDate () method which can be called and used in any other program.

Program: Write a program which shows how to use the Datelmpl which is an implementation class
of MyDate interface.

//Using the Datelmpl of mypack

import mypack.Datelmpl;
class DateDisplay
{
public static void main(String args[])

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 125

{
Datelmpl obj= new Datelmpl();
obj.showDate();
}
}

Output:

C:\> javac DateDisplay.java


C:\>java DateDisplay
Tue May 29 21:14:43 IST 2022

Q). How to creating sub package in a package? explain with examples?

Creating Sub Package in a Package

We can create sub package in a package in the format:

package pack1. pack2:

Here, we are creating pack2 which is created inside pack1. To use the classes and interfaces of pack2,
we can write import statement as:

import pack 1.pack2;

This concept can be extended to create several sub packages. In the following program we are
creating tech package inside dream package by writing the statement

package dream.tech;

Program: Let us make a program to learn how to create a sub package in a package.

//Creating a sub package tech in the package dream.

package dream.tech;
public class Sample
{
public void show ()
{
System.out.println ("welcome to Dream tech");
}
}
Output:
C:\>java -d. Sample.
C:\>

When the proceeding program is compiled, the Java compiler creates a sub directory with the name
dream. Inside this, there would be another sub directory with the name tech is created. In this tech
directory, Sample class is stored. Suppose the user wants to use the Sample class of dream.tech
package, he can write a statement as:

import dream.tech.Sample;

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 126

Program: Let us make a program using Sample class of dream.tech package.

//Using the package dream.tech


import dream.tech.Sample;
class Use
{
public static void main (String args[])
{
Sample s= new Sample ();
s.show();
}
}

Output:

C:\> javac Use.java


C:\>java Use
Welcome to Dream tech

Q). Access Specifiers in Java

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

The access specifiers in Java specify the accessibility (or) scope of a field, method, constructor, or
class. We can change the access level of fields, constructors, methods, and class by applying the
access Specifier on it.

There are four types of Java access Specifiers:

1. Private:

The access level of a private specifier is only within the class. It cannot be accessed from
outside the class.

2. Default:

The access level of a default Specifier is only within the package. It cannot be accessed from
outside the package. If you do not specify any access level, it will be the default.

3. Protected:

The access level of a protected Specifier is within the package and outside the package
through child class. If you do not make the child class, it cannot be accessed from outside the
package.

4. Public:

The access level of a public Specifier is everywhere. It can be accessed from within the class,
outside the class, within the package and outside the package.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 127

There are many non-access Specifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access Specifiers only.

Understanding Java Access Specifiers

Let's understand the access Specifiers in Java by a simple table.

Access within within outside package by outside


Specifier class package subclass only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

Q). Creating API Document:

Application Programming Interface (API) document is a Hyper Text Markup language (html) file that
contains description of all the features of software, a product or a technology.

API document is like a reference manual that is useful to all the users of the product to understand all
the features and how to use them. For example, JavaSoft people have created API document
separately for the three parts, Java SE, Java EE and Java ME after they created Java language.

Every feature of Java language is described in API document. We can select any package, any class in
that package and the description of the class along with the fields, constructors, methods will appear.

When we click on any of these features, a detailed description of the feature is displayed. We can also
click on Index of the first row to see the index of all items in alphabetical order. Let us know how to
create an API document for any software:

1. First of all, we should copy all the source code files (.java) into a directory. For example, copy
APIDocEx .java of the package pack into a directory
e:\temp.

2. We should open each of the source code files and provide Java documentation comments by
using /** and */. When documentation comments are written, the APIDocEx .java files look like
shown here:

An example that shows document API


In this example; we can create a simple class that contains a documentation comment and shows how
to create a documented API.
package com.mypack;  
public Class APIDocEx   
{  
  public static void square(int x)   
  {  
   System.out.println(x * x);  
 }  
}  
Output
To create the document API, we need to use the javadoc tool as in the following.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 128

 In a command prompt write the following:

 javadoc M.java

 
After generating the documented API. We will now see many HTML(browser) files created. Now we
need to open the index.html file to get the information about the classes. The figure below shows the
following.

Q). JAR Files in Java:

JAR (Java Archive) file is a file that contains compressed version of class files, audio files, image files
or directories. We can imagine a jar file as a zipped file (.zip) that is created by using WinZip software.
Even, WinZip software can be used to extract the contents of a jar file. The difference is that a jar file
can be used as it but whereas the .zip file cannot be used directly. The files should be extracted first
from a .zip file, and then used...

Creating a Jar file


You can create a Jar file using the jar command as shown below.
jar cf jar-file input-file(s)
Let us consider an example, create a Sample Java program with name Sample.java
Sample.java
public class Sample {
public static void main(String args[]){
System.out.println("Hi welcome to Tutorialspoint");
}
}
If you compile this program using Javac command as shown below −
C:\Examples >javac Sample.java
This command compiles the given java file and generates a .class file (byte code)

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 129

Now, create a jar file for the generated class as −


C:\Sample>jar cvf sample.jar *.class
added manifest
adding: Sample.class(in = 434) (out= 302)(deflated 30%)
This will generate a jar file for all the classes in the current directory (since we used * instead of name)
with specified name.

Exceptions Handling

Error

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 130

It is common to make mistakes while developing as well as typing a program. A mistake leads to an
error. Errors are the wrongs that can make a program go wrong.

An error may produce an incorrect output (or) may terminate the execution of the program
abruptly (o)r even may cause the system to crash. It is therefore important to detect and manage
properly all the possible error condition in the program so that the program will not terminate or
crash during execution.

Types of Errors
Errors may broadly classified into two categories.
1. Compile-time errors
2. Run-time errors.
1. Compile-Time Errors
All syntax errors will be detected and displayed by the java compiler and therefore these errors
are known as compile-time errors. Whenever the compiler displays an error, it will not create the
.class file.

The following program is the illustration of Compile-time errors

Most of the compile time errors are due to typing mistakes. The most common problems:
 Missing semicolons
 Missing brackets in the classes and methods
 Misspelling of identifiers and keywords
 Missing of double quotes in strings
 Use of undeclared variables
 Incompatible types in assignment / initialization And so on
2. Runtime Errors
Sometimes, a program may compile successfully creating the .class file but may not run properly.
Such programs may produce wrong results due to wrong logic (or) may terminate due to errors
such as stack overflow. Most common Run-time errors are:
 Dividing an integer by zero
 Accessing an element that is out of the bounds of an array
 Trying to store a value into an array of an incompatible class or type
 Passing a parameter that is not in a valid range or value for a method
 Attempting to use a negative size of an array.
 Converting invalid string to a number
 Accessing a character that is out of bounds of a string
When such errors encountered, java typically generates an error message an aborts the program.
The following program is the illustration of Run-time errors.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 131

Exception
An exception is a condition that is caused by a Run-Time Error in the program. When the java
interpreter encounters an error such as dividing an integer by zero, it creates an Exception Object
and throws it (i.e. informs us that an error has occurred).
 If the exception object is not caught and handled properly, the interpreter will display an
error message and will terminate the program.

 If we want the program to continue with exception of the remaining code, then we should
try to catch the exception object thrown by the error condition and then display an
appropriate message for taking corrective actions. This task is known as Exception Handling.

The purpose of exception handling mechanism is to provide a means to detect and report an
“Exceptional Circumstance” so that appropriate action can be taken.
Exception handling mechanism performs the following tasks:
 Find the problem ( Hit the exception)
 Inform that an error has occurred (throw the exception)
 Receive the error information (catch the exception)
 Take corrective actions (Handle exception)

The error handling mechanism code basically consists of two segments, one detect errors and to
throw exceptions and other to catch exceptions and to take appropriate actions.
Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow of the application. An
exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:

statement 1;
statement 2;
statement 3;
statement 4;
statement 5; //exception occurs
statement 6;
statement 7;
statement 8;
statement 9;
statement 10;
Suppose there are 10 statements in your program and there occurs an exception at statement 5,
the rest of the code will not be executed i.e. statement 6 to 10 will not be executed. If we perform
exception handling, the rest of the statement will be executed. That is why we use exception
handling in Java.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 132

Java exception handling is managed via 5 keywords, try, catch, throw, throws and finally. The
general form of exception handling block is

1. Try:

The "try" keyword is used to specify a block where we should place exception code. The try
block must be followed by either catch (or) finally. It means, we can't use try block alone.

2. Catch:

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

3. Finally:

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

4. Throw:

The "throw" keyword is used to throw an exception.

5. Throws:

The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies
that there may occur an exception in the method. It is always used with method signature.

Syntax of Exception Handling Code


The basic concepts of exception handling are throwing an exception and catching it. This illustrates
in the following figure.

Fig: Exception handling mechanism

Java uses the keywords try and catch to handles the exceptions in the java programs.

The following table shows the some common errors that are occurred in the java programs.

Exception Type Cause of Exception


1. ArithemeticException 1.Caused by the math errors such as division by zero.
2. ArrayIndexOutOfBoundsException 2.Caused by bad array indexes.
3. FileNotFoundException 3.Caused by an attempt to access a non existing file.
4. NumberFormatException 4.Caused when a conversion between strings and numbers fails.

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 133

5. IOException 5.Caused by general I/O failures

Exceptions in java can be categorized into two types.


1. Checked Exceptions:
These exceptions are explicitly handled in the code itself with the help of try-catch blocks.
Checked exceptions are extended from the java.lang.Exception class.
2. Unchecked Exceptions:

These exceptions are not essentially handled in the program code, instead the JVM handles
such exceptions. Unchecked exceptions are extended from the class
java.lang.RuntimeException.

Java Try Block and Catch Block:


Try Block:
Java uses the keyword try to preface a block of code that is likely to cause an error condition and
“throw” an exception. The try block can have one or more statements that could generate an
exception. If anyone statement generates an exception, the remaining statements in the block are
skipped and execution jumps to the catch block that is placed next to the try block.
catch Block
The catch block is defined by the keyword catch catches the exception thrown by the try block and
handles it appropriately. The catch block is added immediately after the try block. The catch block
can have one or more statements that are necessary to process the exception. The try statement
should be followed at least on catch statement; otherwise compilation error will occur.
catch statement works like method definition. It passed single parameter, which is reference to
exception object thrown (by the try block). If the catch parameter matches with the type of
exception object, then the exception is caught and the exception is handled otherwise program will
be terminated.

Syntax:
try
{
//Statements that causes Exception
}
catch(ExceptionType ex_ob)
{
//Statements that handle Exception
}

Example:
public class Testtrycatch2{
public static void main(String args[]){
try{
int data=50/0;
}

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 134

catch(ArithmeticException e){
System.out.println(e);
}
System.out.println("rest of the code...");
}
}

Multiple catch Statements


Multiple catch statements handle the situation where more than one exception could be raised
by a single piece of code. In such situations specify two or more catch blocks, each specify
different type of exception.
Syntax:
……………………
……………………
try
{
Statements; // Generates an exception
}
catch ( Exception-type-1 e)
{
Statements; // Process exception type-1
}
catch ( Exception-type-2 e)
{
Statements; // Process exception type-2
}
:
:
catch ( Exception-type-N e)
{
Statements; // Process exception type-N
}
…………………………
…………………………
When exception in try block is generated, java checks exception object and catch block
parameter; if it matches, it will execute and remaining statements will be skipped.
Let's see a simple example of java multi-catch block.

Example:
public class TestMultipleCatchBlock{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e)
{System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e)
{System.out.println("task 2 completed");}
catch(Exception e)

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no- 135

{System.out.println("common task completed");}


System.out.println("rest of the code...");
} }
Output: task1 completed
rest of the code...

Finally Statement
finally creates a block of code that will be executed after a try/catch block has completed. The finally
block will execute whether or not an exception is thrown. If an exception is thrown, the finally block
will execute even if no catch statement matches the exception. It may be added immediately after the
try block or after the last catch block.
Syntax 1:
try
{
// statements
}
finally
{
// statements
}
Syntax 2:
try
{
// statements
}

catch (…………)
{
// statements
}
catch (…………)
{
// statements
}
finally
{
// statements
}

Prepared By: M.VENKAT(MCA, M-Tech) Lecturer in Computer Science


Page no-

Q). Write about throws Clause?


Even if the programmer is not handing runtime exceptions, the Java compiler will not give any error
related to runtime exceptions. But the rule is that the programmer should handle checked
exceptions.

In case the programmer does not want to handle the checked exceptions, he should throw them out
using throws clause. Otherwise, there will be an error flagged by Java complier.

Example program which shows the use of throws clause.

package demo;  
import java.io.*;  
public class Demo
 {  
  void checkout() throws IOException
 {  
  System.out.println("checking machine");  
 }  
 public static void main(String[] args) throws IOException 
{  
   Demo d = new Demo();  
   d.checkout();  
   System.out.println("successfully checked");  
 }  
}  

Q). Write about throw Clause ?


There is also a throw statement available in Java to throw an exception explicitly and catch it. Let us
see how it can be used. In the following program, we are creating an object of Null Pointer Exception
class and throwing it out of try block, as shown here:

throw new Null Pointer Exception ("Exceptiondata");

In the above statement, Null Pointer Exception class object is created and 'Exception data' is stored
into its object. Then it is thrown using throw statement. Now, we can catch it using catch block as:

Catch(Null Pointer Exception)


{
}

Program:Throw a null Pointer exception

//using throw
class Sample
{
static void demo()
{
try
{

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

System.out.println(“inseid demo()”);
throw new NullPointerException(“Excception data”);
}
catch(NullPointerException)
{
System.out.println()ne;
}
}
class ThrowDemo
{
public static void main(String args[])
{
Sample.demo();
}
}

Explain Re-throwing an Exception with example?


When an exception occurs in a try block, it is caught by a catch block. This means that the thrown
exception is available to the catch block. The following code shows how to re-throw the same
exception out from catch block:
try {
throw exception;
} catch (Exception job)
{ throw exception; //re-throw the exception out
}

Program: Write a program to throw the StringIndexOutOfBondsException.


//Rethrowing an exception.
class A
{
void methodl ()
{
try {
string str="Hello";
char ch= str.charAt (5);
}
catch(StringIndexOutOfBondsException sie)
{
System.out.println("please see the index is withing the range");
throw sie; // rethrow the exception
}
}
}

class B
{
public static void main (String args[])
{
A a= new A();
try {
a.methodl ()
}
catch(StringIndexOutOfBoundsException sie)
{
System.out.println ("I caught rethrown exception");
}
}
}

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Output:

Please see the index is within the range


I caught rethrow exception.

UNIT-4, THREADS

What is a Thread
“A thread is a lightweight sub process, and the smallest unit of processing”. It is a separate path of
execution. A thread is similar to a program that has a single flow of control. It has a beginning, a
body, and an end, and executes commands sequentially. In fact main program in our programs
can be called as Thread.

Threads in java are subprograms of a main application program, they can share the same
memory space, and saves the CPU time, they are known as Lightweight Processes or Lightweight
Threads.
All the threads are running on a single processor, the flow of execution is shared between the
threads.
Benefits of threads:
 It enables the programmers to do multiple things at one time.

 This approach will improve the speed of our programs.


 Any application requires two or more things to be done at the same time are
probably a best one to use is thread.

Multi thread (or) Main Thread

Main method
module

star star star


t t t

switchin switchin
g g

Thread A Thread B Thread C

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Fig: A multithreaded program


The main thread is actually the main thread module, which is designed to create and start the
other threads, namely A, B, and C. Once initiated by the main thread, the threads A, B, and C
concurrently and share the resources jointly.

Q). Explain about single tasking using a Thread?

A thread can be employed to execute one task at a time. Suppose there are 3 taks to be executed.
We can create a thread and pass the 3 tasks one by one to the thread.

For this purpose, we can write all these tasks separately in separate methods: task1(), task2(),
task3(). Then these methods should be called from run() method, one by one.

Remember, a thread executes only the code inside the run() method. It can never execute other
methods unless they are called i run ().

Program: Create single tasking use a thread.

class MyThread implements Runnable


{
public void run()
{
//execute the tasks one by one by calling the methods.
task1():
task2():
task3():
}

void task1()
{
System.out.println ("This is taks 1");
}

void task2()
{
System.out.println ("This is task 2");
}

void taxk3()
{
System.out.println("This is task 3");
}

class Single
{
public static void main(String args[])
{
MyThread obj= new MyThread();
Thread t1=new Thread(obj);
}
}

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

}
Output:
This is taks1
This is taks2
This is taks3

Q). Explain about Multi tasking using Threads

In multi tasking, several tasks are executed at a time. For this purpose, we need more than one
thread. For example, to perform 2 tasks, we can take 2 threads and attach them to the 2 tasks.
Then those tasks are simultaneously executed by the two threads. Using more than one thread is
called 'multi threading’.

When we go to a movie theatre, generally a person is there at the door-checking and cutting the
tickets. When we enter the hall, there is another person who shows the seats to us. Suppose there
is only one person (1 thread) doing these two tasks. He has to first cut the ticket and then come
along with us to show the seat. Then he goes back to the door to cut the second ticket and then
again enter the hall to show the seat for the second ticket. Like this, if he is does the things one by
one, it takes a lot of time, and even though the show is over, there will be still a few people left
outside the door waiting to enter the hall! This is pretty well known to the theatre management. So
what they do? They employ two persons (2 threads) for this purpose

The first person will cut the ticket, and the second one will show the seat. When the second person
is showing the seat, the first person cuts the second ticket. Like this, both the persons can act
simultaneously and hence there will be no wastage of time.

Program: Create a program showing two threads working simultaneously upon two objects.
//Two threads performing two tasks at a time-Theatre example
class MyThread implements Runnable
{
String str;
MyThreads(String str)
{
this.str=str;
}

public void run()


{
for(int i=1; i<10; i++)
{
System.out.println(str+":"+i);
try{
Thread.sleep(2000);
//cease thread execution for 2000 milliseconds
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
class Theatre
{
public static void main (String args[])
{

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

//create two objects to represent two tasks


MyThread obj1= new MyThread ("Cut the ticket");
MyThread obj2= new MyThread ("Show the seat");
//create two threads and attach them to the two objects
Thread t1= new Thread(obj1);
Thread t2= new Thread(obj2);
t1.start();
t2.start();
}
}
Output:

Cut the ticket: 1


Show the seat : 1
Cut the ticket: 2
Show the seat : 2
Cut the ticket: 3
Show the seat : 3
.......
Cut the ticket: 10
Show the seat : 10

Ways of Creating a Thread

New thread can be created in two ways.


1. By extending the class thread
2. By implementing the interface Runnable

1). Creating a new thread extending thread:

The first method of creating a thread is simply by extending the thread class. The Thread class is
defined in the package java.lang.Thread. This gives access to all the thread methods directly. It
includes the following steps:

1. Declare the class as extending the thread class.


2. Implement the run() method
3. Create a thread object and call the start() method

1. Declaring the Class: The Thread class can be extended as follows:

class MyThread extends Thread


{
……….
……….
……….
}

2. Implementing the run() Method :

The run() method has been inherited by the class MyThread. This method order to
implement the code to be executed by our thread. The basic implementation of run() will look
like this:

public void run()

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

{
………..
……….. // Thread code here
………..
}

When we start the new thread, Java calls the thread's run() method, so it is the run() method,
where all the action takes place.
3. Starting New Thread:

To actually create and run an instance of our thread class, we must write the following:
MyThread aThread = new MyThread( );
aThread. start(); // invokes run() method

The first line instantiates a new object of class MyThread. This statement just creates the
object. The thread is in a newborn state.
The second line calls the start() method causing the thread to move into the runnable state.

Example program:

import java.lang.*;
class A extends Thread
{
public void run()
{
for(int i=1;i<=5; i++)
{
System.out.println("\tFrom ThreadA: i=” +i);
}
System.out.println("Exit form A);
}
}

class B extends Thread


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

class ThreadTest
{

public static void main(String args[])


{
new A().start();
new B().start();
}
}

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

2). Creating a thread implementing Runnable interface:

The Runnable interface declares the run() method that is required for implementing threads in
our programs. To do this, we must perform the steps listed below.

1. Declare the class as implementing the Runnable interface.


2. Implement the run() method.
3. Create a thread by defining an object that is instantiated from this "runnable" class
as the target of the thread.
4. Call the thread's start() method to run the thread.

Example:
class XYZ implements Runnable
{
public void run()
{
for(int i=1;i<10; i++)
{
System.out.println("Thread XYZ:” +i);
}
System.out.println("End of ThreadXYZ");
}
}

class RunnableTest
{
public static void main(String args[])
{
XYZ runnable= new XYZ();
Thread tx=new Thread(runnable);
tx.start();
System.out.println(“End of main Thread”);
}
}

Q). Terminating a Thread? Explain.


A thread will terminate automatically when it comes out of run() method. To terminate the thread
on our own, we have to derive our own logic. For this purpose, the following steps can be used:

1. Create a boolean type variable and initialize it to false.

boolean stop=false;

2. Let us assume that we want to terminate the thread when the user presses <Enter> key. So,
when the user presses that button, make the boolean type variable as true

stop = true;

3. Check this variable in run() method and when it is true, make the thread return from the run()
method.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

public void run()


{
if (stop ==true)
return;
}
Program : How to terminate the thread by pressing the Enter button.

//To create a thread and run it, then stop it


import java.io.*;
class MyThread extends Thread
{
boolean stop = false;
public void run()
{
for (int i=1;i<=100000; i++)
System.out.println (i);
if(stop) return; //come out of run ()
}
}

class Demo1
{
public static void main(String args[]) throws IOException
{
MyThread obj = new MyThread();
Thread t = new Thread (obj);
t.start();
System.in.read();
obj.stop()=true;
}
}

Output:

Q). Explain about Multiple Threads Acting a Single Object?


First let us see why 2 threads should share the same object (same run() method). We write an
object to represent one task. If there is a different task, we take another object. When two
people (threads) perform same task, then they need same object (run() method) to be executed
each time.

Take the case of railway reservation. Every day several people want reservation of a berth for
them. The procedure to reserve the berth is same for all the people. So we need same object
with same run() method to be executed repeatedly for all the people (threads).

Let us think that only one berth is available in a train, and two passengers (threads) are asking for
that berth. In reservation counter no.1, the clerk has sent a request to the server to allot that
berth to his passenger. In counter no.2, the second clerk has also sent a request to the server to
allot that berth to his passenger. Let us see now see to whom that berth is allotted.

Program: Create a program showing two threads acting upon a single object.

//Thread unsafe-Two threads acting on same object

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

class Reserve implements Runnable


{
int available=1;
int wanted;
Reserve (int i)
{
wanted = i;
}
public void run()
{
System out.println ("Available Berths="+available);
if(available>= wanted)
{
string name= Thread.currentThread(). getName();
System.out.println(wanted+" Berths reserved for "+name);
try{
Thread.sleep(1500); // wait for printing the ticket
available =available - wanted;
}
catch (InterruptedException ie)
{}
} else System.out.println ("Sorry, no berths");
}
}

class Unsafe
{
Reserve obj = new Reserve (1);
Thread t1= new Thread (obj);
Thread t2= new Thread(obj);
t1.setName ("First person");
t2.setName ("Second person");
t1.start();
t2.start();
}

Output:

Available Berths = 1
1 Berths reserved for First Person
Available Berths = 1
1 Berths reserved for Second Person

Q). What Is Thread Deadlock?


A deadlock occurs when two or more threads wait forever for a lock (or) resource held by
another of the threads. Consequently, an application may stall (or) fail as the deadlocked threads
cannot progress.

Deadlock Example

First, let's take a look into a simple Java example to understand deadlock. In this example, we'll
create two threads, T1 and T2.  Thread T1 calls operation1, and thread T2 calls operations.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

To complete their operations, thread T1 needs to acquire lock1 first and then lock2, whereas


thread T2 needs to acquire lock2 first and then lock1. So, basically, both the threads are trying to
acquire the locks in the opposite order.

Now, let's write the DeadlockExample class:

1. public class TestDeadlockExample1 {  
2.   public static void main(String[] args) {  
3.     final String resource1 = "ratan tata";  
4.     final String resource2 = "vimal tata";  
5.         
6. Thread t1 = new Thread() {   // t1 tries to lock resource1 then resource2  
7.        public void run() {  
8.            synchronized (resource1) {  
9.             System.out.println("Thread 1: locked resource 1");  
10.   
11.              try { Thread.sleep(100);} 
12. catch (Exception e) {}  
13.    synchronized (resource2) {  
14.               System.out.println("Thread 1: locked resource 2");  
15.            }   }  }   };  
16.   
17.   Thread t2 = new Thread() {   // t2 tries to lock resource2 then resource1  
18.        public void run() {  
19.          synchronized (resource2) {  
20.            System.out.println("Thread 2: locked resource 2");  
21.   
22.            try { Thread.sleep(100);} 
23. catch (Exception e) {}  
24.            synchronized (resource1) {  
25.              System.out.println("Thread 2: locked resource 1");  
26.           }  }   }   };  
27.     t1.start();  
28.     t2.start();  
29.   }  }       

Once we run the program, we can see that the program results in a deadlock and never exits. The log
shows that thread T1 is waiting for lock2, which is held by thread T2. Similarly, thread T2 is waiting
for lock1, which is held by thread T1.

Avoiding Deadlock

Deadlock is a common concurrency problem in Java. Therefore, we should design a Java application
to avoid any potential deadlock conditions.

Q). Explain about thread communication?


In some cases, two or more threads should communicate with each other. For example, a
Consumer thread is waiting for a Producer to produce the data (or some goods). When the
Producer thread completes production of data, then the Consumer thread should take that data

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

and use it.

We improve the efficiency of communication between threads. Java.lang. Object class provides
3 methods for this purpose.

1. notify():

This method releases an object (obj) and sends a notification to a waiting thread that the
object is available.
Ex: public final void notify()  

2. notifyAll():
This method is useful to send notification to all waiting threads at once that the object (obj) is
available.
Ex: public final void notifyAll() 
 
3. wait():
This method makes a thread wait for the object (obj) till it receives a notification from a
notify() or notify All() methods. It is recommended to use the above methods inside a
synchronized block.

Method Description
public final void wait() throws InterruptedException It waits until object is notified.
public final void wait(long timeout) throws It waits for the specified amount of time.
InterruptedException

Q). Priority of a Thread (Thread Priority)


In java, each thread is assigned a priority, which affects the order in which it is scheduled for
running. The Threads of the same priority are given equal treatment by the java scheduler and,
therefore, they share the processor on a First-Come, First-Serve basis.

Java permits us to set the priority of a thread using the setPriority() method as follows.

ThreadName.setPriority(Number);

The Number is an integer value to which the threads priority is set. The Thread class defines several
priority constants of 3 types that is.

 public static int MIN_PRIOITY=1

 public static int NORM_PRIORITY=5

 public static int MAX_PRIORITY=10

The Number may assume one of these constants or any value between 1 and 10. The default setting
is NORM _ PRIORITY.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Whenever multiple Threads are ready for execution, the Java system chooses the highest priority
thread and executes it. For a thread of lower priority to gain control, one of the following things
should happen.

1. It stops running at the end of run().


2. It is made to sleep using sleep().
3. It is told to wait using wait().

Example of priority of a Thread:


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

public static void main(String args[]){


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

Q). Briefly explain about Thread Group?


A thread group represents several threads as a single group. The main advantage of taking several
threads as a group is that by using a single method, we will be able to control all the threads in the
group.

1. To create a thread group, we should simply create an object to ThreadGroup

class as:

ThreadGroup tg=new ThreadGroup("groupname");

Here, tg is the thread group object, and groupname is its name.


2. To add a thread to this group (tg);
Thread t1 = new Thread(tg, targetobj, "threadname");
Here, t1 thread is created and added to the thread group tg. This thread acts on targetobj,
which is the target object for the thread. The threadname represents the name of the thread
t1.
3. To add another tg1 = new ThreadGroup (tg, "groupname");

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Here we are creating and adding the thread group tg1 to the thread group tg. The name of the
added thread group is represented by groupname.
4. To know the parent of a thread or a thread group, we can use getParent().
tg.getParent ();
This method returns ThreadGroup object which is the parent of tg.
5. To know the parent thread group of a thread, we can use:
t.getThreadGroup();
This return a ThreadGroup object to which the thread t belongs.
6. To know the number of threads actively running in a thread group :
tg.setMaxPriority ();
Normally, the maximum priority of a thread group will be 10. But this method can set it as any other
number between 1 and 10.
Example: To demonstrate the creation of thread groups and some methods which act on thread
groups.
class TGroups
{
public static void main(String[] args) throws Exception
{
Reservation res = new Reservation ();
Cancellation can = new Cancellation ();

ThreadGroup tg= new ThreadGroup ("First Group");


Thread t1 = new Thread(tg, res, "First thread");
Thread t2 = new Thread(tg, res, "Second thread");

ThreadGroup tg1 = new ThreadGroup(tg, "Second Group");


Thread t3 = new Thread (tg1, can, "Third thread");
Thread t4 = new Thread (tg1, can "Fourth thread")

System.out.println ("Parent of tg1="+tg1.getParent());


tg1.setMaxPriority (7);
System.out.println("Thread group of t1="+t1.getThreadGroup());
System.out.println("Thread group of t1="+t3.getThreadGroup());
t1.start();
t2.start();
t3.start();
t4.start();
System.out.println("No of threads active in tg = "+tg.activeCount());
}
}

class Reservation extends Thread


{
public void run ()
{
System.out.println("I am reservation thread")
}
}
class Cancellation extends Thread
{
public void run ()
{
stem.out.println("I am cancellation thread");
}
}

Q). What is Daemon Threads?

A daemon thread is a thread that executes continuously. Daemon threads are service providers for
other threads (or) objects. It generally provides a background processing

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

1. To make a thread t as a daemon thread, we can use setDaemon() method as:


t. setDaemon(true);

2. 2 To know if a thread is daemon or not, isDaemon() is useful.

boolean x = t. isDaemon ();


If isDaemon() returns true, then the thread t is a daemon thread, otherwise not.

Lifecycle of a Thread (Thread states)


During the lifetime of a thread, there are many states it can enter. They include:
1) Newborn State
2) Runnable State
3) Running State
4) Blocked State
5) Dead State

A thread is always in one of these five states. It can move from one state to another via a variety
of ways as shown in below figure.

1. NewBorn State
When we create a thread object, the thread is born and is said to be in newborn state. The

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

thread is not yet scheduled for running. At this state, we can do only one of the following
things with it:
 Schedule it for running using start() method

2. Runnable State

The Runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. If all the threads have equal priority, then they are given time
slots for execution in first-come, first-serve manner. If we want a thread to relinquish (hand
over) control to another thread to equal priority before its turn comes, we can do so by using
the yield().

3. Running State

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

 It has suspended by suspend() method. A suspended thread can be revived by


using the resume() method.
 It has been made for sleep by using sleep() method. The thread re-enters the
runnable state as soon as this time period is elapsed.
4. Blocked State

A thread is said to be Blocked when it is prevented from entering into the runnable state
and subsequently the running state. This happens when the thread is suspended, sleping, or
waiting in order to satisfy certain requirements. A blocked thread is considered “not
runnable” but not dead and therefore fully qualified to run again.
5. Dead State

Every thread has a lifecycle. A running thread ends its life when it has completed executing
its run() method. It is natural death. However, we can kill it by sending the stop message to it
at any state thus causing a premature death to it. It is done by stop() method.

Q). Thread Class Methods


Before we begin with the programs(code) of creating threads, let’s have a look at these methods
of Thread class. We have used few of these methods in the example below.

1. getName(): It is used for Obtaining a thread’s name

Syntax: String getName()

2. getPriority(): Obtain a thread’s priority

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Syntax: setPriority(int priority)

3. isAlive(): Determine if a thread is still running

Syntax: boolean isAlive()

4. join(): Wait for a thread to terminate

Syntax: void join()

5. run(): Entry point for the thread

Syntax: void run()


{
//Thread ststement;
}
6. sleep(): suspend a thread for a period of time
Syntax: void sleep(long time-in milliseconds)

7. start(): start a thread by calling its run() method

Syntax: void start()

8. stop() stops the running thread

Syntax: void stop()

Thread class also defines many methods for managing threads. Some of them are,

Method Description
1)setName() to give thread a name
2)getName() return thread's name
3)getPriority() return thread's priority
4)isAlive() checks if thread is still running or not
5)join() Wait for a thread to end
6)run() Entry point for a thread
7)sleep() suspend thread for a specified time
8)start() start a thread by calling run() method
Returns an estimate of the number of active threads in
9)activeCount()
the current thread's thread group and its subgroups.
Determines if the currently running thread has
10) checkAccess()
permission to modify this thread.
Returns a reference to the currently executing thread
11) currentThread()
object.
Prints a stack trace of the current thread to the
12) dumpStack()
standard error stream.
13) getId() Returns the identifier of this Thread.
14) getState() Returns the state of this thread.
15) getThreadGroup() Returns the thread group to which this thread belongs.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Method Description
16) interrupt() Interrupts this thread.
17) interrupted() Tests whether the current thread has been interrupted.
18) isAlive() Tests if this thread is alive.
19) isDaemon() Tests if this thread is a daemon thread.
20) isInterrupted() Tests whether this thread has been interrupted.
21) setDaemon(boolean Marks this thread as either a daemon thread or a user
on) thread.
22) setPriority(int
Changes the priority of this thread.
newPriority)
A hint to the scheduler that the current thread is willing
23) yield()
to yield its current use of a processor.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

UNIT-4 STREAMS
Q). What is a Stream?. Concept of stream.

Java uses the concept of streams to represent the ordered sequence of data, a common
characteristic shared by all the input/output devices. A stream presents a uniform, easy-to-use,
object-oriented interface between the program and the input/ output devices.

A stream in Java is path along which data flows (like a river or a pipe along which water flows). It
has a source (of data) and a destination (for the data). Both the source and the destination may
be physical devices or programs or other streams in the same program.

Java streams are classified into two basic types, namely, input stream and output stream. An
input stream extracts (i.e., reads) data from the source (file) and sends it to the program.
Similarly, an output stream takes data from the program and sends (i.e. writes) it to the
destination (file). The program connects and opens an input stream on the data source and then
reads the data serially. Similarly, the program connects and opens an output stream to the
destination place of data and writes data out serially.

Q). Briefly explain about stream classes?

The java.io package contains a large number of stream classes that provide capabilities for
processing all types of data. These classes may be categorized into two groups based on the data
type on which they operate.

1. Byte stream classes that provide support for handling I/O operations on bytes.

2. Character stream classes that provide support for managing I/O operations on characters.

These two groups may further be classified based on their purpose. Figure below shows how
stream classes are grouped based on their functions

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

1. Byte Stream classes:

It was designed to provide functional features for creating and manipulating streams and files
for reading and writing bytes. Byte stream are defined by using two classes, InputStream and
OutputStream.

a. Input Stream classes:

InputStream classes that are used to read 8-bit bytes, include a super class known as
InputStream and a number of sub classes for supporting various input related functions.

b. OutputStream classes:

OutputStream classes that are used to write 8-bit bytes, include a super class known as
OutputStream and a number of sub classes for supporting various output related functions.
16-bit unicode character. There are two kinds of character stream classes namely

2. Character Stream classes:

Character streams can be used to read and write reader stream classes and writer stream
classes.

a. Reader stream classes:

Reader stream classes are designed to read character from the files. Reader class is the base
class for all other classes in this group.

b. Writer stream classes:

Writer stream classes are designed to write all output operation on files. Writer class is the
base class for all other classes in this group. We can also cross-group the streams based on
the type of source or destination they read from or write to. The source(or destination) may
be memory, a file or a pipe.

Q). How to create a file using FileOutputStream? Explain with example?

FileOutputStream class belongs to byte stream and stores the data in the form of individual
bytes. It can be used to create text files. We know that a file represents storage of data on a
second storage media like a hard disk or CD. The following steps are to be followed to create a
text file that stores some characters (or text)

i) First of all, we should read data from the keyboard. For this purpose, we should attach the
keyboard to some input stream class. The code for using DatalnputStream class for reading
data from the keyboard is as:

DataInputStream dis= new DataInputStream(System.in);

Here, System.in represents the keyboard which is linked with DataInputStreamm object, that is, dis.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

ii) Now, attach a file where the data is to be stored to some output stream. Here, we take the
help of FileOutputStream which can send data to the file. Attaching the file myfile.txt to
FileOutputStream can be done as

FileOutputStream fout=new FileOutputStream ("myfile.txt");

In the above statement, fout represents the FileOutputStream object.

iii) The next step is to read data from DataInputStream and write it into FileOutputStream. It
means read data from dis object and write it into fout object, as shown here:

ch= (char) dis.read(); //read one character into ch

fout.write(ch); //write ch into file

Finally, any file should be closed after performing input or output operations on it, else the
data of the file may be corrupted. Closing the file is done by closing the associated streams.
For example, fout.close(); will close the FileOutputStream, hence there is no way to write
data into the file. These steps are shown in Figure and implemented in Program

Example: Creating a text file using FileOutputStream

import java.io.*;
class CreateFile
{
public static void main (String args[]) throws IOException
{
DataInputStream dis = new DataInputStream (System.in);
FileOutputStream fout = new FileOutputStream ("myfile.txt");
System.out.println("Enter text (@at the end);");
char ch;
while ((ch=(char)dis.read()) != '@')
fout.write(ch);
fout.close();
}
}
Output:
CA> javac createfile java
C:\> java createfile
enter text (@ at the end);
This is my life line one
This is my life line two

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

@
C: type myfile.txt
This is my file line one
This is my file line two.

Q). Explain about Reading data from a file using FileInputStream with example?

FileInputStream is useful to read data from a file in the form of sequence of bytes. It is possible
to read data from a text file using FileInputStream. Let us see how it is done:

1. First, we should attach the file to a FileInputStream as shown here:

FileInputStream fin = new FileInputStream ("myfile.txt");

This will enable us to read data from the file. Then, to read data from the file, we should read
data from the FileInputStream as :

Ch= fin.read ();

When the read() method reads all the characters from the file, it reaches the end of the file.
When there is no more data available to read further, the read() method returns -1.

2. For displaying the data, we can use System.out which is nothing but PrintStream object.

System.out.print(ch);

3. Finally, we read data from the FileInputStream and write it to System.out. This will display all
the file data on the screen.

These steps are shown in Figure and implementd in Program

Example: // Reading textfile using FileInputStream


import java.io.*;
class ReadFile
{
public static void main(String args[]) throws IOException
{
FileInputStream fin=new FileInputStream("myfile.txt");
while ((ch=fin.read()) != -1)
System.out.print((char)ch);
fin.close();
}
}

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Output:

C:> java ReadFile.java


C:>java ReadFile File contents:
This is my third line
This is my file line four
This is last line

Q). Explain about writing character to a file and Reading character from a file with
examples.
(or)
Explain about File writer and FileReader classes with example?

Java provides two special types of stream called the FileReader and FileWriter to read
characters from file and write characters in to a file.

1. Writing characters to a file:

The FileWriter class can use to write characters to a file. FileWriter will create the file before
opening it for output when we create the object.

A FileWriter object can be created as follows:

FileWriter fo= new FileWriter(String filename); //Alternatively, it can be created as File


File Outfile = new File(String filename);
FileWriter fw= new FileWriter(outfile);

Methods of FileWriter class:

Method Description
1) public void write(String text) :writes the string into FileWriter.
2) public void write(char c) :writes the char into FileWriter.
3) public void write(char[] c) : writes char array into FileWriter.
4) public void close() : closes File Writer.

Example program for writing characters to a file:

import java.io.*;
class Simple {
public static void main(String args[])
{
try{
FileWriter fw= new FileWriter("abc.txt");
fw.write("my name is sachin");
fw.close();
}

catch(Exception e)
{System.out.println(e);}
System.out.println("success");
}

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Output: success...

2. Reading character from a file:

The FileReader class that we can use to read characters from a file. A FileReader object can be
created as follows

FileReader fi= new FileReader(String filename); //Alternatively, it can be created as


File infile = new File(string filename);
FileReader Fi= new FileReader(infile);

Methods of FileReader class:


Method Description

1) public int read() : returns a character in ASCII form. It returns-1 at the end of file.
2) public void close() : closes FileReader.

Example program for reading characters from a file :

import java.io.*;
class Simple {
public static void main(String args[]) throws Exception
{
FileReader fr = new FileReader ("abc.txt");
int i;
While(i=fr.read())!=-1)
System.out.println((char)i);
fr.close();
}
}

Output:
my name is sachin

Q). Explain about Zipping a File?

Let us now learn how to compress data in a file, say 'file' by following these steps:

i) Attach the input file 'file' to FileInputStream for reading data.

ii) Take the output file 'file2' and attach it to FileOutputStream. This will help to write data
into 'file2'.

iii) Attach FileOutputStream to DeflaterOutputStream for compressing the data.

iv) Now, read data from FileInputStream and write it into DeflaterOutputStream. It will
compress the data and send it to FileOutputStream which stores the compressed data
into the output file. These steps are shown in Figure and implemented in Program

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Example: //Compressing a file using a DeflaterOutputStream

import java.io.*;
import java.util.zip.*;
class Zip
{
public static void main (String args[]) throws Exception{
// FileInputStream for reading data
FileInputStream fis = new FileOutputStream("files1")
FileOutputStream fos=nes FileOutputStream ("file2")
DeflaterOutputStream dos = new DeflaterOutputStream(fos);
fis.close();
int data;
while ((data = fis.read()) != -1)
dos.write (data);
fis.close();
dos.close();
}

Output:
C:\> javac Zip.java
C:\> java Zip

Q). Explain about unzipping a file?

The file with the name 'file2' contains compressed data and suppose we want to obtain original
uncompressed data from this file. Let us follow these steps to data from this file.

i) Attach the compressed file 'file2' to FileInputStream. This helps to read data from 'file2'

ii) Attach the output file file3' to FileOutputStream. This will help to write uncompressed
data into 'file3".

iii) Attach FileInputStream to InflaterInputStream so that the data read from FileInputStream
goes into InflaterInputStream. Now InflaterInputStrea uncompresses the data.

iv) Now, read uncompressed data from InflaterInputStream and write it into
FileOutputStream. This will write the uncompressed data to 'file3'. These steps are shown
in Figure below and are implemented in Program.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Example: Program to uncompress data from a compressed file by using InflaterInputStream.

import java.io.*;
import java.util.zip.*;
class unzip
{
public static void main (String args[]) throws Exception
{
FileInputStream fis= new FileInputStream ("file2");
FileOutputStream fos= new FileOutputStream ("file3");
InflaterInputStream iis = new InflaterInputStream(fis);
int data;
while ((data = iis.read()) != -1)
fos.write(data);
fos.close();
}
}

Q). Briefly explain about serialization of Objects?

So far, we wrote some programs where we stored only text into the files and retrieved same
text from the files. These text files are useful when we do not want to perform any calculations
on the data.

For example, we want to store some employee details like employee identification number (int
type), name (String type), salary (float type) and date of joining the job (Date type) in a file. This
data is well structured and got different types. To store such data, we need to create a class
Employee with the instance variables id, name, sal, doj as shown here:

class Employee implements Serializable


{
//instance var
private int id;
private String name;
private float sal;
private Date doj;}

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Then create an object to this class and store actual data into that object. Later, this object
should be stored into a file using objectOutputStream. Observe that the Serializable interface
should be implemented by the class whose objects are to be stored into the file. This is the
reason why Employee class implements Serializable interface.

To store the Employee class objects into a file, follow these steps:

i) First, attach objfile to FileOutputStream. This helps to write data into objfile.

FileOutputStream fos = new FileOutputStream("objfile")

ii) Then, attach FileOutputStream to ObjectOutputStream.

ObjectOutputStream oos = new objectOutputStream(fos).

iii) Now, ObjectOutputSteam can write objects using writeObject() method to FileOutputStream,
which stores them into the objfile.

Storing objects into a file like this is called 'serialization'. The reverse process where objects can be
retrieved back from a file is called 'de-serialization'.

Program: Write a program to create Employee class whose objects are to be stored into a file.

//Employee class
import java.io.*;
import java.util.Date;
class Employee implements Serializable
{
private int id;
private Straing name;
private float sal;
private Date doj;
Employee (int i, String n, float s, Date d)
{
Id=i;
Name=n:
Sal=s;
Doj=d;
}
System.out.println(id+"\t"+name+"\t"+doj);
static Employee getData() throws IOExecption
{
BufferedReader br = new BufferedReader (new InputStreamReader (System.in);
System.out.print("Enter emp id: ") ;
int id= Integer.parseInt(br.readLine());
System.out.print ("Enter name: ");
String name = br.readLine();
Date d= new Date();

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Employee e= new Employee (id, name, sal, d);


return e;
}
}

Output:
C>javac Employee.java

Program: Write a program to show serialization of objects.


//objectoutputStream is used to store objects to a file
import java.io.*;
import java.util.*;
class StoreObj
{
public static void main (String args[]) throws Exception
{
BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
FileOutputStream fos = new FileOutputStream("objfile") ;
ObjectOutputStream oos = new ObjectOutputStream(fos) ;
System.out.print ("How may objects?") ;
int n = Integer.parseInt(br.readLine());
for (int i=0; i<n; i++)
{
Employee el-=Employee.getData();
oos.writeobject(el);
}
oos.close();
}
}

Output:
C: javac Storeobj.java
C>java Storeobj

How many objects ? 3


Enter emp id: 10
Enter name: Rohith
Enter salary: 9800.50
Enter emp id: 11
Enter name: Rohan
Enter salary: 8000.00

Q). Explain about counting number of characters in a File?

Write a program which accepts a filename from command line argument and displays the
number of charaters, words, and lines in the file.

//Counting no. of chars in a text file


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

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

{
int ch;
boolean prev= true;
int char_count=0; int line_count=0;
int word_count=0;
FileInputStream fin= new FileInputStream (args [0]);
while ((ch=fin.read()) != -1)
{
if (ch !=’ ‘) ++char_count ;
if (!prev && ch==' ')++word_count;
if (ch==' ') prev=true; else prev= false;
if (ch=='\n')++line_count;
}
char_count=line_count*2;
word count+=line_count;
System.out.println ("No. of chars="+char_count);
System.out.println("No. of words="+word_count);
System.out.println("No. of lines="+ line_count);
fin.close();
}
}

Output:
C:\> javac Count.java
C:\> java Count myfile No. of chars = 44
No. of words=12
No. of lines=6

Q). Briefly explain File copy with example?

Sometimes we need to copy the entire data of a text file into another text file. Streams are useful
in this case. To understand how to use streams for copying a file content to another file, we can
use the following logic:

i) For reading data form the input file, attach it to FileInputStream.

ii) For writing data into the output file, which is to be created, attach it to
FileOutputStream.

Example: Write a program to read the contents of the input file and write them into an output
file..

//Copying a file contents as another file.

import java.io.*;
class CopyFile
{
public static void main (String args[]) throws loXeception
{
int ch;
FileInputStream fin = new FileInputStream(args[0]);

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

FileoutStream fout = new FileoutputStream (args[0]);


while ((ch=fin.read ()) != -1)
fout.write (ch);
fin.close();
fout.close();
System.out.println("I file copied");
}
}
Output:
C: javac CopyFile.java
ile car gif carl1.gif
I file copied

Q). Briefly explain about File class and Methods with example?

1. File Class

File class of java.io package provides some methods to know the properties of a file or a
directory. First of all, we should create the File calss object by passing the filename or directory
name to it.

File obj =new File (filename);


File obj=new File (directoryname);
File obj=new File ("path", filenmae);
File obj = new File ("path", directoryname);

2. File Class Methods

File class includes the following methods:

1. boolean is File (): This method returns true if the File object contains a filename, otherwise
false.

2. boolean isDirectory(): This method returns true if the File objects contains a directory name.

3. boolean canRed (): This method returns true if the File object contains a file which is
rendable.

4. boolean can Write (): This method returns true if the file is writable.

5. boolean canExecute (): This method returns true if the file is executable.

6. boolean exists(): This method returns true when the File object contains a file or directory
which physically exists in the computer

7. String getParent (): This method gives the name of directrory path of a file or directory.

8. String getPath(): This method gives the name of directory path of a file or directory.

9. Stirng getAbsolutePath(): This method gives the absolute directory path of a file or directory
location. Absolute paaath is mentioned staarting from the root directory.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

10. long length(): This method returns a number that represents the size of the file in bytes.

11. boolean delete (): This method deletes the file or directory whose name is in File object.

12. boolean createNewFile(): This method automatically creates a new, empty file indicated by
File object, if and only if a file with this name does not yet exist.

13. boolean mkdir (): This method creates the directory whose name is given in File object.

14. boolean rename To (File newname): This method charges the name of the file as new name.

15. String[] list (): This method returns an array of strings naming the files and directories in the
directory.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

UNIT-5, Applet Programming


1. Applet
2. Applet Life cycle
3. Development of Applet
4. HTML tags

Applet
Applets are the small java programs that are primarily used for Internet computing. They can be
transported over the internet from one computer to another. They can be run using the applet
viewer (or) any web browser that supports java. An applet like any application program, can
perform arithmetic operations, display graphics, play sounds, accept user input, create
animation, and play interactive games.

Local and Remote Applets:


We can embed applets in two ways. One, we can write our own applets and store them into web
pages. “An applet developed locally and stored in a local system is known as local applet”. When
a web page is trying to find out a local applet, it does not need to use the internet and therefore
the local system does not require the internet connection

“A remote applet is that which is developed by someone else and stored on a remote computer
connected to the internet”. If our system is connected to the internet, we can download the
remote applet on to our system via internet and run it.

G. ANKAMMA RAO
How Applets differ from Applications
Applets are designed for the use on the internet. They impose certain Limitations and restrictions
in their design.
1. Applets do not use the main( ) method for initiating the execution of the code. Applets are
loaded automatically to call certain methods of applet class to start( ) and execute( ) the
applet code.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

2. Applets run from a web page by using HTML tag.

3. Applets cannot read from or write to the files in the local computer.

4. Applets cannot communicate with other servers on the network.

5. Applets cannot run any program from the local computer.

Applet Life Cycle


Every java applet inherits a set of default behavior from the Applet class. When an applet is
loaded, it undergoes a series of changes. The applet state includes
1. Born on initialization state.
2. Running state
3. Idle state
4. Dead or destroyed state.
These are represented as below:

Exit from browser

Fig: Applet’s state transition diagram


1) Born on Initialization State:
Applet enters the initialization state when it is first loaded. This is achieved by calling the init()
method of Applet class. The applet is born. At this stage, we may do the following, if required.
 Create objects needed by the applet.
 Set up initial values.
 Load images or fonts.
 Set up colors.
The initialization occurs only once in the applets life cycle. To provide any of the behaviors

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

mentioned above we must override the init( ) method.


public void init( )
{
----------------
----------------
}
2) Running State:

Applet enters the running state when the system calls the start( ) method of Applet class. This
occurs automatically after the applet is initialized. Starting can also occur if the applet is
already in “stopped” (idle) state. The start( ) method may be called more than once.
public void start()
{
-----------------
-----------------
}

3) Idle or Stopped State:


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

----------------
----------------
}
4) Dead State:
An applet is said to be dead when it is removed from the memory. This occurs automatically
by invoking the destroy ( ) method destroying occurs only once in the life cycle.
If the applet has created any resources, like threads. We may override the destroy( ) method
to clean
up these resources.
public void destroy( )
{
----------------
----------------
}
Display State:
Applet moves to the display state whenever it has to perform some output operations on the
screen. paint( ) method is used to accomplish the task. The default version of paint( ) method
does absolutely nothing we must override this method .
public void paint(Graphics g)
{
----------------
----------------
}
It is to be noted that the display state is not considered as a part of applet’s life cycle. This
method is inherited from the Component class a super class of the applet class.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Development of the applet(Building, create executable, design, Runnable)

These steps involved in developing and testing in applet are:


1. Building an applet code.
2. Creating an executable applet.
3. Designing a Web page using HTML tags.
4. Preparing <APPLET> tag.
5. Incorporating <APPLET> tag into the web page.
6. Creating HTML file.
These steps are explained as follows;

1) Building an applet code:

The Applet class which is contained in the java.applet package provides life and behavior to
the applet through its methods such as init ( ), start( ) and paint( ).

Unlike the applications which calls the main( ) method directly to initiate the execution of a
program, when applet is loaded, java automatically calls a series of Applet class methods for
starting, running, and stopping the applet code. the applet code is executed when an applet is
loaded.
The paint( ) method of the Applet class, when it is called, actually displays the result of the
applet code on the screen. The output may be text, graphics, or sound. The paint( ) method
requires the Graphics class object as an argument.

This requires that the applet code imports the java.awt package that contains the Graphics
class. All the output operations of a class are performed using the methods defined in the
Graphics class.
Applet will have a general format as shown below.
import java.awt.*;
import java.applet.*;
---------------
----------------
public class <applet class name> extends Applet
{
public void paint(Graphics g)
{
------------------- // Applet operation code
-------------------
}
}

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

The <applet class name> is the main class for the Applet. When the applet is loaded, Java
creates an instance of this class and a series of applet class methods are called on that
instance to execute the code.
Example:
import java.awt.*;
import java.applet.*;
public class HelloJava extends Applet
{
public void paint(Graphics g)
{
g.drawString(“Welcome to Java World”,10,100);
}
}
This should be saved with the filename HelloJava .java. The main Applet class must be
declared public. When drawstring is executed, draws the string Welcome Java at the position
10, 100 (pixels) of applet reserved space.

2). Creating an Executable Applet:


Executable applet is nothing but the .class file of the applet, which is obtained by compiling
the source code of the applet. The applet programming can be compiled using the command
called javac.
Syntax: Javac <file-name>.java

Example:

The compiled output file called HelloJava.class is placed in the same directory as the source.

3). Designing a Web-Page:


A web page is basically made of HTML tags and text. A web page is also known as a HTML
page. Web pages are stored with the extension called .html. Such files are referred to as
HTML files. A web page is marked by an opening HTML tag <HTML> and a closing </HTML>.
This is divided into the following three major sections.
1. Comment section (optional)
2. Head section (optional)
3. Body section.
A web page outline containing these three sections would look like as follows.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

<HTML
>
<!
…………………………
………………………… Comment Section
>

<HEAD>
<TITLE >.............
</TITLE> Head Section
</HEAD>
<BODY>
<APPLET............. > Body Section
</APPLET>
<BODY>
</
HTML>

Fig: Web Page Template

a) Comment section:
This section contains comments about the web page. It is useful to prepare notes. A comment
line begins with a <! and ends with a >. Web browsers ignore the text enclosed between
them.
b) Head section:
The head section is defined with a starting <HEAD> tag and a closing </HEAD> tag. This
section contains a title for the web page as shown below.
<HEAD>
<TITTLE>
welcome to java applets
</TITTLE>
</HEAD>
The text enclosed in the tags <TITLE> and </TITLE> will appear in the title bar of the web
browser when it displays the page. A slash ( / ) in a tag signifies the end of that tag section.
c)Body Section:
After the head section body section appears. This section contains the entire information
about the web page and its behaviour. We can set up many options to indicate how our page
must appear on the screen like color, location, sound etc.
<BODY>
<CENTER>
<H1>
Welcome to the world of applets
</H1>
</CENTER>
<APPLET>
</APPLET……>

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

</BODY>

4) Creating Applet Tag:


This supplies the name of the applet to be loaded and tells the browser how much space the
applet requires. The ellipses in tag <APPLET ……> indicates that it contains certain attributes
that must specified. The following are the minimum requirements to place the hellojava
applet on a web page.
<APPLET
CODE=”HelloJava. Class”
WIDTH=400
HEIGHT=200>
</APPLET>

The HTML code tells the browser to load the compiled hellojava.class, which is in the same
directory as the HTML file. This also specifies the display area for the applet output as 400
pixels width, 200 pixels height.
The Applet tag specifies three things.
 Name of the Applet
 Width of the Applet
 Height of the Applet.

5). Adding Applet to HTML file:


1. Various components of a web page can be put together and a file can be created.
This is known as HTML file.
2. Insert the <APPLET> tag in the page at the place where the output of the applet must
appear. Following is the content of the HTML file that is embedded with the
<APPLET> tag of our hellojava applet.
<HTML>
<! This page includes a welcome title in the title bar and displays message>
<HEAD>
<TITLE>
Welcome to java applets
</TITLE>
</HEAD>
<BODY>
<H1>
Welcome to the world of applets
</H1>

<APPLET>
CODE=”HelloJava.class”
WIDTH=400 HEIGHT=200>
</APPLET>

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

</BODY>
</HTML>
And finally save HTML file with the name HelloJava.html.

Running the Applet:


Now that we have created applet files as well as HTML file containing the applet, we must
have the following files in our current directory.
HelloJava.java
HelloJava.class
HelloJava.html
To run an applet we require one of the following tools.
1. Java Enabled Web Browser.
2. Java Applet Viewer.

If we use a java-enabled web browser, we will be able to see the entire web page containing
the applet. We can use it to run applet; just double click on the HelloJava.html file or open
with a web browser (ex: Internet Explorer, google chrome etc.)

If we use the appletviewer tool, we will only see the applet output. Applet viewer is available
as a part of Java Development Kit (JDK). We can use it to run applet as follows:
Appletviewer HelloJava.html

Aligning the display


The output can be aligned using the attributes values Left, Right, Top, Middle, and Bottom.
For example: Align-Left will display the output at the left margin of the page.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

<HTML>

<HEAD>
<TITLE>

Here is an Applet
</TITLE>

</HEAD>

</BODY>
<APPLET CODE= HelloJava.class WIDTH=400 HEIGHT=200 ALIGN=RIGHT>

</APPLET>

</BODY>
</HTML>

The alignment of the applet is seen when it is run.

HTML Tags
1. <HTML> …. </HTML> : Specifies the beginning and end of the file.
2. <HEAD> …. </HEAD> : This tag includes the details about the web page.
3. <TITLE> …. </TITLE> : displays title.
4. <BODY> ….. </BODY> : This contains the main text of the web page. This is the
place where the applet tag is declared.
5. <H1> ….. </H1> : Header tags: These are used to display the headings.
6. <H6> ….. </H6> : Creates the smallest tag.
7. <CENTER> …… </CENTER> : places the text contained at the centre of the page.
8. <PARAM> : supplies user-defined parameter using <PARAM> tags. The PARAM tag is
allowed only in the <Applet> tag.
9. <B> …. </B> : Text between these tags will be displayed in bold type.
10. <BR> : Line break.

Write a java program to illustrate about applet life cycle methods


Since applets are running in the browser, the class Applet contains the life cycle methods. Life cycle
methods are also called as loop back methods.
The Applet life cycle methods are as follows….
 public void init()
 public void start()
 public void stop()
 public void destroy()

a) MyAppAll.java
import java.awt.*;
import java.applet.*;
public class MyAppAll extends Applet
{
String msg = " ";
public void init()
{
setForeground(Color.yellow);

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

setBackground(Color.red);
Font f = new Font("Arial", Font.BOLD, 30);
setFont(f);
msg += " init";
}

public void start()


{
msg += "start";
}
public void stop()
{
msg += "stop";
}

public void destroy()


{
msg += " destroy";
}
public void paint(Graphics g)
{
msg += " paint"; g.drawString(msg, 50, 50);
}
}
Compile as > javac MyAppAll.java

b) HTML code with Applet Tag


<HTML>
<APPLET>
CODE=”MyAppAll.class”
WIDTH=300 HEIGHT=300
</APPLET>
</HTML>

Save : MyAppAll.html Output:

Q). Animation in Applet


Applet is mostly used in games and animation. For this purpose image is required to be
moved

Example of animation in applet:

import java.awt.*;  
import java.applet.*;  
public class AnimationExample extends Applet 
{  
  Image picture;  
  public void init() 
{  
     picture =getImage(getDocumentBase(),"bike_1.gif");  
   }  
   public void paint(Graphics g) 
{  
     for(int i=0;i<500;i++)

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

{  
       g.drawImage(picture, i,30, this);  
         try{Thread.sleep(100);}
catch(Exception e){}  
     }  
   }  
}  

In the above example, drawImage() method of Graphics class is used to display the image.
The 4th argument of drawImage() method of is ImageObserver object. The Component class
implements ImageObserver interface. So current class object would also be treated as
ImageObserver because Applet class indirectly extends the Component class.

myapplet.html

<html>  
<body>  
<applet code="DisplayImage.class" width="300" height="300">  
</applet>  
</body>  
</html>  

Q). Passing Parameters to Applets

Parameters specify extra information that can be passed to an applet from the HTML page.
Parameters are specified using the HTML’s param tag

Param Tag

The <param> tag is a sub tag of the <applet> tag. The <param> tag contains two
attributes: name and value which are used to specify the name of the parameter and the value of
the parameter respectively. For example, the param tags for passing name and age parameters
looks as shown below:

<param name=”name” value=”Ramesh” />

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

<param name=”age” value=”25″ />

Now, these two parameters can be accessed in the applet program using
the getParameter() method of the Applet class.

getParameter() Method

The getParameter() method of the Applet class can be used to retrieve the parameters passed


from the HTML page. The syntax of getParameter() method is as follows:

String getParameter(String param-name)

Let’s look at a sample program which demonstrates the <param> HTML tag and
the getParameter() method:

import java.awt.*;
import java.applet.*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
g.drawString("Name is: " + n, 20, 20);
g.drawString("Age is: " + a, 20, 40);
}
}
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/
Output of the above program is as follows:
 

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

JAVA Database Connectivity

Q). Write about Database servers?


Database Servers:
A database is a repository of data. We can store data permanently in a database and retrieve it later
whenever needed by using some query commands.

Databases like Oracle, Sybase, MySQL and SqlServer are in use now a day. Data is stored generally in the
form of tables in these databases. To retrieve data from the tables we need some program. This program
is called 'database client' program. To understand the database client, let us take an example. If oracle
10g is installed in your computer, go to 'Start' menu and click.

Start-> Programs -> Oracle Database 10g Express Edition-> Run SQL command

It opens a window at DOS prompt where SQL> prompt appears. Types connect and, it asks to enter user-
name and password. Type 'scott' and 'tiger' as default values. Then you would be connected to the oracle
database. This application is called SQL*Plus which is a client program to connect to the oracle server at
any moment.

Q). Explain about Database clients?

Database clients:

Using SQL Plus application, it is possible to store data into oracle database. Also retrieving the data as
well as updating it is also possible. Since, SQL*Plus is retrieving data from the oracle server in your
system, SQL*Plus is called database client and oracle database is called database server. Now type a
query as:

SQL> select from tab;

It displays all the tables available in oracle database. Press Control+Alt+Del to see Task Manager Dialog
box, where you can spot out Oracle.exe file running in your system. This is nothing but the oracle
database.

It is possible to load SQL*Plus client software in a system and the oracle database server program in
another system connected on a network. The client will be able to connect to the database server and
retrieve the data on the network.

Similarly, MySQL is a database. To connect to this database,

go to Start -> MySQL >> MySQL Server 5.0> MySQL Command line client. It asks for password, where you
type: 'root' at DOS prompt. Now you can see the screen shown in the figure.

To see the names of databases in MySQL, give the following command: mysql show databases;
To come out of MySQL, we can type quit at mysql>prompt.

SQL*Plus or MySQL client programs connect to database servers and retrieve the data from them. The
same thing can be done through a Java program which connects to a database and retrieves data from it.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

This technology is called Java Database Connectivity (JDBC).

Q). Write about Java Database Connectivity (JDBC)?

JDBC (Java Database Connectivity): JDBC is an API (Application Programming Interface) that helps a
programmer to write Java programs to connect to a database, retrieve the data from the database and
perform various operations on the data in the Java program.

Every database vendor will provide a document representing all the commands to connect and utilize the
database features. This document is called 'API (Application Programming Interface) document'. API
document is a file that contains description of all the features of a software, a product or a technology.

For example, the vendor of oracle database has given the following information for the programmers
who use his product, in his API document:

1. To connect to oracle database, use oLog() function.


2. To execute a command, use oexec() function.
3. To disconnect from oracle, use oLogoff() function.

If the same programmer wants to work with MySQL database, he should learn the syntax and usage of
functions provided by MySQL vendor in his API document.

For example,

1. To connect to MySQL database, use mysql_connect() function.


2. To execute a command, use mysql_execute() function.
3. To disconnect from MySQL, use mysql_disconnect() function.

By using these functions of this common API document, programmers can communicate with any
database in the world. Such a document is called ODBC (Open Database Connectivity) API.

“ODBC is a document that contains common functions to communicate with any database”. It is created
by Microsoft Corporation. If any organization creates a software depending on this ODBC document, it is
called ODBC driver.

In the same way, Sun Microsystems Inc. has also created an API document named JDBC (Java Database
Connectivity) API and the actual software which is created according to JDBC API, is called JDBC driver,
JDBC API is defined in java.sql package. This package contains interfaces like Connection, Statement,
ResultSet, ResultSetMetaData, PreparedStatement, Driver, CallableStatement and classes like Date,
Time, DriverManager etc. Several companies have started developing software containing these
interfaces and classes. These software are called JDBC drivers.

Q). Explain about working with oracle Database?


Working with Oracle Database:
Oracle is the most popular database all over the world. After connecting to oracle database, SQL>prompt
appears where you should enter SQL (Structured Query Language) commands. Let us see how to use SQL
commands to do certain useful tasks on the Oracle database.

SQL> select * from tab;

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

TNAME TABTYPECLUSTERID
ACCOUNT TABLE
DEPT TABLR
EMP TABLE
SALGRADE TABLE

4 rows selected.

1) Suppose, we want to create a table with the name 'emptab' with 3 columns: eno (int type), ename
(String type) and sal(float type), we can type SQL command as:

SQL> create table emptab (eno int, ename varchar2(20), sal float);
Table created..
2) To see the information about the table created by us, we can use description command, as:

SQL> desc emptab;


Name Null Type
ENO INT;
ENAME VARCHAR2(20);
SAL FLOAT;

3) To store data into the table 'emptab'. For this purpose, we should use 'insert' command as:

SQL> insert into emptab values(&eno, '&ename', &sal);

Enter value for eno: 10


Enter value for ename: Subba Rao
Enter value for sal: 8900.95

old 1: insert into emptab values(&eno, '&ename', &sal)


new 1: insert into emptab values(10, 'Subba Rao', 8900.95)
1 row created.

In this way, we can store rows into empty table. To save all entered rows into the table, we can use
'commit' command, as:

SQL> commit;

4) To see all the rows of our emptab, we should use 'select' command in the following way:

SQL> select from emptab;

ENO ENAME SAL


10 Subba rao 8900.95
11 Gopal 5600.55
12 Laxmi 5000
13 Nitin Prakesh 1200

5) Now update the salary of an employee in emptab. Let us increase the salary by Rs.1000 to the
employee whose eno is 11.

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

SQL> update emptab set sal = sal + 1000 where eno 11;
1 row updated.

6) If we want to delete an employee row whose eno is 10:


SQL> delete from emptab where eno=10;
1 row deleted.

7) To save all the changes into the database, we can use to 'commit' command. Similarly, to un-save the
changes, 'rollback' can be used.
SQL> rollback;
Rollback completed.

8) Now we will close the SQL client giving 'exit":


SQL> exit;
The commands we used are called SQL commands. The same commands can be used on any other
database with slight modifications.

Q). Explain working with MySQL Database?


Working with MySQL Database:
MySQL is a free database software provided by mysql.com. We can create only one database in oracle,
but in MySQL, it is possible to create multiple databases. After going into MySQL, we can see mysql>
prompt where we should enter commands.

1) To see what databases are existing in MySQL, give the following command:
mysql> show databases;
Database
Mysql
test

The above output means that there are 2 databases currently available in MySQL and they are: mysql
and test.

2) Let us see which tables are available in the database 'test'. We should first enter test database, as:
mysql> use test;
Database changed

Now, to see the tables in test database,


mysql> show tables;
Table_in_test
emp
mytab
student

3) To create a table with the name 'emptab' in test database. eno, ename and sal are the columns in
emptab.
mysql> create table emptab (eno int, ename char(20), sal float);
Query OK, 0 rows affected

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

4) To see the description of emptab by giving 'desc' command.


mysql>desc emptab;

Field Type Null Key Default Extra


eno int(11) YES Null
name char(20) YES Null
sal float YES Null

3 rows in set

5) Let us now store some rows into emptab.


mysql> insert into emptab values(1001, "Nagesh", 7800);
Query OK, 1 row affected
mysql> insert into emptab values(1002, "Ganesh", 10000.00);
In this way, we can store some rows into emptab.

6) To see all the rows of the table, we can use select query as:
mysql> select from emptab;
eno ename sal
10 Nagesh 7800
11 Ganesh 10000
12 Vinaya 5000.55
13 Rahul 7800

4 rows in set
7) Suppose we want to retrieve employees names whose salary is Rs.7800.
mysql> select ename from emptab where sal = 7800;
ename
Nagesh
Rahul

2 rows in set

8) Suppose we want to delete the row of an employee whose employee number is 10.
mysql> delete from emptab where eno = 1001;
Query OK, 1 row affected

9) To update the salary to Rs.15000 of an employee whose name is "Rahul",


mysql> update emptab set sal = 15000 where name="Rahul";
Query OK, 1 row affected
Rows matched: 1 changed: 1 warnings: 0

10) Finally, to close MySQL, we can give 'quit' command to see the system prompt, as:
mysql> quit;

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

Q). Write the database programming using JDBC? or write various stages in a
database program?
Database programming using JDBC: JDBC APIs are used by a Java application to communicate with a
database. In other words, we use JDBC connectivity code in Java application to communicate with a
database.
There are 6 steps to connect any Java application with the database in Java using JDBC. They are as
follows:
1. Register the Driver class
2. Create connection
3. Create statement
4. Execute queries (or)Retrieving the result.
5. Close connection

Step 1: Registering the Driver:


This is the first step to connect a database. A programmer should specify which database driver he is
going to use to connect to the database. There are 4 ways to register a driver.

1. By creating an object to driver class of the driver software, we can register the driver. For example, to
register JdbcOdbcDriver of the Sun Microsystems, we can create an object to the driver class:
JdbcOdbeDriver, as shown below:

sun.jdbo.odbc.jdbcOdbcDriver obj = new sun.jdbc.odbc.JdbcOdbcDriver();

2. The second way to register a driver is by sending the driver class object to registerDriver() method of
DriverManager class.
DriverManager.registerDrive (new sun.jdbc.odbc.JdbcOdbcDriver());

3. The third way to register the driver is to send the driver class name directly to forNasme() method,
as:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

4. In case, the user should specify the driver name at the time of running the program, we can use
getProperty() method of System class to receive the driver name, as:
String dname= System.getProperty("driver");
Class.forName(dname);

Step 2: Connecting to a Database:

The getConnection() method of DriverManager class is used to establish connection with the


database.
Syntax:

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

1) public static Connection getConnection(String url)throws SQLException  
2) public static Connection getConnection(String url,String name,String password)  throws SQLException  

Example:
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");  

Step 3: Creating statement:


After the connection made, we need to create the statement object to execute the SQL statements.
The create statement() method of connection interface is used to create statement. This statement
object is responsible to execute SQL statements with the database.

Syntax of createStatement() method

public Statement createStatement()throws SQLException  

Example to create the statement object

Statement stmt=con.createStatement(); 

Step 4: Executing SQL statements:


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.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException  

Example to execute query


ResultSet rs=stmt.executeQuery("select * from emp");    
while(rs.next()){  
System.out.println(rs.getInt(1)+" "+rs.getString(2));  
}  

Step 5: Close Connection:


Last but not least, finally we need to close the connection object. It is very important step to close the
connection. Else we may get JDBCConnectionException exception. con.close()

Program: This is a program to retrieve all the rows from emptab of oracle database. //To retrieve data
from Oracle database import java.sql.*;
import java.sql.*;
class OracleCon{
public static void main(String args[])
{
try{
//step1 load the driver class 
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create  the connection object  

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

//step3 create the statement object  

Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object  
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

(Two ways to load the jar file:


1. paste the ojdbc14.jar file in jre/lib/ext folder
2. set classpath

1) paste the ojdbc14.jar file in JRE/lib/ext folder:


Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
There are two ways to set the classpath:
o temporary

o permanent
How to set the temporary classpath:
Firstly, search the ojdbc14.jar file then open command prompt and write:
C:>set classpath=c:\folder\ojdbc14.jar;.;  
How to set the permanent classpath:

Go to environment variable then click on new tab. In variable name write classpath and in variable value paste the path to

ojdbc14.jar by appending ojdbc14.jar;.; as C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;. )

Output:
C:\> set classpath=C:\jars/ojdbe 14.jar;.;
C:\> javac OracleData.java
C:\> java Oracle Data
1001
Nageswara Rao
7800.55
1002
Vijay kumar
6000.0

Q). How to use Jdbc-Odbc Bridge driver to connect oracle database?


Using jdbc-odbe Bridge Driver to Connect to Oracle Database: Sun Microsystems Inc. provides a default
driver called jdbc-odbe bridge driver along with Java software that is useful to connect to any database.
Let us see how to use this driver with oracle database.

Step 1: First of all, we should create a DSN (Data Source Name) that represents the name for the
database, by clicking on the Start button and following the

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

path: Start > Settings> Control Panel -> Administrative tools Data Sources (ODBC).

We can find ODBC Data Source Administrator dialog box as shown in Figure.

Step 2: In this dialog box, select User DSN tab and click the Add button at right side. Now the list of
drivers available will be displayed in a separate dialog box. Select Microsoft ODBC for Oracle driver in the
list and click the Finish button.

Step 3: Now, you can see Microsoft ODBC for Oracle Setup dialog box appears. Type the DSN name and
user name and then click the OK button, as shown in Figure.

Now, we can verify that a new DSN with the name 'nitin' has been created in UserDSN tab. Click the OK
button to close the ODBC Data Source Administrator.

After creating the DSN name as shown above, the next thing we should do is to register the driver. To
register Sun's jdbc-odbc bridge driver, we can use the following statement in our program:

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

DriverManager. registerDriver (new sun.jdbc.odbc.JdbcOdbcDriver());

To connect to the database, using this driver, we can write:

Connection con = DriverManager.getConnection("jdbc.odbe:nitin", "scott", "tiger");

Here, nitin is the DSN name that we have just created, scott is the username and tiger is the password.

Program: Let us see how to use Sun's jdbc-odbe to oracle database and retrieve all the rows from
emptab.

//To retrieve data from oracle database using jdbc-odbe bridge driver
import java.sql.*;
class OracleData
{
public static void main (Strig args[]) throws Exception
{
//Register the driver
DriverManager.registerDriver (new sun.jdbc.odbc.JdbcOdbc Driver());
//Establish connection with the database
Connection con = DriverManager.getConnection("jdoc:odbc:nitin", "scott", "tiger");
//Create a SQL statement
Statement stmt = con.CreateStatement();
//Execute the stmt
ResultSet rs = stmt.executeQuery("Select from emptab");
while(rs.next()){
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getFloat(3));
System.out.println(".......");
//close the connection
con.close();
}
}

Output:
C:> javac OracleData.java
C: java OracleData
10
Nageswara Rao 7800.55
1002
Vijay Kumar
6000.0

Q). How to retrieving Data from MS Access Database? Explain.


Retrieving Data from MS Access Database: Microsoft Access is also one of the databases used by many
organizations. We can create a database in MS Access and create tables in the database. For this, select
the options:

Start > Programs -> Microsoft office -> Microsoft Access -> Create a new file - Blank database
File New Database dialog box will be displayed as shown in Figure. Type the database name as 'Mydb' in a

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

directory, for example, D:\rnr. Then click the Create button.

When we enter the MS Access, a dialog box is displayed where double click 'Create table by entering
data' option. This is shown in Figure.

Then, we will see a spread sheet with several rows and columns where we can enter column names in
the table and column data as shown in Figure. Rename Field 1 as eno, Field 2 as ename and Field 3 as sal.
Then enter data.

Then select File -> Save option and Enter Filename as 'emptab' and then click OK button.

MS Access prompts us to enter a primary key. Click on 'NO' button. And close the table. Come out of MS
Access now.

To connect to MS Access, we can use Sun Microsystems 'jdbc-odbe bridge driver. To use this driver, it is
necessary to create a DSN (Data Source Name) by going to Start
Settings-> Control Panel -> Administrative Tools> Data Sources (ODBC).

We can find ODBC Data Source Administrator dialog box where select User DSN tab and click the Add
button at right side. Now the list of drivers available will be displayed in a separate dialog box. Select
Microsoft Access (*.mdb) driver in the list and click Finish button. It displays ODBC Microsoft Access Setup
dialog box as shown in Figure. In this box, enter:

Data Source Name : accdsn


Then click the Select button to select the database. Then select the directory with the name: D:\rar
where mydb.mdb will appear. Click on that directory. Then click the OK button and you will come back to
ODBC Microsoft Access Setup dialog box where you click OK button and close it.

Now DSN is created, we can mention it while connecting it to MS Access database, as:

Connection con= DriverManager.getConnection("jdbc:odbe:accdsn","","");


Here, no need to give username and password. So, we just used "" and "" in these places.
Program: In this program, we connect to MS Access database and retrieve the data from emptab.

//To retrieve data from MSAccess database


import java.sql.*;
class AccessData
{
public static void main (String arg[]) throws Exception
{
//Register the driver
DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbeDriver());
//Establish connection:
connection Con=DriverManager.getConnection("jdbc:odbc:accdsn","","");
//Create a SQL statement
Statement stmt = con.createStatement();
//Execute the stmt
ResultSet rs = stmt.executeQuery ("select * from emptab");
//retrieve from ResultSet and display column data
while(rs.next()){

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science


Page no-

System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
System.out.println(rs.getFloat(3));
System.out.println("-------------“);
}
}
}

Output:
C:\> javac AccessData.java
C:\> java AccessData
1001
8900.0
1002
Nageswara Rao
Vijaya 9000.9

Prepared by M.VENKAT (MCA, M-Tech) Lecturer in Computer Science

You might also like