Vous êtes sur la page 1sur 130

Software Evolution: Earnest Tello a well-known writer compared the evolution of software technology to

the growth of a tree.


1, 0
Machine Language
Assembly Language
Procedure Programming
Object-oriented Programming

Procedure Oriented Programming: High level languages such as COBOL, FORTRAN and C are commonly
known as procedure-oriented programming. In the procedure-oriented approach, the problem is viewed
as a sequence of things to be done, such as reading, calculating and printing. Procedure-oriented
programming basically consists of writing a list of instructions into groups known as functions.

Characteristics:
1. Emphasis is on doing things (algorithms)
2. Large programs are divided into smaller programs known as functions
3. Most of the functions share global data
4. Functions transforms data from one form to another
5. Employs top-down approach in program design.

Object Oriented Paradigm: The major objective of object-oriented approach is to eliminate some of the
flaws encountered in the procedural approach.

Object-Oriented Programming: OOP treats data as a critical


element in the program development and does not allow it to
flow freely around the system. It ties data more closely to the
functions that operate on it and protects it from accidental
modification from outside functions. OOP allows us to
decompose a problem into a number of entities called objects
and then builds data and functions around these entities. The
combination of data and methods make up an object.
Features:
1. Emphasis is on data rather than procedure.
2. Programs are divided into what are known as
objects.
3. Data is hidden and cannot be accessed by external
functions.
4. Objects may communicate with each other though
functions.
5. New data and functions can be easily added whenever necessary.
6. Follows bottom-up approach in program design.

Definition: Object-oriented programming is an approach that provides a way of modularizing programs


by creating partitioned memory area for both data and functions that can be used as templates for
creating copies of such modules on demand.

mnnappaji@gmail.com
1
Basic Concepts of Object-Oriented Programming

1. OBJECTS 2. CLASSES
3. DATA ABSTRACTION 4. DATA ENCAPSULATION
5. INHERITENCE 6. POLYMORPHISM
7. DYNAMIC BINDING 8. MESSAGE COMMUNICATION

1. Objects: Objects are the basic run-time entities in an object-oriented system. They may represent a
person, a place, a bank account, a table of data or any item that the program must handle. Programming
problem is analyzed in terms of objects. When a program is executed, the objects interact by sending
messages to one another. For example if customer and account are two objects in a program, then the
customer object may send message to the account object requesting for the bank balance. Each object
contains data and code to manipulate the data.
---------------------------------------------------
Object : STUDENT
---------------------------------------------------
DATA
Name
Date-of-birth
Marks
---------
---------------------------------------------------
FUNCTIONS
Total
Average
Display
---------------------------------------------------

Objects serve two purposes: They promote understanding of the real world and provide a
practical basis for computer implementation. All Objects have identity and are distinguishable.

2. Classes: An Object class describes a group of objects with similar properties (attributes), common
behavior (operations) and common relationships to other objects. Objects in a class have the same
attributes and behavior patterns. The entire set of data and code of an object can be made a user defined
data type with the help of a class.

For ex: Mango, Apple, Orange are the members of the class fruit.
If fruit has been defined as a class then the statement
fruit mango;
 will create an object mango belonging to the class fruit.
 A class serves as a blue print or a plan or a template.
 It specifies what data and what functions will be included in objects of that class.

mnnappaji@gmail.com
2
Person (Person) (Person) (Person)
Appaji Chakri Shyam
Fig: Class and Objects

Person (Person) (Person) (Person)


Name: string Appaji Chakri Shyam
age: integer 28 32 30

Class with Attributes Objects with Values

An attribute is a data value held by the objects in a class.

3. Data Abstraction: It consists of focusing on the essential inherent aspects of an entity. Most modern
languages provide data abstraction, but the ability to use inheritance and polymorphism provides
additional power. Classes use the concept of abstraction, they are known as Abstract Data Types.

4. Encapsulation: It is also termed as information hiding. The wrapping up of data and functions into a
single unit is known as encapsulation. It is the most essential feature of a class. The data is not accessible
to the outside and only those functions in the class can access it.

5. Inheritance: Inheritance is the sharing of attributes and operations among classes based on a
hierarchical relationship. (or)
Inheritance is the process by which objects of one class acquire the properties of objects of
another class.

Using a concept of inheritance new classes can be built from the old ones. The new class referred
to as a derived class, can inherit the data structures and functions of the original or the base class. The
new class can add data elements and functions to those it inherits from its base class.

For ex: 1. Scrolling window and Fixed window are subclasses of window.

2.
BIRD
Attributes:
----------
----------
FLYING BIRD NON FLYING BIRD
Attributes Attributes
---------- ----------
---------- ----------
ROBIN SWALLOW PENGUIN KIWI
Attributes Attributes Attributes Attributes
---------- ---------- ---------- ----------
---------- ---------- ---------- ----------
The bird ROBIN is a part of the class FLYING BIRD that is again a part of the class BIRD.

In Object Oriented Programming, the concept of inheritance provides the idea of reusability. This
means that we can add additional features to an existing class without modifying it.

mnnappaji@gmail.com
3
6. Polymorphism: Polymorphism is another important Object-Oriented Programming concept.
Polymorphism means that the same operation may behave differently on different classes.

For example: The move operation may behave differently on the windows and chess piece classes.
Polymorphism plays an important role in allowing objects involving different internal structures to share
the same external interface. Polymorphism is extensively used in implementing inheritance.

SHAPE
Draw()

CIRCLE BOX TRIANGLE


object object object
---------- ---------- ----------
Draw(circle) Draw(box) Draw(triangle)

There are two types of polymorphism.


Compile time polymorphism - It is achieved by overloading functions and operators. A class
that has many Load methods having different parameters, this is called Compile time
polymorphism.
Run time polymorphism - It is achieved by overriding virtual functions. Where you have a
virtual method in the base class called Load with one parameter and you have redefined its
functionality in your sub class by overriding base class Load method, this is called Run time
polymorphism.

7. Dynamic Binding: Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time. It is associated with polymorphism and inheritance.

8. Message Communication: An Object-Oriented Programming consists of a set of objects that


communicate with each other. Objects communicate with one another by sending and receiving
information. Message passing involves specifying the name of object, the name of function (message) and
information to be sent.
Ex: Employee Salary (Name)
Object Message Information

Objects have a life cycle. They can be created and destroyed. Communication with an object is feasible as
long as it is alive.
Object1

Object2
Object5

Object4 Object3

Network of objects communicating between them


mnnappaji@gmail.com
4
Benefits of OOP:
OOP offers several benefits to the program designer and the user. Object-orientation contributes to the
solutions of many problem associated with the development and quality of software products. The new
technology promises greater programmer productivity, better quality of software and lesser maintenance
cost. The principal advantages are:

1. Through inheritance, we can eliminate redundant code and extend the use of existing classes.
2. We can build programs from standard working modules that communicate with one another
rather than, having to start writing the code from scratch. This leads to saving of development
time and higher productivity.
3. The principle of data hiding helps the programmers to build secure program that can’t be invaded
by code in other parts of the program.
4. It is possible to have multiple objects to coexist without any interference.
5. It is possible to map objects in the problem domain to those objects in the program.
6. It is easy to partition the work in a project based on objects.
7. The data-centered design approach enables us to capture more details of the model in an
implementable form.
8. Object-oriented systems can be easily upgraded from small to large system
9. Message passing technique for communication between objects makes the interface descriptions
with external system much simpler.
10. Software complexity can be easily managed.

Applications of OOPS:

1. Real time System.


2. Simulation and Modeling.
3. Hypertext, Hypermedia and expertext.
4. Decision support system.
5. CAM/CAE/CAD System.
6. Office Automation System.
7. AI and expert system.
8. Object Oriented Relational database Management System(OORDBMS).

Note:

Expertext : It is a system which combines a hypertext and an expert system. Hypertext systems can
include expert system features for incorporating flexibility, formal representations and arbitrary
computations that helping users find relevant information.

CAM : Computer Aided Manufacturing

CAE : Computer Aided Engineering

CAD : Computer Aided Drafting


mnnappaji@gmail.com
5
History of Java:

Java is a general-purpose, OOP Language developed by James Gosling, Patric Naugton, etc., at Sun
Micro Systems of USA in 1991.
Java Logo
The original name of JAVA is OAK by James Gosling (which is a tree name).
In the year 1995, OAK was revised and developed software called JAVA
(which is a coffee seed name).
His objective was to create a common development environment for
consumer electronic devices like TVs, VCRs, Toasters and such other
electronic machines.
Java is Object-Oriented language built on C and C++. It derives its syntax
from C and its Object-Oriented features are influenced by C++.
Java retains much of the syntax and power of C++, but it is simpler, increased robustness, better
security features.
It promised "Write Once, Run Anywhere" (WORA), providing no-cost run-times on popular
platforms.
Java is a programming language which is greater portability across different operating system
platforms i.e., platform independent and very secure for use on the Internet.
Designed for easy Web/Internet applications
Widespread acceptance

Java Milestones
Year Development
1990 Sun decided to developed special software that could be used for electronic devices. A project
called Green Project created and head by James Gosling.
1991 Explored possibility of using C++, with some updates announced a new language named “Oak”
1992 The team demonstrated the application of their new language to control a list of home appliances
using a hand held device.
1993 The World Wide Web appeared on the Internet and transformed the text-based interface to a
graphical rich environment. The team developed Web applets (tiny programs) that could run on
all types of computers connected to the Internet.
1994 The team developed a new Web browser called “Hot Java” to locate and run Applets. HotJava
gained instance success.
1995 Oak was renamed to Java, as it did not survive “legal” registration. Many companies such as
Netscape and Microsoft announced their support for Java
1996 Java established itself as both “the language for Internet programming” & a general purpose OOL.
1997- A class libraries, Community effort and standardization, Enterprise Java, Clustering, etc., Sun
releases Java Development kit 1.1 (JDK 1.1)
1998 Sun releases Java 2 with version 1.2 of the Software Development kit (SDK 1.2)
1999 Sun releases Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition (J2EE).
2000 J2SE with SDK 1.3 released
2002 J2SE with SDK 1.4 released
2004 J2SE with JDK 5.0 (instead of SDK 1.5) released. This is known as J2SE 5.0
mnnappaji@gmail.com
6
Java Editions:

JAVA released to the market in three categories


a) J2SE (JAVA 2 Standard Edition): It is basically used for developing client side
applications/programs
b) J2EE (JAVA 2 Enterprise Edition): It is used for developing server side applications/programs.
c) J2ME (JAVA 2 Micro/Mobile Edition): It is used for developing server side applications/programs.

Principles

There were five primary goals in the creation of the Java language:

1. It should be "simple, object-oriented and familiar"


2. It should be "robust and secure"
3. It should be "architecture-neutral and portable"
4. It should execute with "high performance"
5. It should be "interpreted, threaded, and dynamic"Features of Java

JAVA FEATURES
1. Compiled and Interpreted
2. Platform-Independent and Portable
3. Object-Oriented
4. Robust and Secure
5. Distributed
6. Familiar, Simple and Small
7. Multithreaded and Interactive
8. High Performance
9. Dynamic and Extensible

Compiled and Interpreted: Usually a computer language is either compiled or interpreted. Java
combines both these approaches thus making Java a two-stage system. First, Java compiler translates
source code into what is known as bytecode instructions. Bytecodes are not machine instructions and
therefore, in the second stage, Java interpreter generates machine code that can be directly executed by
the machine.

Platform-Independent and Portable: Platform is the combination of operating system and


microprocessor. Java programs works in all platforms. It is achieved by JVM (Java Virtual Machine). The
philosophy of java is “Write Once, Run Anywhere” (WORA).The most significant contribution of Java over
other languages is its portability. Java programs can be easily moved from one computer system to
another, anywhere and anytime. Changes and upgrades in operating systems and system resources will
not force any changes in Java programs. So, Java has become a popular language for programming on
Internet which interconnects different kinds of connectors.

Object-Oriented: Java is a true object-oriented language. Almost everything in Java is an object. Java
comes with an extensive set of classes, arranged in packages that we can use in our programs by
inheritance. The object model in Java is simple and easy to extend. Although influenced by its procedures.
It was designed to be source code compatible with any other language.

mnnappaji@gmail.com
7
Robust and Secure: Java is a robust language. It provides many safeguards to ensure reliable code. It is
designed as a garbage-collected language relieving the programmers virtually all memory management
problems. Java also incorporates the concept of exception handling which captures series errors and
eliminates any risk of crashing the system. Java systems not only verify all memory access but also ensure
that no viruses are communicated with an applet.

Distributed: Java is designed as a distributed language for creating applications on networks. It has the
ability to share both data and programs. Java applications can open and access remote objects on Internet
as easily as they can do in a local system. This enables multiple programmers at multiple remote
locations to collaborate and work together on a single project.

Simple, Small and Familiar: Java is a small and simple language. Java follows the syntax of C and Object
Oriented principles of C++. It eliminates the complexities of C and C++. Many features of C and C++ that
are will not support in Java. For example, Java does not use pointers, preprocessor header files, goto
statement and many others. It also eliminates operator overloading and multiple inheritance.

Multithreaded and Interactive: Multithreaded means handling multiple tasks simultaneously. Java
supports multithreaded programs. This means that we need not wait for the application to finish one task
before beginning another. For example, we can listen to an audio clip while scrolling a page and at the
same time download an applet from a distant computer.

High Performance: Java performance is impressive for an interpreted language, mainly due to the use of
intermediate bytecode. Java architecture is also designed to reduce overheads (difficulties) during
runtime.

Dynamic and Extensible: Java is a 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. This facility enables the programmers to use the
efficient functions available in these languages. Native methods are linked dynamically at runtime.

Ease of development: JAVA 2 Standard Edition (J2SE) 5.0 supports features, such as generics, Enhanced
for loop, auto boxing or unboxing, typesafe and enum.

Difference between JAVA and C

 Java does not include the C unique statement keywords goto, sizeof and typedef.
 Java does not contain the data types struc, union and enum.
 Java does not support an explicit pointer type.
 Java does not have a preprocessor and therefore we cannot use # define, # include, and
# ifdef statements.
 Java does not support any mechanism for defining variable arguments to functions.
 Java requires that the functions with no arguments must be declared with empty parenthesis
and not with the void keyword as done in C.
 Java adds new operators such as instanceof and > > >.
 Java adds labeled break and continue statements.
 Java adds many features required for object-oriented programming.

mnnappaji@gmail.com
8
Difference between JAVA and C++

1. Java does not support operator overloading.


2. Java does not have template classes as in C++.
3. Java does not support multiple inheritance of classes. This is accomplished using a new
feature called “interface”.
4. Java does not use pointers.
5. Java does not include structure and union.
6. There are no header files in Java.
7. Java does not have a preprocessor.
8. Java has replaced the destructor function with a finalize( ) function.

JAVA and Internet:

Java is strongly associated with the Internet because of the fact that the first application program
written in Java was HotJava, a Web browser to run applets on Internet. Internet users can use Java to
create applet programs and run them locally using a "Java-enabled browser" such as HotJava. They can
also use a Java-enabled browser to download an applet located on a computer anywhere in the Internet
and run it on his local computer. In fact, Java applets have made the Internet a true extension of the
storage system of the local computer.

Internet users can also set up their Web sites containing Java applets that could be used by other
remote users of Internet. The ability of Java applets to hitch a ride on the Information Superhighway has
made Java a unique programming language for the Internet. Hence, Java is popularly known as Internet
language.

JAVA and World Wide Web:

World Wide Web (WWW) is an open-ended information retrieval system designed to be used in
the Internet's distributed environment. This system contains what are known as Web pages that provide
both information and controls. It is made possible with the help of a language called Hypertext Markup
Language (HTML). Web pages contain HTML tags that enable us to find, retrieve, manipulate and display
documents worldwide. Java communicates with a Web page through a special tag called <APPLET>.

1. 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 required
document.
2. The HTML document is returned to the user's browser. The document contains the APPLET tag,
which identifies the applet.
3. The corresponding applet bytecode is transferred to the user's computer. This bytecode had been
previously created by the Java compiler using the Java source code file for that applet.
4. The Java-enabled browser on the user's computer interprets the bytecodes and provides output.
5. The user may have further interaction with the applet but with no further downloading from the
provider's Web server. This' is because the bytecode contains all the information necessary to
interpret the applet.

mnnappaji@gmail.com
9
Web Browsers: The Internet is a vast sea of information represented in many formats and Stored on
many computers. A large portion of the Internet is organized as the World Wide Web which uses
hypertext. Web browsers are used to navigate through the information found on the net. They allow us to
retrieve the information spread across the Internet and display it using the hypertext markup language
(HTML). Examples of Web browsers,

HotJava: It is the Web browser from Sun Microsystems that enables the display of interactive content on
the Web, using the Java language. HotJava is written entirely in Java and demonstrates the capabilities of
the Java programming language.
When the Java language was first developed and ported to the Internet, no browsers were available that
could run Java applets. Although we can view a Web page that includes Java applets with a regular
browser, we will not gain any of Java's benefits. HotJava is currently available for the SPARC/Solaris
platform as well as Windows 95 and Windows NT. So far as being a Web browser goes, it is nothing
special and does not offer anything special that most other
Web browsers don't offer. Its biggest draw is that it was the first Web browser to provide support for the
Java language, thus making the Web more dynamic and interactive.

Netscape Navigator: Netscape Navigator, from Netscape Communications Corporation, is a general-


purpose browser that can run Java applets. With versions available for Windows 95, NT, Solaris and
Apple Macintosh, Netscape Navigator is one of the most widely used browsers today.
Netscape Navigator has many useful features such as visual display about downloading process and
indication of the number bytes downloaded. It also supports JavaScript, a scripting language used in
HTML documents.

Internet Explorer: Internet Explorer is another popular browser developed by Microsoft for Windows
95 and NT Workstations. Both the Navigator and Explorer use tool bars, icons, menus and dialog boxes
for easy navigation. Explorer uses a just-in-time (JIT) compiler which greatly increases the speed of
execution.

Hardware and Software requirements: Java is currently supported on Windows 95, Windows NT, Sun
Solaris, Macintosh, and UNIX machines. The minimum hardware and software requirements for Windows
95 version of Java are as follows:

 A hard drive  Minimum of 8 MB memory


 A CD-ROM drive  Windows 95 software
 A Microsoft-compatible mouse  A Windows-compatible sound card, if
 IBM compatible 486 system necessary

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

mnnappaji@gmail.com
10
Java Development Kit: The Java Development Kit comes with a collection of tools that are used for
developing and running Java programs. They include:
Tool Description
appletviewer Enables us to run Java applets (without actually using a Java-compatible browser).
java Java interpreter, which runs applets and applications by reading and interpreting
byteeode files
javac The Java compiler, which translates Java sourcecode to byteeode files that the
interpreter can understand.
javadoc Creates HTML format documentation from Java source code files.
Javah Produces header files for use with native methods for C header files.
javap Java disassembler, which enables us to covert byteeode files into a program Description
jdb Java debugger, which helps us to find errors in our programs.
To create a Java program, we need to
create a source code file using a text editor. Text Editor
The source code is then compiled using the
Java compiler javac and executed using the
Java interpreter java. The Java debugger
jdb is used to find errors, if any, in the Java Source HTML
Javadoc
source code. A compiled Java program can Code files
be converted into a source code with the
help of Java disassembler javap.
Javac
Application Programming Interface
The Java Standard Library (or API)
includes hundreds of classes and methods
grouped into several functional packages
Java Class Header
(see Appendix G). Most commonly used Javah
File Files
packages are:

Language Support Package: A collection


of classes and methods required for
Java (only file name) Jdb
implementing basic features of Java.
(database)
Utilities Package: A collection of classes to
provide utility functions such as date and Java
time functions. Program
Input/output Package: A collection of Output
classes required for input/output manipulation.

Networking Package: A collection of classes for communicating with other computers via Internet.

AWT Package: The Abstract Window Tool Kit package contains classes that implements platform-
independent graphical user interface.

Applet Package: This includes a set of classes that allows us to create Java applets.
mnnappaji@gmail.com
11
Overview of Java Language

Java is a general-purpose, object-oriented programming language. We can develop two types of Java
programs:
 Stand-alone applications  Web applets

Stand-alone applications are programs written in Java to carry out certain tasks on a stand-alone 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 ++. HotJava itself is a Java application program. Executing a stand-
alone Java program involves two steps:

1. Compiling source code into bytecode using javac compiler


2. Executing the bytecode program using Java interpreter.

Applets are small Java programs developed for Internet applications. An applet located on a distant
computer (Server) can be downloaded via Internet and executed on a local computer (Client) using a
Java-capable browser. We can develop applets for doing everything from simple animated graphics to
complex games and utilities. Since applets are embedded in an HTML (Hypertext Markup Language)
document and run inside a Web page.

Stand-alone programs can read and write files and perform certain operations that applets cannot do. An
applet can only run within a Web browser.

Simple JAVA Program


class Sample
{
public static void main(String args[ ])
{
System.out.println("Welcome to JAVA.");
}

Class Declaration: The first line class Sample declares a class, which is an object-oriented construct. As
stated earlier, Java is a true object-oriented language and therefore, everything must be placed inside a
class, class is a keyword and declares that a new class definition follows. Sample is a Java identifier that
specifies the name of the class to be defined.

Opening Brace: Every class definition in Java begins with an opening brace "{" and ends with a matching
closing brace "}", appearing in the last line in the example.

The Main Line: The third line public static void main(String args[ ]) defines a method named main.
Conceptually, this is similar to the main( ) function in C / C++. Every Java application program must
include the main( ) method. This is the starting point for the interpreter to begin the execution of the
program. A Java application can have any number of classes but only one of them must include a main
method to initiate the execution. Java applets will not use the main method.
All parameters to a method are declared inside a pair of parentheses. Here, String args[ ] declares
a parameter named args, which contains an array of objects of the class type String.

mnnappaji@gmail.com
12
The Output Line: executable statement in the program is System.out.println("Welcome to JAVA"). This is
similar to the printf ( ) statement of C or cout < < construct of C++. Since Java is a true object oriented
language, every method must be part of an object. The println method is a member of the out object,
which is a static data member of System class. This line prints the string Welcome to JAVA to the screen.
The method println always appends a newline character to the end of the string. This means that any
subsequent output will start on a new line. Note the semicolon at the end of the statement. Every Java
statement must end with a semicolon. (Saving, compiling, and executing a Java program)

JAVA Program Structure:


Java program may contain many classes of which only one class defines a main method. Classes contain
data members and methods that operate on the data members of the class. Methods may contain data
type declarations and executable statements. To write a Java program, we first define classes and then
put them together. A Java program may contain one or more sections.

Documentation Section Suggested

Package Statement Optional

Import Statements Optional

Interface Statements Optional

Class Definitions Optional

Main Method Class Essential

Main Method Definition

General structure of a Java program

Documentation Section: The documentation section comprises a set of comment lines giving the name
of the program, the author and other details, which the programmer would like to refer-to at a later stage.
Comments must explain why and what of classes and how of algorithms. This would greatly help in
maintaining the program. In addition to the two styles of comments discussed earlier, Java also uses a
third style of comment /**....*/ known as documentation comment. This form of comment is used for
generating documentation automatically.
mnnappaji@gmail.com
13
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.
Example: package student;

Import Statement: The next thing after a package statement (but before any class definitions) may be a
number of import statements. This is similar to the #include statement in C. Example: import student.test;
This statement instructs the interpreter to load the test class contained in the package student. Using
import statements, we can have access to classes that are part of other named packages.

Interface Statements: An interface is like a class but includes 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. Interface is a new concept in Java

Class Definitions: A Java program may contain multiple class definitions. Classes are the primary and
essential elements 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.

Main Method Class: Since every Java stand-alone program requires a main method as its starting point,
this class is the essential 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.

Comments in a Program: Three types of comment statements are available in Java. They are
i) Single line comment (//)
ii) Multi line comment (/* and */)
iii) Documentation comment (/** and */)

1. Single line comment: For a single line comment we use double slash (//) to begin a comment. It
ends at the end of line.
Example: // Program for stack operations

2. Multi line comment: For more than one line of information, we use multi line comments. Multi line
comments are starts with /* and ends with */.
Example: /* Program for stack operations
Designed by APPAJI
Bhimavaram, Andhra Pradesh */

3. Documentation comment: For the documentation purpose, we use documentation comments.


Documentation comments are starts with /** and ends with */.
Example: /** A test for JDK

Java Character Set: Letters, Digits and Special Characters

Letters: Java language comprises the following set of letters to form a standard program. They
are: A to Z in Capital letters & a to z in Small letters.

Digits: Java language comprises the following sequence of numbers to associate the letters. 0 to 9
digits.

mnnappaji@gmail.com
14
Special Characters: Java language contains the following special character in association with the
letters and digits.

Symbol Meaning - Minus sign


~ Tilde = Equal to sign
! Exclamation mark { Left brace
# Number sign } Right brace
$ Dollar sign [ Left bracket
% Percent sign ] Right bracket
^ Caret : Colon
& Ampersand " Quotation mark
* Asterisk ; Semicolon
( Left parenthesis < Less than or Opening angle bracket
) Right parenthesis > Greater than or Closing angle bracket
_ Underscore ? Question mark
+ Plus sign , Comma
| Vertical bar . Period
\ Backslash / Slash or forward Slash
` Apostrophe

Java Access Modifiers:


Java provides a number of access modifiers to set access levels for classes, variables, methods and
constructors. The four access levels are:

Visible to the package default. No modifiers are needed.


Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).

JAVA TOKENS:
A Java program is basically a collection of classes. A class is defined by a set of declaration
statements and methods containing executable statements. Most statements contain expressions, which
describe the actions carried out on data. Smallest individual units in a program are known as tokens. Java
program is a collection of tokens, comments and white spaces. Java language includes five types of
tokens. They are:

 Reserved Keywords  Operators


 Identifiers  Separators
 Literals

Keywords: Keywords are an essential part of a language definition. They implement specific features of
the language. Java language has reserved 50 words as keywords. Since 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. Since Java is case-sensitive

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

abstract assert boolean break byte case catch


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

Identifiers:
Identifiers are programmer-designed tokens. They, are used for naming classes, methods,
variables, objects, labels, packages and interfaces in a program. Java identifiers follow the following rules:

1. They can have alphabets, digits, and the underscore and dollar sign characters.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. The variable name should not be a keyword.
5. White spaces are not allowed.
6. They can be of any length.

Literals:
Literals in Java are a sequence of characters (digits, letters, and other characters) that represent
constant values to be stored in variables. Java language specifies five major types of literals. They are:

1. Integer literals 4. String literals


2. Floating point literals 5. Boolean literals
3. Character literals

Operators: An operator is a symbol that takes one or more arguments and performs certain
mathematical and logical manipulations.
1. Arithmetic Operators 5. Bit wise operator
2. Relational Operators 6. Assignment Operator
3. Logical Operators 7. Conditional Operator
4. Increment and Decrement Operator 8. Special operator

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

Name What it is used for


Parentheses ( ) Used to enclose parameters in method definition
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 array values
semicolon ; Used to separate statements
mnnappaji@gmail.com
16
comma , Used to separate consecutive identifiers in a variable declaration, also used to chain
statements together inside a 'for' statement
period . Used to separate package names from sub-packages and classes; also used to separate
a variable or 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 sequence in
the order in which they appear. It is possible to control the flow of execution, if necessary, using special
statements.

JAVA
Statements

Expression Labeled Synchronization Guarding


Statement Statement Statement Statement

Control
Statement

Selection Iteration Jump


Statement Statements Statements

If- Switc break Conti retur


If
else h nue n

While do for

mnnappaji@gmail.com
17
Java Statements:

a. Expression Statement: Most statements are expression statements. Java has seven types
of Expression statements: Assignment, Pre-Increment, Pre-Decrement, Post-Increment,
Post-Decrement, Method Call and Allocation Expression.

b. Labeled Statement: Any Statement may begin with a label. Such labels must not be
keywords, already declared local variables, or previously used labels in this module. Labels
in Java are used as the arguments of Jump statements, which are described later in this
list.

c. Control Statement:
i. Selection Statement: These select one of several control flows. There are three
types of selection statements in Java: if, if-else, and switch.
ii. Iteration Statement: These specify how and when looping will take place. There
are three types of iteration statements: while, do and for.
iii. Jump Statement: Jump Statements pass control to the beginning or end of the
current block, or to a labeled statement. Such labels must be in the same' block, and
continue labels must be on an iteration statement. The four types of Jump statement
are break, continue, return and throw.

d. Synchronization Statement: These are used for handling issues with multithreading.

e. Guarding Statement: Guarding statements are used for safe handling of code that may
cause exceptions (such as division by zero). These statements use the keywords try, catch,
and finally.

Implementing a JAVA Program:

Creating the Program:


1. We can create a program using any text editor or dos editor. Save the file with a .java extension
2. Type file name should be the same as the class, which has the main method.

Sample Program:
/*this is a simple Java program*/
class Appaji
{
// your program begin with a call to main()
public static void main(String args[ ])
{
System.out.println("Hello! This is a Sample Java Program");
}
}
Note: All Java source files will have the extension .java. If a program contains multiple classes, the file
name must be the classname of the class containing the main method.

mnnappaji@gmail.com
18
Compiling the Program: To compile the program, we must run the Java Compiler javac, with the name
of the source file on the command line.
Syntax : javac <filename.java>
Example : javac Appaji.java

Running the Program: After compilation, run the program using the java interpreter.
Syntax : java <filename> (without the .java extension)
Example : java Appaji

The program output will be displayed on the command line.

Source Code

Java Compiler

Bytecode

Windows ABC Interpreter Macintosh


interpreter Interpreter

Machine Code Machine Code Machine Code

Windows ABC Computer Macintosh


Computer Computer
Implementation a JAVA Program
Machine Neutral: JAVA compiler converts the source code files into bytecode files. These codes are
machine-independent and therefore can be run on any machine. That is, a program compiled on an IBM
machine will run on a Macintosh machine. Java interpreter reads the bytecode files and translates them
into machine code for the specific machine on which the Java program is running.
JAVA VIRTUAL MACHINE:
All language compilers translate source code into machine code for a specific computer. Java compiler
produces an intermediate code known as bytecode for a machine that does not exist. This machine is
called the Java Virtual Machine and it exists only inside the computer memory. It is a simulated computer
within the computer and does all major functions of a real computer.

Virtual
JAVA Program JAVA Compiler
Machine
Source Code Process of compilation Bytecode
mnnappaji@gmail.com
19
The virtual machine code is not machine specific. The machine specific code (known, as machine code) is
generated by the Java interpreter by acting as an intermediary between the virtual machine and the real
machine.

JAVA Virtual
Bytecode
Compiler Machine
Virtual Machine Real Machine

COMMAND LINE ARGUMENTS


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 receive and use the arguments provided in the command line.
public static void main(String args[ ])
args is declared as an array of strings. Any arguments provided in the command line are passed to
the array args as its elements. We can simply access the array elements and use them in the program

Program:
Class ComLineTest
{
public static void main(String args[ ])
{
int count,. i=0;
String string;
count = args.length;
System.out.println("Number of arguments = " + count);
while(i < count)
{
string = args[i];
i = i + 1;
System.out.println(i+ " : " + "Java is " +string+"!");
}
}
}
The individual elements of an array are accessed by using an index or subscript like args[i]. the
value of I denotes the position of the elements inside the array.
java ComLineTest Simple Object_Oriented Distributed Robust Secure Portable Multithreaded Dynamic
count = args.length; The output of the program would be as follows:

Number of arguments = 8
Java is Simple!
Java is Object_Oriented!
Java is Distributed!
Java is Robust!
Java is Secure!
Java is Portable!
Java is Multithreaded!
Java is Dynamic!

mnnappaji@gmail.com
20
Constants, Variables and Data types

Constants: Constants in Java refer to fixed values that do not change during the execution of a program.
Java supports several types of constants.

JAVA Constants

Numeric Constants Character Constants

Integer Constants Real Constants Character String Backslash


Constants Constants Character
Constants

Decimal Octal Hexadecimal

Integer Constants:

 An integer constant refers to a sequence of digits.


 There are three types of integers, namely decimal integer, octal integer and hexadecimal integer.
 Decimal integers consist of a set of digits, 0 through 9, preceded by an optional minus sign.
Embedded spaces, commas, and non-digit characters are not permitted between digits.
For example, 123 -321 0 654321
 An octal integer constant consists of digits from 0 to 7, with a leading 0.
For example, 0435 0551
 A sequence of digits preceded by Ox or OX is considered as hexadecimal integer (hex integer).
They may also include alphabets A through F or a through f. A letter A through F represents the
numbers 10 through 15. Following are the examples of valid hex integers.
For example, 0X2 0X9F Oxbcd

Real Constants:
 Numbers containing fractional parts like 17.548. Such numbers are called real constants.
For example, 0.0083 435.36
 A Real number may also be expressed in exponential notation. The general form is
Mantissa E exponent
 Mantissa is either a real number or an integer. The exponent is an integer with an optional plus or
minus sign. The mantissa and the exponent can be written in either lowercase or uppercase.
For example, 7845.49e2
e2 means multiple by 102

Single Character Constants:


A single character constant contains a single character enclosed within a pair of single quote
marks.
For example, '5' 'M' ‘A’ ‘P’
 Note that the character constant '5' is not the same as the number 5. The last constant is a blank
space.
mnnappaji@gmail.com
21
String Constants:
A string constant is a sequence of characters enclosed between double quotes. The characters maybe
alphabets, digits, special characters and blank spaces'.

For example, "Hello Java" "1997" "WELL DONE" "?...!" "5+3" "X"

Backslash Character Constants:


Java supports some special backslash character constants that are used in output methods. For example,
the symbol '\n' stands for newline character.

Following table shows the Java escape sequences:

Escape Sequence Description


\t Insert a tab in the text at this point.
\b Insert a backspace in the text at this point.
\n Insert a newline in the text at this point.
\r Insert a carriage return in the text at this point.
\f Insert a form feed in the text at this point.
\' Insert a single quote character in the text at this point.
\" Insert a double quote character in the text at this point.
\\ Insert a backslash character in the text at this point.
When an escape sequence is encountered in a print statement, the compiler interprets it accordingly.

Variables:
A Variable is an identifier that denotes a storage location used to store a data value. Variable may
take different values at different times during the execution of the program. A variable name can be
chosen by the programmer in a meaningful way so as to reflect what it represents in the program.
Examples of variable names are:

 average
 height
 total_height
 classStrength

Variable names may consist of alphabets, digits, the underscore(_) and dollar characters, with following
conditions:

 They must not begin with a digit.


 Uppercase and lowercase are distinct. For example, that the variable Total is not the same as total
or TOTAL.
 It should not be a keyword.
 White space is not allowed.
 Variable names can be of any length.

mnnappaji@gmail.com
22
Data Types
Every variable in Java has a data type. Data types specify the size and type of values that can be stored.
Java language is rich in its data types.

Byte
Numeric Interger

Short

Primitive Int
Data Types
Floating
Point Long

DATA TYPES Non-Numeric Character


Float

Boolean
Classes
Double
Non-
Primitive
Data Types Interface

Arrays

Integer Types: Integer types can hold whole numbers. The size of the values that can be stored depends
on the integer data type we choose. Java supports four types of integers. They are byte, short, int, and
long. Java does not support the concept of unsigned types.

Type Size Minimum value Maximum value Default


Value
Byte One byte -128 127 0
short Two bytes -32, 768 32,767 0
Int Four bytes -2,147, 483, 648 2, 147, 483, 647 0
Long Eight bytes -9, 223, 372, 036, 854, 775, 808 9, 223, 372, 036, 854, 775, 807 0L
Size and Range of Integer Types
Floating Point Types: These types to hold numbers containing fractional parts such as 27.59 and -1.375.
There are two kinds of floating point storage are float & double in Java.

Type Size Minimum value Maximum value Default


Value
float 4 bytes 3.4e-038 3.4e+038 0.0f
double 8 bytes 1.7e-308 1.7e+308 0.0d
Size and Range of Floating Point Types
mnnappaji@gmail.com
23
Floating point numbers are treated as double-precision quantities. To force them to be in single-precision
mode, we must append f or F to the numbers. Example: 1.23f 7.56923e5F.
Double-precision types are used when we need greater precision in storage of floating point numbers. All
mathematical functions, such as sin, cos and sqrt return double type values.

Character Type:
In order to store character constant in memory, Java provides a character data type called char. The char
type assumes a size of 2 bytes but, basically, it can hold only a single character.

Boolean Type:
Boolean type is used when we want to test a particular condition during the execution of the program.
There are only two values that a Boolean type can take: true or false. Remember, both these words have
been declared as keywords. Boolean type is denoted by the keyword Boolean and uses only one bit of
storage.

Declaration of Variables: In Java, variables are the names of storage locations. After designing suitable
variable names, we must declare them to the compiler.

 It tells the compiler what the variable name is.


 It specifies what type of data the variable will hold.
 The place of declaration (in the program) decides the scope of the variable.

Syntax : type variablel, variable2 ,…………… , variableN;


Ex : int a, b;
Float pi;

Giving values to Variables: A variable must be given a value after it has been declared but before it is
used in an expression. This can be achieved in two ways:
1. By using an assignment statement
2. By using a read statement
Assignment Statement: A simple method of giving value to a variable is through the assignment
statement as follows:
Syntax : variable name = value;
Ex : a=10;
It is also possible to assign a value to a variable at the time of its declaration.
Syntax : type variable name = value;
Ex : int a=10;
The process of giving initial values to variables is known as the initialization. If the variable is not
initialized, It is automatically set to zero.

Read Statement: We may also give values to variables interactively through the keyboard using the
readLine( ) method

Reading data from keyboard

import java.io.DatalnputStream;
class Reading
{
public static void main(String args[ ]) {
mnnappaji@gmail.com
24
DatalnputStream in = new DatalnputStream(System.in);
int intNumber = 0;
float floatNumber = 0.0f;
try
{
System.out.println("Enter an Integer: ");
intNumber = Integer.parselnt(in.readLine ( ));
System.out.println("Enter a float number: ");
floatNumber = Float.valueOf(in.readLine( )).floatValue( );
catch (Exception e) { } }
System.out.println("intNumber = " + intNumber);
System.out.println("floatNumber = " + floatNumber);
}
}

Output:
Enter an integer:
579
Enter a float number:
444.55
intNumber = 579
floatNumber = 444.55

The readLine( ) method reads the input from the keyboard as a string which is then converted to the
corresponding data type using the data type wrapper classes.

Scope of Variables: The area of the program where the variable is accessible is called its scope. Java
variables are actually classified into three kinds:

 Instance variables
 Class variables
 Local variables

Instance variables: Instance and class variables are declared inside a class. Instance variables are
created when the objects are instantiated and therefore they are associated with the objects. They
take different values for each object.
Class variables: Class variables are global to a class and belong to the entire set of objects that class
creates. Only one memory location is created for each class variable.
Local variables: Variables declared and used inside methods are called local variables. They are
called so because they are not available for use outside the method definition. Local variables can
also be declared inside program blocks that are defined between an opening brace { and a closing
brace }.

Symbolic Constants:

Syntax : final type symbolic-name = value;


Ex : final int STRENGTH = 100;
final int PASS_MARK = 40;
final float PI = 3.14159;
mnnappaji@gmail.com
25
1. Symbolic names take the same form as variable names. But, they are written in CAPITALS to
visually distinguish them from normal variable names.
2. After declaration of symbolic constants, they should not be assigned any other value within the
program by using an assignment statement.
3. Symbolic constants are declared for types. This is not done in C and C++ where symbolic
constants are defined using the # define statement.
4. They can NOT be declared inside a method. They should be used only as class data members in
the beginning of the class.

TYPECASTING: Type casting is a process of converting one data type to another is called casting.
Examples:
Syntax : type variable1 = (type) variable2;
Ex : int m = 50; byte n = (byte)m; long count = (long)m;

Casting into a smaller type may result in a loss of data. The float and double can be cast to any
other type except Boolean. Casting a floating point value to an integer will result in a loss of the fractional
part. Automatic type conversion is possible only if the destination type has enough precision to store the
source value. For example, int is large enough to hold a byte value. Therefore, byte b = 75; int a = b;

The following conversions will not any Loss of Information


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

The process of assigning a smaller type to a larger one is known as widening or promotion and
that of assigning a larger type to a smaller one is known as narrowing.

Getting Values of Variables: Java supports two output methods that can be used to send the results to
the screen.
 print ( ) method // print and wait
 println(" ) method // print a line and move to next line

1. The print ( ) method sends information into a buffer. This buffer is not flushed until a newline
character is sent.
System.out.print("Hello ");
System.out.print("Java!");
display the words Hello Java! on one line

2. The println( ) method, takes the information provided and displays it on a line followed by a
line feed (carriage-return) just like ‘\n’ in C.
System.out.println("Hello");
System.out.println("Java!") ;
will produce the following output:
Hello
Java!
mnnappaji@gmail.com
26
Java Basic Operators: Java provides a rich set of operators to manipulate data and variables. We can
divide all the Java operators into the following groups:

Java operators can be classified into a number of related categories as below:

1. Arithmetic operators 5. Increment and decrement operators


2. Relational operators 6. Conditional operators.
3. Logical operators 7. Bitwise operators
4. Assignment operators 8. Special operators

Arithmetic Operators: These are used to construct mathematical expressions as in algebra. For
arithmetic operations, operands must be numeric values. Arithmetic operations are classified as
1. Integer Arithmetic (both operands are integers)
2. Real Arithmetic (both operands are real numbers)
3. Mixed mode Arithmetic (one operand is int and another one is real)
4. Modulus operator % can be applied to the floating point data as well. It returns the floating point
equivalent of an integer division.

Operator Description Example


+ Addition - Adds values on either side of the operator A + B will give 30
- Subtraction - Subtracts right hand operand from left hand operand A - B will give -10
* Multiplication - Multiplies values on either side of the operator A * B will give 200
/ Division - Divides left hand operand by right hand operand B / A will give 2
% Modulus - Divides left hand operand by right hand operand and returns B % A will give 0
remainder

Floating point arithmetic


class FloatPoint
{
public static void main(String args[ ])
float a = 20.5F, b = 6.4F;
{ Output:
System.out.println(" a = " +a); a = 20.5
System.out.println(" b = " +b); b = 6.4
System.out.println(" a+b =" +(a+b)); a+b = 26.9
System.out.println(" a-b =” +(a-b)); a-b = 14.1
System.out.println(" a*b =” +(a*b)) ; a*b = 131.2
System.out.println(" a/b =” +(a/b)) ; a/b = 3.20313
System.out.println(“ a%b =” +(a%b)); a%b = 1.3
}
}

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 such as
containing a relational operator is termed as a relational expression. The value of relational expression is
either true or false.
mnnappaji@gmail.com
27
Operator Description Example
> Checks if the value of left operand is greater than the value of right (A > B) is not
operand, if yes then condition becomes true. true.
< Checks if the value of left operand is less than the value of right operand, (A < B) is true.
if yes then condition becomes true.
>= Checks if the value of left operand is greater than or equal to the value of (A >= B) is not
right operand, if yes then condition becomes true. true.
<= Checks if the value of left operand is less than or equal to the value of (A <= B) is true.
right operand, if yes then condition becomes true.
== Checks if the value of two operands are equal or not, if yes then condition (A == B) is not
becomes true. true.
!= Checks if the value of two operands are equal or not, if values are not (A != B) is true.
equal then condition becomes true.
Implementation of relational operators
class RelationalOperators
{
public static void main(String args[ ])
{
float a = 15.OF, b = 20.75F, c = 15.OF;
System.out.println (" a = " + a); Output:
System.out.println (" b = " + b); . a = 15
System.out.println (" c = " + c); b = 20.75
System.out.println (" a < b is " + (a<b) ) ; c = 15
System.out.println (" a > b is " +(a>b)); a < b is true
System.out.println (" a == c is " + (a==c)); a > b is false
System.out.println (" a <= c is " + (a<=c)); a == c is true
a <= c is true
System.out.println (" a >= b is " + (a>=b));
a >= b is false
System.out.println (" b != c is " + (b!=c)); b != c is true
System.out.println (" b == a+c is " + (b==a+c)); b == a+c is false
}
}

Logical Operators: An expression, kind which combines two or


more relational expressions is termed as a logical expression or a
compound relational expression.

Operator Description Example


&& Called Logical AND operator. If both the operands are non-zero then then (A && B) is
condition becomes true. false.
|| Called Logical OR Operator. If any of the two operands are non-zero then (A || B) is
then condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. !(A && B) is
If a condition is true then Logical NOT operator will make false. true.
Assignment Operators: Assignment operators are used to assign the value of an expression to a
variable.

Operator Description Example


= Simple assignment operator, Assigns values from right side C = A + B will assigne value
operands to left side operand of A + B into C
mnnappaji@gmail.com
28
+= Add AND assignment operator, It adds right operand to the C += A is equivalent to C = C
left operand and assign the result to left operand +A
-= Subtract AND assignment operator, It subtracts right C -= A is equivalent to C = C -
operand from the left operand and assign the result to left A
operand
*= Multiply AND assignment operator, It multiplies right C *= A is equivalent to C = C
operand with the left operand and assign the result to left *A
operand
/= Divide AND assignment operator, It divides left operand C /= A is equivalent to C = C
with the right operand and assign the result to left operand /A
%= Modulus AND assignment operator, It takes modulus using C %= A is equivalent to C = C
two operands and assign the result to left operand %A
<<= Left shift AND assignment operator C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

Increment and Decrement Operators: These are the increment and decrement operators ++ and --.
The operator ++ adds 1 to the operand while -- subtracts 1.We use the increment and decrement
operators extensively in for and while loops.

Operator Description Example


++ Increment - Increase the value of operand by 1 B++ gives 21++B gives 21
-- Decrement - Decrease the value of operand by 1 B—gives 19 --B gives 19

class IncrementOperator class IncrementOperator


{ {
public static void main(String args[]) public static void main(String args[])
{ {
int m = 10, n; int m = 10, n;
System.out.println (“Pre Incrementation”); System.out.println (“Post Incrementation”);
n=++m; n=m++;
System.out.println(“m=”+m+”n=”+n); System.out.println(“m=”+m+”n=”+n);
} }
} }

m= 11 n = 11 m= 11 n=10

Conditional Operator ( ? : ): It is a combination of ?,: and takes three operands is also known as the
ternary operator.

variable x = (expression) ? value if true : value if false


First evaluates the expression. if the expression is true after ? statement will be executed if the express is
false after : statements will be executed

Ex: int big = (a>b)?a:b;


mnnappaji@gmail.com
29
Bitwise Operators: Java has a distinction of supporting special operators known as bitwise operators for
manipulation of data at values of bit level. These operators are used for testing the bits, or shifting them
right or left. Bitwise operators may not be applied to float or double.
Example: a=4 b=6
The equivalent binary value of a = 0000 0100
The equivalent binary value of b = 0000 0110
 a&b= 0000 0100
 a |b = 0000 0110
 a ^b= 0000 0010
 a << 2 = 0001 0000
 b>>2 = 0000 0001
 ~a = 1111 1011

Operator Description Example


& Binary AND Operator copies a bit to the result if it exists in (A & B) will give 12 which is
both operands. 0000 1100
| Binary OR Operator copies a bit if it exists in eather (A | B) will give 61 which is
operand. 0011 1101
^ Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is
operand but not both. 0011 0001
~ Binary Ones Complement Operator is unary and has the (~A ) will give -60 which is
efect of 'flipping' bits. 1100 0011
<< Binary Left Shift Operator. The left operands value is A << 2 will give 240 which is
moved left by the number of bits specified by the right 1111 0000
operand.
>> Binary Right Shift Operator. The left operands value is A >> 2 will give 15 which is
moved right by the number of bits specified by the right 1111
operand.
>>> Shift right zero fill operator. The left operands value is A >>>2 will give 15 which is
moved right by the number of bits specified by the right 0000 1111
operand and shifted values are filled up with zeros.
Special Operators:

instanceOf Operator: This operator is used only for object reference variables. The operator checks
whether the object is of a particular type(class type or interface type). instanceOf operator is written as:

( Object reference variable ) instanceOf (class/interface type)

Dot Operator: The dot operator (.) is used to access the instance variables and methods of class objects.
Examples: person1.age // Reference to the variable age
person1.salary ( ) // Reference to the method salary( )
It is also used to access classes and sub-packages from a package

Arithmetic Expressions: An arithmetic expression is a combination of variables, constants, and


operators arranged as per the syntax of the language.
Algebraic expression Java Expression ab/c a*b/c
Ab-c a*b-c 3x2+2x+l 3*x*x+2*x+l
(m+n)(x+y) (m+n)*(x+y) x/y+c x/y+c

mnnappaji@gmail.com
30
Evaluation of Expressions: Expressions are evaluated using an assignment statement as
variable = expression;
Variable is any valid Java variable name. When the statement is encountered, the expression is
evaluated first and the result will replaces the previous value of the variable on the left-hand side. All
variables used in the expression must be assigned values before evaluation is attempted.
Examples of evaluation statements are x = a*b-c; y = b/c*a; z = a-b/c+d;

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 as they are encountered. During the second pass, the low
priority operators
Example : x = a-b/3+c*2-l 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 Step l: 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: The precedence is used to determine how expression
involving more than one operator is evaluated. 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 associatively property of an operator.

Category Operator Associativity Rank


Postfix / Highest Precedence ( ) [ ] . (dot operator) Left to right 1
Unary ++ - - ! ~ Right to left 2
Multiplication */% Left to right 3
Additive +- Left to right 4
Shift >> >>> << Left to right 5
Relational > >= < <= Left to right 6
Equality == != Left to right 7
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 ?: Right to left 13
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left 14
Comma , Left to right 15

mnnappaji@gmail.com
31
Introduction
When a program breaks the sequential flow and jumps to another part of the code, it is called branching.
When the branching is based on a particular condition, it is known as conditional branching. If branching
takes place without any decision, it is known as unconditional branching.
There are classified into three statement are classified into three types. They are

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

Decision making with If statement:

The if statement is a powerful decision making statement and is used to


Entry
control the flow of execution of statements. It is basically a two-way
decision statement and is used in conjunction with an expression. It takes
the following form:
False
if (test_expression) Test
It allows the computer to evaluate the expression first and then, Exp. ?
depending on whether the value of the expression is 'true' or 'false', it
transfers the control to a particular statement.

Some examples of decision making using if statements are: True


I. if (room is dark)
put on lights
II. if (age is more than 60) Flow Chart
person is retired Two-way branching

The if statement may be implemented in different forms there are


a. Simple if
b. If ….. else
c. Nested if …. else Entry
d. else if ladder

Simple if statement: If the test expression is true, the


statement block (a single or group of statements) will be True
executed; otherwise the statement block will be skipped and Test
the execution will transfers to the statement-x. The Exp.?
'statement-block' may be a single statement or a group of
statements. The general form of a simple if statement is Statement-block
Syntax:
if(test expression)
{
statement-block;
}
statement-x; Statement-X

mnnappaji@gmail.com
32
int a= 10;
int b = 5;
if (b!=10)
{
double c =a/b
}
System.out.println(c);

If...Else Statement: If the expression is true, then the true block statements will be executed; otherwise the
False Block Statements will be executed. In
both the cases the control is transferred Entry
subsequently to statement x.

Syntax: True False


Test
if(expression is true) Exp.?
{
True-block statements;
} True Block False Block
Else Statements Statements
{
False-block statements; Statement-X
}
statement X
if (Salary<8000)
{
bonus =500;
}
else
{
bonus =800;
}
System.out.println(bonus);

Nested if-else: When a series of decisions are involved, we may have to use more than one if....else
statement in nested form as follows:
The general form is
If (test exp1)
{
if (test exp2)
{
statement-1;
}
else
{
statement-2;
}

mnnappaji@gmail.com
33
}
else
{
statement-3;
}
If test exp-1 is false, the statement-3 is executed. Otherwise it continues with test exp-2. If the test exp-2
is true, the statement-1 will be evaluated otherwise statement-2 will be evaluated and the control is
transferred to the statement-x.

If (a>b&a>c) Else
{ sl=c;
If (b>c sl=b); }
Else Else if (c>a&c>b)
Sl=c; {
} If (a>b sl=a)
Else if (b>a&b>C) Else
{ sl=b
If (a<c sl=a) System.out.println(“Second Largest is” +sl);

Entry

True
False
Test
Exp.1

False True
Test
Statement-3
Exp.2

Statement-2 Statement-1

Statement-X

mnnappaji@gmail.com
34
Else-If Ladder: There is another way of putting together when multipath decisions are involved. A
multipath decision is a chain of ifs in which the statement associated with each else is an if. It takes the
following general form:

The general form is Statement-x;


If (Test exp1) Test expressions are evaluated from the top
Statement-1; down words.
Else
If (Test exp2) If (a>b&a>c)
Statement-2; Big =a;
Else Else If (b>a & b>c);
If (Test exp n) Big=b;
Statement-n; Elseif (c>a&c>b)
Else Big =c
Default statement; System.out.println(“Big ” +big);

mnnappaji@gmail.com
35
Switch Statement: The switch statement tests the value of a given variable (or expression) against a list
of case values and when a match is found, a block of statements associated with that case is executed. The
general form of the switch statement is as shown below:
Switch(expression)
{
case value-1:
block-1;
break;
case value-2:
block-2;
break;
default:
default-block;
}
statement-x;

Entry

Switch
Exp

Exp Value -1
Block -1
Exp Value -2
Block -2
Exp Value -3
Block -3

Block -4

Statement -x

Switch ope
{
Case ‘+’:
Res =a+b;
Break;
Case ‘-’:
mnnappaji@gmail.com
36
Res =a-b;
Break;
Case ‘*’:
Res =a*b;
Break;
Case ‘/’:
Res =a/b;
Break;
}

THE ?: OPERATOR: This operator is a combination of ? and :, and takes three operands. So it is popularly
known as the conditional operator or ternary operator. The general form of use of the conditioned
operator is as follows:
conditional expression ? expressionl : expression2
Ex:
A = 10;
B = 15;
BIG = (A>B) : A : B;
IF (A>B)
BIG = A;
ELSE
BIG = B;

mnnappaji@gmail.com
37
Loop Statement: Loop is a statement, which executes a sequence of statements until some conditions for
the termination of the loop are satisfied. It consists of two segments, one known as the body of the loop
and the other known as the control statement. The control statement tests certain conditions 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 as exit-controlled loop.
In the entry-controlled loop, the control conditions are tested before the start of the loop
execution. If the conditions are not satisfied, then the body of the loop will not be executed.
For Example : For Loop and While Loop
In the exit-controlled loop, the test is performed at the end of the body of the loop and therefore
the body is executed unconditionally for the first time.
For Example : do While Loop

A loop generally includes the four steps:

1. Initialization of a counter.
2. Test for a specified condition for execution of the loop.
3. Execution of the statements in the loop.
4. Incrimination the Counter.

mnnappaji@gmail.com
38
While Statement:
The while loop 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.

Initialization; int i =1;


While (test condition) while (i <=10)
{ {
Body of the loop; S.O.P.(I);
Increment /Decrement i = i++;
} }

Syntax Example

Start

Initialize

False
test Stop

True
Body of Loop

Increment

The do While Statement: The do-while is an exit-controlled loop. This process continues as long as the
condition is true. Based on a condition becomes false, the control is transferred back to a particular point
in the program.

Initialization; int i =1;


Do do
{ {
Body of the loop; S.O.P.(I);
Increment/Decrement i++;
} }
while (test condition); while (i <=10);

Syntax Example
mnnappaji@gmail.com
39
Start

Initialize

Body of Loop

Increment

True
test

False

Stop

Difference between while and do-while loops:

While Do While
It is a looping construct that will execute only if the It is a looping construct that will execute at least
test condition is true. once if the test condition is false.
It is an Entry – controlled loop It is an Exit – controlled loop
It is generally used for implementing common It is typically used for implementing menu-based
looping situations programs where the menu is required to be printed
at least once.
int i =11; int i =11;
while (i <=10); do
{ {
S.O.P.(I); S.O.P.(I);
i++; i++;
} }
s.o.p(“end”); While (i <=10);
} s.o.p(“end”);
Output: End }
Output: 11 end

For Loop: This loop is entry-controlled loop that provides a more concise loop control structure. It
consisting of three expressions. The first expression is used to initialize the index value. The second
expression is used to check whether or not the loop is to be continued and the third expression is used to
change the index value for further iteration. The general form is:
mnnappaji@gmail.com
40
for (intialization; test condition; increment/decrement) for (i=1; i<=10; i++)
{ {
Body of the loop; System.out.println(i);
} }
Syntax: Example

Start

Initialize

Test

Stop
Body of Loop

Increment

The execution of the for statement is as follows:

1. Initialization of the control variables is done first, using assignment statements such as i = 1 and
count = 0.
2. The value of the control variable is tested using the test condition. The test condition is a relational
expression, such as i <=10 that determines when the loop will exit. If the condition is true, then the
body of the loop is executed. After execution continues with the statement that immediately
follows the loop.
3. The control is transferred back to for statement. The control value is incremented using an
assignment statement such as i = i + 1. The control variable is again tested to see whether is
satisfies the loop condition.

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. Exit from a loop can be accomplished by using the break statement. We have already
seen the use of the break in the switch 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.

mnnappaji@gmail.com
41
Skipping a part of a Loop:
During the loop operations, it may be necessary to skip a part of the body of the loop under
certain conditions. The continue, causes the loop to be continued with the next iteration after
skipping any statements in between. The continue statement tells the compiler. "SKIP THE
FOLLOWING STATEMENTS AND CONTINUE WITH THE NEXT ITERATION".
The format of the continue statement is simply
Continue;
Labeled Loops:
In Java, we can give a label to a block of statements. A label is any valid Java variable name. To give a label
to a loop, place it before the loop with a colon at the end.
Example:
for ( ………..)
{
…….
}

Exiting a loop with break statement

outer: for (int m=1; m<11; m++)


{
inner: for (int n=1; n<11; n++)
{
System.out.print(" “+ m*n);
if (m == n )
counter outer;
}
}
. . . . . . . . . . . . . .

loop1: for (int m=1; m<11; m++)


{
Loop2: for (int n=1; n<11; n++)
{
System.out.print(" “+ m*n);
if ( m == n )
break loop1;
}
}

. . . . . . . . . . . . . .

Continue Outer: continue statement terminates the inner loop when m == n and continues with the next
iteration of the outer loop

Break loop causes the execution to break out of both the loops.

mnnappaji@gmail.com
42
Java is a true object-oriented language and therefore the underlying structure of all Java programs
is classes. Anything we wish to represent in a Java program must be encapsulated in a class that defines
the state and behavior of the basic program components known as objects. Classes create objects and
objects use methods to communicate between them.

Classes provide a convenient method for packing together a group of logically related data items
and functions that work on them. In Java, the data items are called fields and the functions are called
methods. Calling a specific method in an object is described as sending the object a message.

Defining a Class: A class is a user-defined data type with a template that serves to define its properties.
Once the class type has been defined, we can create "variables" of that type using declarations that are
similar to the basic type declarations. In Java, these variables are termed as instances of classes, which are
the actual objects

A class is a way to bind the data and its associated methods (functions) together. It allows the data and
functions to be hidden, if necessary from the external use. When defining a class we are creating a new
Abstract Data Type that can be treated like any other built-in data type. A Class Specification has two
parts:
1. Class Declaration
2. Variables or Fields Declaration
3. Method Declaration
Class Declaration: It describes the type and scope of its members. The class function defines describe
how the class functions are implemented. The basic form of a class definition is:
Syntax:
class classname [extends superclassname]
{
[variable declaration;]
[methods declaration;]
}

classname and superclassname are any valid Java identifiers. The keyword extends indicates that the
properties of the superclassname class are extended to the classname class. This concept is known as
inheritance.

Fields Declaration: Data is encapsulated in a class by placing data 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
Class Room
{
int length ,width;
}

Methods Declaration: Methods are necessary for manipulating the data contained in the class. 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

mnnappaji@gmail.com
43
type methodname (parameter-list)
{
method-body;
}

Method declarations have four basic parts:


The name of the method (methodname)
The type of the value the method returns (type)
A list of parameters (parameter-list)
The body of the method

The type specifies the type of value the method would return. This could be a simple data type such as int
as well as any class type. It could even be void type, if the method does not return any value. The
methodname is a valid identifier. The parameter list is always enclosed in parentheses. This list contains
variable names and types of all the values we want to give to the method as input. The variables in the list
are separated by commas. In the case where no input data are required, the declaration must retain the
empty parentheses. The method body actually describes the operations to be performed.
Example
class Rectangle // Class declaration
int length; // Variable declaration
int width;
void getData(int x , int y) // Method declaration
{
length = x ;
width = y ;
}

Creating Objects:
Once a class is defined, an object (which is just variable of class type) can be declared in the same way as
variables of any other type. Creating 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 of the specified
class and returns a reference to that object. Here is an example of creating an object of type student.

For example: student s; // Declares the Object


s=new student ( ); // Instantiate the Object

The first statement declares a variable to hold the object reference and the second one actually assigns
the object reference to the variable.
s=new student ( ); // Instantiate the Object

The method Student( ) is the default constructor of the class. We can create any number of objects of
Rectangle.

Accessing Class Members: Each object containing its own set of variables. All variables must be assigned
values before they are used. We cannot access the instance variables and the method directly, when we
are outside the class.
objectname.variablename = value;
objectname.methodname(parameter-list);
mnnappaji@gmail.com
44
Here objectname is the name of the object, variablename is the name of the instance variable inside the
object that we wish to access, methodname is the method that we wish to call, and parameter-list is a list
of the methodname declared in the class.
Example:
a.x = 4; a.y = 5
a.getdata (4,5);

Member allocation for objects: Memory space for objects is allocated when they are declared and not
when the class is specified. The member functions are created and placed in the memory only once when
they are defined as a part of a class specification. Since all the objects belong to that class use the same
member functions, no separate space is allocated separately for each object.
class Rectangle
int length, width;
void getData(int x, int y)
{
length = x;
width = y;
int rectArea() //
int area = length * width; return (area);
class RectArea
Class with main method
public static void main(String args[ ]
{
int areal,area2;
Rectangle rectl = new Rectangle();
Rectangle rect2 = new Rectangle ();
rectl.length = .15;
rectl.width = 10;
areal = rectl.length * rectl.width;
rect2.getData(20,12);
area2 = rect2.rectArea ();

CONSTRUCTOR: It is a special type of method, called a constructor that enables an object to initialize
itself when it is created. It is distinct from the other member function of the class, and it has the same
name, as its class. It is executed automatically when an object is created. It is generally used to initialize
object member. The constructor has no return value. The constructor of a class is the first member
function to be executed every time an object of that class is defined. The constructor which does not take
arguments explicitly is called default constructor.

class Rectangle
int length, width ;
Rectangle (int x, int y) //Defining constructor
{
length = x ;
width = y ;
}
int rectArea( )
{
return(length * width);
mnnappaji@gmail.com
45
}

class RectangleArea
{
public static void main(string args[ ])
{
Rectangle rectl = new Rectangle (25,10) ; //Calling constructor
int areal = rectl.rectArea( ) ;
System.out.println("Areal = "+ areal) ;
}
}

Output:
Areal = 250

METHODS OVERLOADING
In Java it is possible to create methods that have the same name, but different parameter lists and
different definitions. This is called method overloading. Method overloading is used when objects are
required to perform similar tasks but using different input parameters. When we call a method in an
object, Java matches up the method name first and then the number and type of parameters to decide
which one of the definitions to execute. This process is known as polymorphism.
To create an overloaded method, all we have to do is to provide several different method definitions in
the class, all with the same name, but with different parameter lists. The difference may either be in the
number or type of arguments.

class Room
{
float length ;
float breadth ;
Room(float x, float y) // constructor 1
{
length = x ;
breadth = y ;
}
Room(float x) // constructor 2
{
length = breadth = x ;
}
int area( )
{
return (length * breadth) ;
}
}
Here, we are overloading the constructor method Room( ). An object representing a rectangular room
will be created as
Room rooml = new Room (25. 0,15 . 0) ; // using constructor l
On the other hand, if the room is square, then we may create the corresponding object as
Room room2 = new Room (20.0); // using constructor 2
mnnappaji@gmail.com
46
Static Data Members:
1. It is initialized to zero when the object of its class is created.
2. Only one copy of that member is created for the entire class and is shared by all the objects of that
class.
3. It is visible only within the class, but its lifetime is the entire program.
4. Static variable are normally used to maintain values common to the entire class.
5. Static variables can be defined as static int count;

Static Members:
1. Static methods are called using class name.
2. They can only call other static methods.
3. They can only access static data.
4. They cannot refer to this or super in any way.
Static functions can be defined as

class MathOperation
static float mul(float x, float y)
{
return x*y;
}
static float divide(float x, float y)
{
return x/y ;
}
Class MathApplication
{
public void static main(string args[ ])
{
float a = MathOperation.mul(4.0,5.0) ;
float b = MathOperation.divide(a,2.0) ;
System.out.println("b = "+ b) ;
}
}

NESTING OF METHODS:
A method can be called by using only its name by another method of the same class. This is known as
nesting of methods.

Class Nesting
{
int m, n;
Nesting(int x, int y)
{
m = x;
n = y;
}
int largest( )
{
if (m >= n)
mnnappaji@gmail.com
47
return(m);
else
return(n);
}
void display( )
int large = largest ( ) ;
System.out.println("Largest value = " +large)
}
}
class NestingTest
{
public static void main(String args[ ])
{
Nesting nest = new Nesting(50, 40);
nest.display( );
}
}

INHERITANCE: Inheritance is the most powerful feature of Object Oriented Programming. Java strongly
supports the concept of reusability. Java classes can be reused in several ways. This is basically done by
creating new classes, reusing the properties of existing ones. It is the process of the creating new classes,
called derived classes from existing classes. The mechanism of deriving a new class from an old one is
called inheritance. The old class is known as the base class or super class or parent class and the new one is
called the subclass or derived class or child class.

The inheritance allows subclasses to inherit all the variables and methods of their parent classes. A class
can also inherit properties from more than one class or more than one level. Inheritance may take
different forms:
1. Single inheritance (only one super class)
2. Multiple inheritance (several super classes)
3. Hierarchical inheritance (one super class, many subclasses)
4. Multilevel inheritance (Derived from a derived class)
5. Hybrid Inheritance ()

Single Inheritance: A derived class with only one base class is called single inheritance.

B
Multiple Inheritance: A derived class with several base classes is called multiple inheritance.

A B

mnnappaji@gmail.com
48
Hierarchical Inheritance: The base class includes all the features that are common to the sub classes. This
process is called Hierarchical Inheritance.

B C D

Multilevel Inheritance: The mechanism of deriving a class from another derived class is known as a
multilevel inheritance.

C
Hybrid Inheritance: Hybrid inheritance is the combination of multilevel and multiple inheritance.

B C

D
Note :

1. Multiple Inheritance is not supported in Java.


2. So, that Multiple Inheritance & Hybrid inheritance will not work
3. In Java Substitution of multiple Inheritance Interfaces will work.

Defining Derived Class or Sub Class: A derived class can be defined by specifying its relationship with
the base class in addition to its own details.

Syntax: class derived_class_name extends base_class_name


{
Variables declaration;
Methods declaration;
}
The keyword extends signifies that the properties of the base_class_name are extended to the
derived_class_name. The derived class will now contain its own variable and methods as well those of the
super class.

mnnappaji@gmail.com
49
class Room
{
int length;
int breadth;
Room(int x,,int y)
{
length = x;
breadth = y;
}
int area( )
{
return (length * breadth);
}
}
class BedRoom extends Room // Inheriting Room
{
int height;
BedRoom(int x, int y, int z)
{
super (x,y); / / pass values to superclass

height = z;
}
int volume( )
{
return (length * breadth * height);
}
class InherTest
public static void main(String args[ ])
{
BedRoom rooml = new BedRoom(12,12,10) ;
int areal = rooml.area ( ); // superclass method
int volumel = rooml .volume ( ); // baseclass method
System.out.println("Areal = "+ areal);
System.out.println("Volumel = "+ volumel);

Output
Areal =144 Volume = 1440

Sub Class Constructor:


A subclass constructor is used to construct the instance variables of both the subclass and the superclass.
The subclass constructor uses the keyword super to invoke the constructor method of the superclass. The
keyword super is used subject to the following conditions.
super may only be used within a subclass constructor method.
The call to superclass 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 variable declared
in the superclass.

mnnappaji@gmail.com
50
Overriding Methods
Defining a method in the subclass that has the same name, same arguments and same return type as a
method in the superclass. when a method is called, the method defined in the subclass is invoked and
executed instead of the one in the superclass. This is known as overriding.

class Super
{
int x ;
Super(int x)
{
this.x = x ;
}
void display ( ) / / method defined
System.out.println("Super x = " + x);
}
class Sub extends Super
int y ;
Sub(int x, int y)
super(x) ;
this.y = y ;
}
void display( ) // method defined again
System.out.println("Super x = " + x) ;
System.out.println("Sub y = " + y) ;
}
}
class OverrideTest
public static void main(String args[ ])
{
Sub si = new Sub (100,200) ;
si.display( );
}
}
Output
Super x = 1OO '
Sub y = 200
Note: that the method display() defined in the subclass is invoked.

Final Variables and Methods: All methods and variables can be overridden by default in subclasses. If
we wish to prevent the subclasses from overriding the members of the superclass, we can declare them
as final using the keyword final as a modifier.
Example:
final int SIZE = 100 ;
final void showstatus ( ) {…………………}

Final Classes: Sometimes we may like to prevent a class being further sub class for security reasons. A
class that cannot be sub class is called a final class.
final class Aclass {…………………}
final class Bclass extends Someclass {…………………}
mnnappaji@gmail.com
51
Finalizer Methods: Constructor method is used to initialize an object when it is declared. This process is
known as initialization. Similarly, Java supports a concept called finalization, which is just opposite to
initialization. In order to free up the memory resources used by the objects, we must use a finalize
method. The finalize method should explicitly define the tasks to be performed.

Abstract Methods and Classes: We can indicate that a method must always be redefined in a subclass,
thus making overriding compulsory. This is done using the modifier keyword abstract in the method
definition.
Example: abstract class Shape
{
abstract void draw();
}

We cannot use abstract classes to instantiate objects directly.


Shape s = new Shape( ) ; is illegal because shape is an abstract class.
The abstract methods of an abstract class must be defined in its subclass.
We cannot declare abstract constructors or abstract static methods.
The colon indicates that the derived class name is derived from the base class name.

Visibility Control:

Public Access: A variable or method declared has the widest possible visibility and accessible
everywhere.

Friendly Access: When no access modifier is specified, the member defaults to a limited version of public
accessibility known as "friendly" level of access. The difference between the "public" access and the
"friendly" access is that the public modifier makes fields visible in all classes, regardless of their packages
while the friendly access makes fields visible only in the same package, but not in other packages. (A
package is a group of related classes stored separately.)

Protected Access: The visibility level of a "protected" field lies in between the public access and friendly
access. That is, the protected modifier makes the fields visible not only to all classes and subclasses in the
same package but also to subclasses in other packages. Note that non-subclasses in other packages
cannot access the "protected" members.

Private Access: Private Fields accessible only within their own class. They cannot be inherited by
subclasses and therefore not accessible in subclasses.

Private Protected Access: This modifier makes the fields visible in all subclasses regardless of what
package they are in. Remember, these fields are not accessible by other classes in the same package.

Input and Output Statements: java.lang package consists a class called ‘System’ which contains console
I/O methods. If we want to take the information from the keyboard and display the information on the
screen, Java uses Stream objects. The system provides three basic streams. These are
a) System.in b)System.out c)System.err
System.in refers to the standard input stream, System.out refers to the standard output stream and
System.err refers to the standard error stream.
System.out class consists of two methods to print the strings and values on the screen.

mnnappaji@gmail.com
52
Arrays: An array is a collective name given to a group of similar elements, whereas a variable is any
entity that may change during program execution. An array is a variable that is capable of holding many
values; whereas an ordinary variable can hold a single value at a time. For example, an array initialization
would be int a[10];
For which there are ten storage locations reserved, where ten different values can be stored
belonging to the same type. Whereas an ordinary variable initialization would be int n; and only one
storage location is reserved and can hold only one value at a time.

One-Dimensional Arrays: An Array in which list of elements are stored in continuous memory locations
and accessed using only one subscript. Ex: int a[10];

Declaration of One-Dimensional Array:


type array_name[ ] ; type[ ] array_name;
Where type is the data type of array elements, array_name is name of array variable. Remember,
we do not enter the size of the arrays in the declaration.

Creation of memory locations: After declaring an array, we need to create it in the memory. Java allows
us to create arrays using a new operator only.
array_name new type [size];
Ex: a = new int a[5] Here array ‘a’ which can hold 5 integer elements.
The two statements may be combined as follows:
Type array_name [ ] = new type [size];
int a[ ] = new int [4];

Initialization of One Dimensional Array: Assigning values to an array created is known as initialization.
array_name [subscript] = value ;
Ex: a[0] = 7; a[1] = 8; a[2] = 8; a[3] = 9;

type array_name[ ] = (list of elements separate by commas);

int a [ ] = { 7, 8, 8, 9 };
In the above example, four elements are stored in an array ‘a’. the array elements are stored in
contiguous memory locations. The array elements are read from o i.e. a[0] is assigned the value 7.
Similarly a[1] is assigned the value 8, a[2] is 8 and a[3] is 9.

a[0] a[1] a[2] a[3]


7 8 8 9

 Suppose the list of elements specified is less than the size of an array then only that many
elements are initialized. The remaining elements are assigned garbage values.
 Subscript of an array is an integer expression, integer constant or integer variable, that refers to
different elements in the array consider an element. Here array subscripts start at zero. Therefore
the elements are a[0],a[1],…..,a[3].

mnnappaji@gmail.com
53
Array length: In Java, all arrays store the allocation size in a variable named length. We can obtain the
length of the array a using a.length.
Example int s = a.length
for (i=0; i<=n;i++)
System.out.print(“ “ +a[i]);

Sorting a list of numbers

class NumberSorting
{
public static void main(String args[ ])
{
int a[ ] = { 94,92, 24, 44, 55 };
int n = a.length;
System.out.print("Given list : ") ; Given List 94 92 24 44 55
for (int i = 0; i < n; i++)
{ Sorted List 94 92 55 44 24
System.out.print(" " + a[i]);
}
System.out.print("/n");
for (int i = 0; i < n; i++)
{
for (int j = i+1; j < n; j++)
{
if (number[i] < number[j])
{
/ / Interchange values
int temp = number[i];
number [i] = number [j];
number[j] = temp;
}
}
}
System.out.print ("Sorted''list : ") ;
for (int i = 0; i < n; i++)
{
System.out.print(" " + number[i]);
}
System.out.println (“ ");
}
}

TWO-DIMENSIONAL ARRAYS: An array in which list of elements are stored in some rows and columns
(matrix and accessed using two subscripts.

Declaration of Two-Dimensional Array:


type array_name[ ] [ ];
Where type is the data type of array elements, array_name is name of array variable. Remember,
we do not enter the size of the arrays in the declaration.
mnnappaji@gmail.com
54
Creation of memory locations: After declaring an array, we need to create it in the memory. Java allows
us to create arrays using a new operator only.
array_name new type [row_size] [col_size];
Ex: a = new int a[5] [3] Here array ‘a’ which can hold 5 x 3 = 15 integer elements.
The two statements may be combined as follows:
Type array_name [ ] [ ] = new type [row_size] [col_size];
int a[ ] [ ] = new int [5] [3];

Initialization of Two-Dimensional Array: Assigning values to an array created is known as initialization.


array_name [subscript] [subscript] = value ;
Ex: a [0] [0] = 5; a [0] [1] = 8;

type array_name[ ] = {{list of elements in row} {list of elements in column}};


int a [ ] [ ] = {{0,-1,6,8},{4,4,5,6},{-1,9,-8,1}}
0 -1 6 8
Subscripts can also be reflected in for loops that the array a[0] [0] a[0] [1] a[0] [2] a[0] [3]
elements. 4 4 5 6
for (i=0;i<r;i++) a[1] [0] a[1] [1] a[1] [2] a[1] [3]
for(j=0;j<c;j++) -1 9 -8 1
System.out.print(“ ” +a[i][j]); a[2] [0] a[2] [1] a[2] [2] a[2] [3]

Multiplication Table
class Table
{
final static int r =10;
final static int c = 10;
public static void main(String args[])
{
Int a[ ][ ] = new int [r] [c];
System.out.println(“Multiplication Table:”);
for (int i = 1; i<r; i++)
{
for (int j = 1; j<c; j++)
{
a [i] [j] = i * j ;
System.out.println(“ ”+a[i][j]);
}
System.out.println(“ ”);
}
}
}

STRINGS: String manipulation is the most common part of many Java programs. Strings represent a
sequence of characters. 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 is not NULL terminated.
String stringName; String firstName;
StringName = new String ("string") firstName = new String("Appaji");
Syntax : Example:
mnnappaji@gmail.com
55
These two statements may be combined as follows:
String firstName = new String("Appaji");
It is possible to get the length of string using the length method of the String class.
int m = firstName.length ( );
String c = a + b;

String Arrays: We can also create and use arrays that contain strings.
String itemArray[ ] = new String[3];
will create an itemArray of size 3 to hold three string constants.

String Methods: The String class defines a number of methods that allow us to accomplish a variety of
string manipulation tasks.

Method Task performed


s2 = s1.toLowerCase; Converts the string s1 to all lowercase
s2 = s1.toUpperCase; Converts the string s1to 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 the 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 if sl< s2, positive if s1 > s2, and zero if s1 is equal s2
s1.cqncat(s2) Concatenates s1and s2
s1.substring(n) Gives substring starting from nth character
s1.substring(n, m) Gives substring starting from nth character up to mth (not including mth)
String.ValueOf(p) Creates a string object of the parameter p (simple type or object)
p.toString( ) Creates a string representation of the object p
s1.indexOf('x') Gives the position of the; first occurrence of 'x' in the string s1
s1.indexOf ('x',n) Gives the position of 'x' that occurs after nth position in the string s1
String.ValueOf(Variable) Converts the parameter value to string representation

class StringOrdering
{
static String name[] = {"Madras", "Delhi", "Ahmedabad","Calcutta", "Bombay"};
public static void main(String args[ ])
{
int size = name.length;
String temp = null;
for (int i = 0; i < size; i++)
for (int j = i+1; j < size; j++)
{
if (name[j].compareTo(name[i]) < 0)
{
temp = name[i];
name[i] = name[j];
name[j] = temp;
}
mnnappaji@gmail.com
56
}
}
for (int i = 0; i < size; i++)
{
System.out.println(name[i]);
}
}
}

StringBuffer Class: StringBuffer is a peer class of String. While String creates strings of fixedlength,
StringBuffer creates strings of flexible length that can be modified in terms of both length and content.
We can insert characters and substrings in the middle of a string, or append another string to the end.
Method Task performed
s1.setChartAt(n, 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
s1.setLength(n) Sets the length of the string s1 to n. If n<s1 .length () s1 is truncated. If n>s1. length ()
zeros are added to s1

VECTORS: This class can be used to create a generic dynamic array known as vector that can hold objects
of any type and any number. Vectors are created like arrays as follows:
Vector a = new Vector( ); // declaring without size
Vector a = new Vector(3); // declaring with size
Advantages:
1. It is convenient to use vectors to store objects.
2. A vector can be used to store a list of objects that may vary in size.
3. We can add and delete objects from the list as and when required.

The major constraint in using vectors is that we cannot directly store simple data type in a vector,
we can only store objects. Therefore, we need to convert simple types to objects. This can be done using
the wrapper classes

import java.util.*;
class LanguageVector
public static void main(String args[ ])
Vector list = new Vector();
int length = args.length;
for (int i = 0; i < length; i++)
list.addElement(args[i]);
list.insertElementAt("COBOL",2);
int size = list.size( );
String listArray[ ] = new String[size];
list.copylnto(listArray);
System.out.println("List of Languages");
for (int i = 0; i < size; i++)
System.out.println(listArray[i]) ;
C:\JAVA\prog>java LanguageVector Ada BASIC C++ FORTRAN Java
List of Languages Ada BASIC COBOL C++ FORTRAN Java

mnnappaji@gmail.com
57
WRAPPER CLASSES: Vectors cannot handle primitive data types Simple Type Wrapper Class
like int, float, long, char, and double. Primitive data types may be boolean Boolean
converted into object types by using the wrapper classes char Character
contained in the java.lang package. double Double
float Float
Auto boxing & un-boxing: The compiler generates a code int Integer
implicitly to convert primitive type to the corresponding wrapper long Long
class type and vice-versa. Java compiler provides restrictions to
perform the following conversions.

1. Convert from null type to any primitive type.


2. Convert to the null type other than the identity conversion.
3. Convert from any class type C to any array type if C is not compiler.

Enumerated Types: Another user defined data type is enumerated data type provided by ANSI standard.
public enum identifier (value1, value2….)
The identifier is a user-defined enumerated data type, which can be used to declare variables that
can have one of the values enclosed within the braces known as enumeration constant.

Advantages:
 Compile time type safety
 We can use the enum keyword in switch statements
Example: public enum day (Monday, Tuesday, Wednesday,…..)

Use of enum type data:

public class Workingdays


{
enum day (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday)
public static void main(String args[ ])
{
for(Days d : Days.values( ))
{
Weekend(d);
}
}
private static void weekend (Days d)
{
if(d.equals(Days.Sunday))
System.out.println(d + “ is a Holiday”)
else
System.out.println(d + “ is not Holiday”)
}
}

mnnappaji@gmail.com
58
Interfaces: An interface is basically a kind of class. The difference is that interfaces define only abstract
methods and final fields. This means that interfaces do not specify any code to implement these methods
and data fields contain only constants.
interface interface_name
{
variable declaration ;
method declaration;
}
Here, interface is the keyword and interface name is any valid Java identifier. Variables are declared as
follows:
Static final type variable_Name = value;
Note: All variables are declared as constants. Method declaration will contain onLy a list of methods
without any body statement.
return_type method_name (parameter_list);
Example:
interface item
{
Static final int code = 1234;
Static final string name="Pen";
Void display ( );
}
Difference Between Class and Interface:
Class Interface
The members of a class can be constant or The members of an interface are always declared
variables. as constant, i.e., their values are final.
The class definition can contain the code for each of
The methods in an interface are abstract in nature,
its methods. That is, the methods can be abstract or
i.e., there is no code associated with them. It is later
non-abstract. defined by the class that implements the interface.
It can be instantiated by declaring objects. It cannot be used to declare objects. It can only be
inherited by a class.
It can use various access specifiers like public, It can use the public access specifier.
private or protected.
Extending Interfaces: Like classes, Interfaces can also be extended. An interface can be sub interfaced
from other interfaces. The new sub interface will inherit all the members of the super interface in the
manner similar to subclasses. This is achieved using the keyword extends as
interface name2 extends namel
{
Body of name2;
}
We can put all the constants in one interface and the methods in the other. This will enable us to use the
constant in classes where the methods are not required.
interface item
{
Static final int code = 1234;
mnnappaji@gmail.com
59
Static final string name="Pen";
interface cost extends item
{
void display();
}
Implementing Interfaces: Interfaces are used as super classes whose properties are inherited classes.
class classname implements interfacename
{
Body of the class
}
Here the class class_name implements the interface interface_name.
class class_name extends super_calss
implements interfacel, interface2 , ...
{
body of class name
}
When a class implements more than one interface, they are separated by a comma.

interface Area // interface defined


{
final static float PI=3.14f;
float compute(float x, float y) ;
}
class Rectangle implements Area // interface implemented
{
public float compute(float x, float y)
{
return (x*y);
}
}
class Circle implements Area // other interface implemented
{
public float compute(float x,float y)
{
return (PI*x*y) ;
}
}
class Interface
{
public static void main(String args[ ])
{
Rectangle r=new Rectangle( );
Circle c=new Circle( );
Area a; // Interface object
a=r // area refers to r object
System. out .println ("Area of Rectangle="+ a .compute (20, 20) );
a=c;
System.out.println ("Area of Circle="+ a.compute (20, 0) );
}
}
Output: Area of Rectangle: 400 Area of Circle: 1256
mnnappaji@gmail.com
60
Any number of dissimilar classes can implement an interface. However, to implement the methods
we need to refer to the class objects as types of the interface rather than types of their respective classes.
Note that if a class that implements an interface does not implement all the methods of the interface, then
the class becomes an abstract class and cannot be instantiated

Accessing interface variables: interfaces can be used to declare a set of constants that can be used in
different classes. The interfaces do not contain methods. The constant values will be available to any class
that implements the interface. The values can be used in any method, as part of any variable declaration.

interface A
{
int m=44;
int n=55;
}
class B implements A
{
int x=m;
void methodB (int size)
{
………………
………………
if(size<n)
}
}

Implementing multiple inheritance

class Student
{
int rno;
void get(int n)
(
rno=n;
}
void put ( )
{
System.out.println("Roll No:"+rno);
}
}
class Test extends Student
{
float m,p,cs;
void getMarks(float ml, float m2, float m3)
{
m=ml; p=m2; cs=m3;
}
void putMarks( )
{
mnnappaji@gmail.com
61
System.out.println ("Marks Obtained”) ;
System.out.println ("Maths:"+ m) ;
System.out.println ("Physics:"+ p);
System.out. printin ("Computers : "+ cs)
}
}
interface Sports
{
Final static float sportWt=6.0f;
void putwt ( );
}
class Results extends Test implements Sports
{
Final static float total;
public void putwt( )
{
System.out.println ("Sports Weight age ="+sportwt);
}
Void display()
{
total=m+p+cs+sportwt;
put ( ) ;
putMarks( );
putWt( );
System.out.println(Total Score:"+ total;)
}
Class Hybrid
{
public static void main(String args [ ])
{
Results s=new Results();
s.get(2037);
s.getMarks(87.5f, 82.0f, 99.0f);
s.display();
}
}

Output:

Roll NO : 2037
Marks Obtained

Maths = 87.5
Physics = 82
Computers = 99
Sports Wt = 6
Total score = 274.5

mnnappaji@gmail.com
62
Package: Grouping a variety of classes and / or interfaces together is known as package. The grouping is
usually done according to functionality.
Advantages:
1) The classes contained in the packages of other programs can be easily reused.
2) In packages, classes can be unique compared with classes in other packages.
3) Packages provide a way to hide classes thus preventing other programs or packages from
accessing classes that are meant for internal use "only.
4) Packages also provide a way for separating "design" from coding. First we can design classes
and decide their relationships and then we can implement the Java code needed for the
methods.
Java packages are classified into two types.
1) Java API Packages
2) User defined packages.
Java API Packages: Java API provides a large number of classes grouped into different packages
according to functionality. The packages are organized in a hierarchical structure.

Java

lang util io awt net applet

Package Name Contents


java.lang Language support classes. There are classes that java compiler itself uses and
therefore they are automatically imported. They include classes for primitive types,
strings, math, functions, threads and exception
java.util Language utility classes such as vectors, hash tables, random numbers, date etc.
java.io Input/output support classes. They provide facilities for the input and output of data.
java.awt Set of classes for implementing graphical user interface. They include classes for
windows, buttons, lists, menus and so on.
java.net Classes for networking. They include classes for communicating with local computer
as well as internet servers.
java.applet Classes for creating and implementing applets.

Using System packages: There are two ways of accessing the classes stored in a package. The first
approach is to use the fully qualified class name of the class that we want to use. This is done by using the
package name containing the class and then appending the class name to it using the dot operator. For
example, if we want to refer to the class color in the awt package.
java.awt.color
Note that awt is a package within the package java and the hierarchy is represented by separating the
level with dots.
import packagename.classname (Or) import package_name.*
mnnappaji@gmail.com
63
These are known as import statements and must appear at the file, before any class declarations import
is a keyword.
import java.awt.color;
import java.awt.*;
Naming convention: Packages can be named using the standard Java naming rules. By convention,
however, packages begin with lowercase letters. This makes it easy for users to distinguish packages
names from class names when looking at an explicit reference to a class.
java.lang.Math.sqrt (x);
Creating Packages: We must declare the name of the package using the package keyword followed by a
package name. This must be the first statement in a Java source file. Then we define a class, just as we
normally define a class.
package firstPackage;
public class FirstClass
{
body of class
)
Here the package name is firstPackage. The class FirstClass is now considered a part of this
package. This listing would be saved as a file called FirstClass. Java and located in a directory named
firstPackage. When the source file is complied, Java will create a .class file and store it in the same
directory.
Remember that the .class file must be located in a directory that has the same name as the
package, and this directory should be a subdirectory of the directory where classes that will import the
package are located.

Steps for creating packages:


1) Declare the package at the beginning of a file using the following syntax.
package packagename;
2) Define the class that is to be put in the package and declare it public.
3) Create a subdirectory under the directory where the main source files are stored.
4) Store the listing as the classname .java file in the subdirectory created.
5) Compile the file. This creates .class file in the subdirectory.

Remember that case is significant and therefore the subdirectory name must the package name
exactly. Java also supports the concept of package hierarchy. This is done by specifying multiple names in
a package statement, separated by dots. Example:
package firstPackage. secondPackage;

Accessing a Package: The import statement can be used to search a list of packages for a particular class.
The general form of import statement for searching a class is as following:

import packagel [.package2][.package3].classname;

Here packagel is the name of the top level package, package2 is the name of the package that is inside the
packagel, and so on. We can have any number of packages in a package hierarchy. Finally, the explicit
classname is specified. Note that the statement must end with a semicolon (;). The import statement
should appear before any class definitions in a source file. Multiple import statements are allowed.

import firstPackage.secondPackage.MyClass;

mnnappaji@gmail.com
64
Using a Package:
package packagel
public class CiassA
{
public void displayA( )
{
System.out.println("Class A");
}
}

This source file should be named classA.java and stored in the subdirectory package1 as slated earlier.
Now compile this Java file. The resultant classA.class will be stored in the same subdirectory.
import package1.ClassA;
class packagelTest1
{
public static void main(String args[ ])
{
CiassA objectA = new ClassA( );
objectA.displayA( );
}
}
Here the program that imports the class classA from the package package1. The source file should
be saved as PackageTest.java and then compiled. The source file and the compiled file would be saved in
the directory of which package1 was a subdirectory,

Adding a class to a package:


Package p1;
Public CiassA
{
Body of A;
}
The package p1 contains one public class by name A. Suppose we want to add another class B to
this package.
1. Define the class and make it public.
2. Place the package statement.
Package p1;
before the class definition as follows:
package p1;
public classB
{
//body of B;
}
3. Store this as B.java file under the directory p1.
4. Compile B.java file. This will create a B.class file and place it in the directory p1.
Now the package p1 will contain both the classes A and B. Statement like import pi.*
Steps for create a package with multiple public classes in it.
1. Decide the name of the package.
2. Create a subdirectory with this name under the directory where main source files are stored.
mnnappaji@gmail.com
65
3. Create classes that are to be placed in the package in separate source files and declare the package
statement package packagename; at the top of each source file.
4. Switch to the subdirectory created earlier and compile each source file. When completed, the
package would contain .class files of all the source files.

Hiding Classes:
When we import package using asterisk (*), all public classes are imported. However, we may prefer to
"not import" certain classes. That is, we may like to be hide these classes from accessing from outside of
the package.
packagel p1;
public class X //public
{
// body of X;
}
class Y // hidden
{
// body of Y
}

Static import: Static import is another feature eliminates the need of qualifying a static member with the
class name. The static import declaration is similar to that of import. We can use the import statement to
import class from packages and use them without qualifying the package: Similarly, we can use the static
import statement to import static members form classes and use them without qualifying the class name.

import static package-name. subpackage-name. class-name. staticmember-name;


(or)
import static package-name. subpackage-name.class-name.*;

Use of Static Import Program:


import static Java . lang .Math.*;
public class mathop
{
public void circle(double r)
{
double area=PI*r*r*;
System.out.println("Area = "+area); // Using Static Members
}
public static void main(String args[ ])
{
mathop obj=new mathop( );
obj.circle (2,3);
}
}

Output:
Area = 16.61902513749002

mnnappaji@gmail.com
66
The ability to execute several programs simultaneously is known as multitasking. In
System’s terminology, it is called multithreading. It is a conceptual programming which can be
implemented at the same time in parallel.
In computers, we have only a single processor and therefore, the processor is doing only one task
at a time. However the processor switches between the processes so fast that it appears that all of them
are being done simultaneously.
A thread is similar to a program that has a single flow of control. A unique property of Java is its
support for multithreading. Java enables us to use multiple flows of control in developing programs. Each
flow of control may be thought of as a separate tiny program known as a thread that runs in parallel. A.
program that contains multiple flows of control known as Multithreaded Program.
Once initiated by the main thread, the threads A,B and C run concurrently and share the resources
jointly. The ability of a language to support multithreads is referred to as concurrency. Since threads in
Java are subprograms of a main application program and share the same memory space, they are known
as lightweight threads or lightweight processes.

Advantages of Multithreading:
Multithreading is a powerful programming tool that makes Java distinctly different from other
programming language.
It enables programmers to do multiple things at one time.
They can divide a long program into threads and execute them in parallel.
Threads are extensively used in java-enabled browsers such HotJava.

Difference between multithreading and multitasking

Multithreading Multitasking
It is a programming concept in which a program or It is an operating system concept in which multiple
a process is divided into two or more subprograms tasks are performed simultaneously.
or threads that are executed at the same time in
parallel.
It supports execution of multiple parts of a single It supports execution of multiple programs
program simultaneously. simultaneously.
The processor has to switch between different The processor has to switch between different
parts or threads of a program. programs or processes.
It is highly efficient. It is less efficient in comparison to multithreading.
A thread is the smallest unit in multithreading. A program or process is the smallest unit in a
multitasking environment.
It helps in developing efficient programs. It helps in developing efficient operating systems.
It is a cost-effective in case of context switching. It is expensive in case of context switching.

Creating Threads: Threads are implemented in the form of objects that contain a method called run().
The run () method is the heart and soul of any thread. It makes up the entire body of a thread and is the
only method in which the thread's behavior can be implemented.
public void run( )
{
statements for thread
}

mnnappaji@gmail.com
67
The run ( ) method should be invoked by an object of the concerned thread. This can be achieved
by creating the thread and initiating it with the help of another thread method called start().

1. By creating a thread class: Define a class that extends Thread class and override its run() method
with the code required by the thread.
2. By converting a class to a thread: define a class that implements Runnable interface. The Runnable
interface has only one method, run() that is to be defined in the method with the code to be
executed by the thread.

Extending the thread class: We can make our class runnable as thread by extending the class java.
lang.Thread. This gives us access to all thread methods directly.
1. Declare the class as extending the Thread class.
2. Implement the run() method that is responsible for executing the sequence of code that the thread
will execute.
3. Create a thread object and call the start (.) method to initiate the thread execution.

Declaring the class:


Class MyThread extends Thread
{
. . . .. . ...
. . . .. . ...
}

Implementing the run ( ) method:

public void run ( )


{
. . . .. . ...
. . . .. . ... // Thread code here
. . . .. . ...
}

Starting New Thread:

MyThread aThread = new MyThread ( );


aThread . start ; // invoking run() method.

An Example of using the Thread class:


import java.lang.Thread;
class A extends Thread
{
public void run()
{
for(int i=1; i<=5; i + +)
{
System.out.println("Thread A : i =" + i) ;
System.out.println("Exit from A");
}
}
mnnappaji@gmail.com
68
class B extends Thread
{
public void run() {
for(int j = l; j<=5; j++)
{
System.out.println("Thread B: j=" + j);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run( )
{
for(int k=1;k<=5;k++)
{
System.out.println ("Thread C: k=" + k);
}
System.out.println("Exit from C");
}
}
Class Threadtest
{
public static void main(String args [ ])
{
A tl =new A( );
B t2 =new B( );
C t3 =new C( );
tl.start( );
t2.start ( ) ;
t3.start( );
}
}
Note: Output from the threads is not sequential. They do not follow any specific order. They are running
independently of one another and each executes whenever it h.as a chance.

Stopping and blocking a thread: Whenever we want to stop a thread from running state, then call
stop( ) method. aThread.stop ( )
This statement causes the thread to move to the dead state. A thread will also move to the dead state
automatically when it reaches the end of its method.

Blocking a thread: A thread can also be temporarily suspended or blocked from entering into the
mnnabie and subsequently running state by using either of the following thread methods:
sleep ( ) // blocked for a specified time
suspend ( ) // blocked until further order
wait( ) //blocked until certain condition occurs
These methods cause the thread to go into the blocked state. The thread will return to the runnable state
when the specified time is elapsed in the case of sleep ( ), the resume ( ) method is invoked in the case of
suspend ( ), and the notify ( ) method is called in the case of wait ( ).
mnnappaji@gmail.com
69
Life cycle of a thread: During the life of a thread, there are many states it can enter. They Include:

Newborn state.

Runnable state

Running state.

Blocked state.

Dead state.

1) Newborn state: When we create a thread object, the thread is born


and is said to be in newborn state. The thread is not yet scheduled for
running. At this state, we can do
 Schedule it for running using start () method
 Kill it using stop () method.
If scheduled, it moves to the runnable state. If we attempt to-use
any other method at this stage, an exception will be thrown.
Scheduling a newborn thread.

2) Runnable state: The runnable state means that


the thread is ready for execution and is waiting
for the availability of the processor. That is, the
thread has joined the queue of threads that are
waiting for execution. If all threads have equal
priority, then they are given time slots for
execution in round robin fashion, i.e. first-come, Relinquishing control using yield ( ) method
first-serve manner. The thread relinquishes control joins the queue at the end and again waits for its
turn. This process of assigning time to threads is known as time-slicing.
If we want a thread to relinquish control to another thread of equal priority before its turn comes.
We can do so by using the

3) Running state: Running means that the processor has given its time to the thread for its execution.
The thread runs until it relinquishes control on its own or It is preempted by a higher priority thread.

a) It has been suspended using suspend ( ) method. A suspended thread can be revived by using the
resume ( ) method.

Relinquishing control using suspend( ) method

mnnappaji@gmail.com
70
b) It has been made to sleep. We can put a thread to sleep for a specific time period using the method
sleep (time). The thread re-enters the runnable state as soon as this time period is elapsed.

Relinquishing control using sleep( ) method

c) It has been to wait until some even; occurs. This is done using the wait ( ) method. The thread can
be scheduled to run again using the notify ( ) method.

Relinquishing control using wait( ) method

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, or waiting in
order to satisfy certain requirements.
5) Dead State: Every thread has a life cycle. A running ends its life when it has completed executing its
run() method. It is a natural death. However, we can kill it by sending the stop message to it at any
state.

Example for Using thread methods:

import java.lang.Thread;
class A extends Thread
{
public void run ( )
{
for(int i=1; i<=5;i++)
{
if (i==1)
yield( );
System.out.println(“\tFromThread A: i=" + i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run( )
{
for(int j=1;j<=5;j++)
{
mnnappaji@gmail.com
71
System.out.println("\t FromThread B: j=" + j);
if (j==3) stop( ) ;
}
System.out.println("Exit from B");
}
class C extends Thread
{
public void run( )
{
for(int k=1;k<=5;k++)
{
System.out.println("\t From Thread C: k=" + k);
if (k==l)
try
{
sleep (1000);
}
catch(Exception e)
{
}
System.out.println("Exit from C");
}
Class ThreadMethods
(
public static void main(String args [ ])
{
A tA =new A( );
B tB =new B( );
C tC =new C( );
System.out.println("Start thread A");
tA. start ( );
System.out..println("Start thread B");
tB.start( );
System.out.println("Start thread C") ;
tC.start( );
System.out.println("End of main thread");
}

Thread Exceptions: That the call to sleep ( ) method is enclosed in a try block and followed by a catch
block. This is necessary because the sleep ( ) method throws an exception, which should be caught. If we
fail to catch the exception, program will not compile.
Java run system will throw IlIegalTheadStateException whenever we attempt to invoke a method
that a thread cannot handle in the given state. For example a sleeping thread cannot deal with the
resume ( ) method because a sleeping thread cannot receive any instructions. The same is true with the
suspend ( ) method when it is used on a blocked thread.
Whenever we call a thread method that is likely to throw an exception, we have, to supply an
appropriate exception handler to catch it. The catch statement may take one of the following forms:
Catch (ThreadDeath e)

mnnappaji@gmail.com
72
{
...... // Killed thread
}
catch(InterruptedException e)
{
. . . . // Cannot handle it in the current state
}
catchdllegalArgumentException e)
{
. . . . // Illegal Method argument
}
catch(Exception e)
{
. . . . // Any other
}
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 the priority of a thread using the setPriority () method as follows:
ThreadName. setPriority (intNumber)
The intNumber is an integer value to which the thread's priority is set. The Thread class defines several
priority constants:
MIN_PRIORITY = 1 NORM_PRIORITY = 5 MAX_PRIORITY = 10
The intNumber may assume one of these constants or any value between 1 to 10. Note that the default
setting is NORM_PRIORITY. Whenever multiple threads are ready for execution, the Java system chooses
the highest priority thread and executes it.
a. It stops running at the end of run().
b. It is made to sleep using sleep().
c. It is told to wait using wait().

Setting Thread Priority:


Syntax : Threadname.setPriority (Priority);
Ex : Thread1.setPriority(0);

Getting Thread Priority:


Syntax : Threadname.getPriority ( );
Ex : Thread1.getPriority( );

Example for using Thread Priority:


class A extends Thread
{
public void run ( )
System, out.println ("A started");
for(int i=1;i<=5;i++)
{
System.out.println ("Thread A: i=" + i);
}
System, out.println("Exit from A" ) ;

mnnappaji@gmail.com
73
}
}
class B extends Thread
{
public void run( )
{
System.out.println("B started");
for(int j=1;j<=5;j++)
{
System.out.println("Thread B: j=" + j);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run( )
{
System.out.println("C started");
for(int k=1;k<=5;k++)
{
System.out.println("Thread C: k=" + k) ;
}
System.out.println("Exit from C");
}
}
Class ThreadPriority
{
public static void main (String args[ ])
{
A tA = new A( );
B tB = new B( );
C tC = new C ( );
ThreadC.setPriority(Thread.MAX_PRIORITY);
ThreadB.setPriority(ThreadA.getPriority ( ) +1) ;
ThreadA.setPriori.ty (Thread.MIN_PRIORITY) ;

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


tA.start ( ) ;

System.out.println("Start thread B"';


tB. start ( );

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


tC.start ( ) ;

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


}

mnnappaji@gmail.com
74
Synchronization: One thread may try to read a record from a file while another is still writing to the
same file. Depending on the situation, we may get strange results. Java enables us to overcome this
problem using a technique known as synchronization.

The keyword synchronized helps to solve such problems by keeping a watch on such locations.
For example, the method that will read information from a file and the method that will update the same
file may be declared as synchronized. Example:

Synchronized void update ( )


{
. . . . . . .
}

When two or more threads are waiting to gain control of a resource. Due to some reasons, the
condition on which the waiting threads rely on to gain control does not happen. This is known as.
deadlock.

mnnappaji@gmail.com
75
An error may produce an incorrect output or may terminate the execution of the program
abruptly or even may cause the system to crash. Errors may be classified into two categories:
Compile-time errors.
Run-time errors.
Compile-time errors: All syntax errors will be detected and therefore these errors are known as
compile-time errors. Whenever the compiler displays an error, it will not create the .class file. It is
therefore necessary that we fix all the errors before we can successfully compile and run the program.
Java compiler does a nice job of telling us where the errors are in the program. Most of the compile-time
errors are due to typing mistakes.
Missing semicolons.
Misspelling of identifiers and methods.
Missing brackets in classes and keywords.
Use of = in the place of = = operator.
Run-Time Errors: A program may compile successful 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 of the run-time errors are.
Dividing an integer by zero
Accessing an element that is out of the bounds of an array.
Try to store a value into an array of an incompatible class or type.

Exceptions: An exception is an event that occurs during the execution of a program that disrupts the
normal flow of instructions. When an error occurs within a method, for object called an exception object,
Creating an exception object and handing it to the runtime system is called throwing an exception.
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 execution 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 is known as exception handling. Error
handling code that performs the following tasks:
1. Find the problem (Hit the exception)
2. Inform that an error has occurred (Throw the exception)
3. Receive the error information (Catch the exception)
4. Take corrective actions (Handle the exception)
The error handling code basically consists of two segments,
To detect errors and to throw exceptions
To catch exceptions and to rake appropriate-actions

Syntax of Exception Handling Code: The basic concepts of exception handling are throwing an
exception and catching it.
try
{
Statements; // generate an exception
catch (Exception-Type e)
{
Statement; // process the exception
}
mnnappaji@gmail.com
76
Java uses a keyword try to preface a block of code that is likely to cause an error condition and
throw an exception. A catch block defined by the keyword catch catches the exception thrown by these
try block and handles it appropriately. The catch block is added immediately after the try block.

class Error1
{
public static void main{String args[ ])
{
int a=10;
int b =5;
int c=5;
int x,y;
try
{
X=a / (b-c);
}
catch (ArithmeticException e)
{
System.out.println("Division by Zero");
}
y= a/(b+c);
System.out.println("T=" + y) ;
}

Output: Division by zeto


y=1

Multiple Catch Statements: When an exception in a try block is generated, the Java treats the multiple
catch statements like cases in a switch statement. The first, statement whose parameter matches with the
exception object will be executed and the remaining statements will skipped.
try catch (Exception-Type-2 e)
{ {
Statement; Statement;
} }
catch (Exception-Type-1- e) . . . .
{ catch (Exception-Type-n e)
Statement; {
} Statement;
}
.................... .........
Note: Java does not require any processing of the exception at all. We can simply have a catch
statement with an empty block to avoid, program abortion.
Catch (Exception e);
The catch statement simply ends with a semicolon, which does nothing.
Class Error2
{
public static void main (String args [ ])
{
int a[ ]=[5,10];
mnnappaji@gmail.com
77
int b =5;
try
{
int x=a[2] / b-a[1];
}
catch (ArithmeticException e)
{
System.out.printin("Division by Zero");
catch (ArraylndexOutOfBoundsException e)
{
System.out.printin("Array index error");
}
catch (ArrayStoreException e)
{
System, out .println ("Wrong data type");
}
int y= a[1] / a[0];
System.out.println("Y=" + y) ;

Output:
Array index error
y=2

Using Finally Statement: Java supports another statement known as finally statement that can be used
to handle an exception that is not caught by any of the previous catch statements. Finally block can be
used to handle any exception generated within a try block. It may be added immediately after the try
block or after the last catch block as follows.

try try
{ {
............ ............
............ ............
} }
finally catch ( . . . )
{ {
............ ............
............ ............
} }
catch ( . . . )
{
............
............
}
.
.
.
.
finally
{
mnnappaji@gmail.com
78
............
............
}

When a finally block is defined, this is guaranteed to executed regardless of whether or not in exception is
thrown. As a result, we can use it to perform certain house-keeping operations as closing files and
releasing system resources.

Throwing our own exceptions: We can throw our own exceptions using the keyword throw as follows:
throw new throwable_subclass;
Example: throw new ArithmeticException( ) ;

import Java.lang.Exception;
class MyException extends Exception
{
MyException(String message)
{
Super(message);
}
}
Class TestMyException
{
Public static void main(String args[ ])
{
int x=5,y=100;
try
{
Float z=( float) x/(float) y;
If(z<0.01)
(
Throw new MyException ("Number is too small");
}
Catch(MyException e)
{
System.out.println("Caught my exception");
System, out. println (e. getMessage ( ));
}
finally
{
System.out.println("I am always here");
}
}

Output:
Caught my exception.
Number is too small.
I am always here.

mnnappaji@gmail.com
79
Applet: An applet is a Container, which can hold some graphical user elements those are said to be
components of awt (Abstract window tool kit package) and Applets are small java programs. It is
developed for internet applications.

Java applets are used to developed windows applications.


Java program can be executed in two ways i.e. 1) by using JVM 2) by using Browser.
Java applets are special type of the java programs which are executed by a web browser.
If a java application contains main method then it will execute by jvm. It means an applets does
not contain main method which are executes by browser.
Java applets are secured applications because they will never effect with any virus and applets are
transferable over the network.
The biggest package in java is java.awt. and the smallest package in java is java.applet.

chain of class inherited by applet class

Object This class belongs to java.lang package

Compone This class belongs to java.awt package


t

Container This class belongs to java.awt package

Panel Window

Applet This class belongs to java.applet package

Object is a base class of all classes in java. In above structure, the base class of applet is panel and panel is
a class of awt package.
Creating an applet:
If we want to create an applet, we need to create a public class and It must be extended from the base
class from Applet. Applet is a class given in a package java.applet. So we have to write the applet must be
imports applet package.

Syntax of creating an applet: Example:

public class classname extends Applet class Public class myapplet extends Applet
{
{ ……………..
……………..
} }
mnnappaji@gmail.com
80
Our applet code must be containing two classes i.e. Applet and Graphics. Applet is a class given by
java.applet and it provides all life cycle methods i.e. init(), start(), and paint(), stop(), destroy(). Graphics
is a class given by java.awt package. The paint method of the Applet class is using displays the result of
the applet code on the screen. The output may be text, graphics so the paint() requires a Graphics object
defined as follows.
Public void paint(Graphics g)
So the applet code requires imports the java.awt package in your applet program.

Example of applet program:


import java.applet.*;
import java.awt.*;
public class myapplet extend Applet
{
-------------------
-------------------
Public void paint(Graphics g)
{
--------------
--------------
}
--------------
-------------
}
Running an applet: An applet is executed on a web browser but applet is a java class it cannot be
executed directly on browser. So we need to create HTML file and the configuration of the applet class is
stored in html file and then that html file is executed on browser.
Once the html file is created for an applet we can execute this html for two ways i.e. Either by using
browser (or) by using appletviewer. The html file contains the following tag to store the configuration
of an applet.
<applet code=”classname”
Codebase=”path”
width= value height=value >
</applet>
We can execute applet by using applet viewer, write the html file in your program with in the comment
lines like as
/*<applet code=”classname”
Codebase=”path”
width= value height=value >
</applet>*/
Example Output:
import java.applet.*;
public class myapplet extends Applet
{
}
/*<applet code=”myapplet”
Codebase=”/”
width= 200 height=200 >
</applet>*/
Compile: javac myapplet.java Run: appletviewer myapplet.java
mnnappaji@gmail.com
81
//draw the string on applet
import java.applet.*; Output:
import java.awt.*;
public class myapplet extends Applet
{
Public void paint(Graphics g)
{
g.drawString(“welcome applets”,50,100);
}
}
/*<applet code=”myapplet”
Codebase=”/”
width= 200 height=200 >
</applet>*/

Applet life cycle:


Applet life cycle has contains five methods i.e.
1. init()
2. start()
3. paint()
4. stop()
5. destroy()

in below figure 5 states are there i.e. born or initialization state ,running state, display state idle state,
dead state.

Initialization state: when applet is loaded on the browser or appletviewer then init() mehod is exeuted.
This method is used to provide initialization of any variables are objects available in the applet classs.
The init() method executes only once in the applet life cycle.
Declaration of init method in applet
Public void init()
{
------------
------------
}
Running state: after init method execution then start method will executed (running state will be
executed) init() will internally executes start(), which represents applet execution is started.

Public void start()


{
---------
---------
}
Display state: the display state produce the graphical information on the screen using paint(). Start will
internally calls paint().

public void paint(Graphics g)


{
--------
mnnappaji@gmail.com
82
--------
}

Idle state: if we explicitly stopped the execution of an applet then it internally executes stop().

Public void stop()


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

Dead state: when an applet is unloaded from memory. it refers to dead state and it automatically
executes destroy() method

public void destroy()


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

mnnappaji@gmail.com
83
//Example of applet program to display the oval and rectangle, line

import java.awt.*;
import java.applet.*; Output:
public class shape extends Applet
{
Public void paint(Graphics g)
{
g.drawOval(20,50,80,50);
g.setColor(Color.red);
g.fillOval(130,50,70,80);
g..drawRect(30,150,100,55);
g.drawLine(40,70);

}
}
/*<applet code = "shape" width=300 height=300>
</applet>*/
Note: here drawOval,setColor,fillOval,drawRect,drawLine methods of Graphics class and the awt package
contains Graphics class so it must be import awt package.
Output:

// Write a program of calculation of sum, subtract, division, multiplication of given values.(Calculator


program).
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class calculator extends Applet implements ActionListener
{
Label l1,l2,l3; Output:
Button b1,b2,b3,b4;
TextField t1,t2,t3;
public void init()
{
l1=new Label("enter first number ");
l2=new Label("enter second number ");
l3=new Label("result");
t1=new TextField(10);
t2=new TextField(10);
t3=new TextField(10);
b1=new Button("+");
b2=new Button("-");
b3=new Button("*");
b4=new Button("/");
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
mnnappaji@gmail.com
84
add(t3);
add(b1);
add(b2);
add(b3);
add(b4);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
}//init
public void actionPerformed(ActionEvent ae)
{
int x=Integer.parseInt(t1.getText());
int y=Integer.parseInt(t2.getText());
int z;
if(ae.getSource()==b1)
z=x+y;
else if(ae.getSource()==b2)
z=x-y;
else if(ae.getSource()==b3)
z=x*y;
else
z=x/y;
t3.setText(" "+z);
}
}//class
/*<applet code = "calculator" width=300 height=300>
</applet>*/

Applet for Drawing a Human FACE

import java.awt.*;
import java.applet.*;
Public class Face extends Applet
{
Public void paint (Graphics g)
{
g.drawOval (40, 40, 120, 150); //Head
g.drawOval (57, 75, 30, 20); //Left Eye
g.drawOval (110, 75, 30,20); //Right Eye
g.fillOval(68,81,10,10); //Pupil (left)
g.fillOval(121,81,10,10); //Pupil (Right)
g.drawOval(85, 100, 30, 30); // Nose
g.fillArc(60,125,80,40,180,180); // Mouth
g.drawOval(25,92,15,30); // Left Ear
g.drawOval(160,92,15,30); // Right Ear
}
}

mnnappaji@gmail.com
85
Applets: Applets are programs that can be launched from within HTML documents. They are small
programs used to add multimedia effects such as animation to Webpages. HTML stands for Hyper Text
Markup language and is markup (tagging language) used for creating Web pages. HTML has tags
specifically designed for applets. Web browsers (Internet Explorer, Netscape Navigator etc.) run applets
when the browsers display the HTML document. Applets thus normally execute at the client’s machine,
i.e. different from the machine in which it was created.

Applications: Java Applications are programs that can run stand-alone on a variety of computers and can
be anything from simple programs to large software. They can run from the command line or have a
Graphical user Interface (GUI). The applications may connect to networks, databases or other
applications depending on the set of services it is using.

S.No. Applets Applications


1 Applets can be embedded in HTML pages and Applications have no special support in HTML
downloaded over the Internet or Intranet. for embedding or downloading.
2 Applets can only be executed inside a Java- Applications can be executed from the
compatible container, such as a modern Web command line using Java.exe.
Browser.
3 Applets execute under strict security Applications have no security restrictions.
limitations and are not permitted to access
files or systems services on the user’s
computer.
4 Applets are programs written specially for Applications are usually system level programs,
distribution over network and contain i.e. those programs that run in the background
information to be delivered to the world and and do not involve user interaction.
that involves user interaction.
5 For example, order entry form, registration For Example, server administration, security
form, mailing etc. manager etc.

Difference between Java & java Script

JAVA JavaScript
Java is developed by Sun Microsystems. JavaScript is developed by NetScape.
Java is a compiled language. JavaScript is an interpreted language
Java has a complex syntax and requires strict JavaScript is comparatively simple to program.
programming practices.
Java is platform independent. Web browser provides the platform for
JavaScript and therefore the browser for which
you are writing your JavaScript program is
important.
Java is a strongly typed language which means JavaScript is untyped which means that a
the data type of values you are dealing with are JavaScript can hold a value of any data type, does
very specific in type. not have to be set when declaring the variable.

mnnappaji@gmail.com
86
Glossary
GUI: A graphical user interface. It is an interface to the Windows operating system. It includes user
friendly controls, like Buttons, textfields for entering text, message boxes, etc.
AWT: The Abstract Windowing Toolkit. It is a package in Java API and consists of Graphics, Font, color,
Image, etc. classes. You have to call this package by using the import keyword (import java.awt.*). if You
are using methods and interfaces from this package.
LABEL: It denotes uneditable text.
BUTTON: It is a standard control found in Windows.
CHECKBOX: It consists of a set of items. Users can select one or more items at a time.
CHECKBOX GROUP: It denotes a radio (small, black circle shape) button. Users can select only one item
at a time.
TEXTFIELD: Users can enter information in the boxes. You can enter in one single line.
TEXTAREA: By using this control, users can enter multiple lines of text.
CHOICE: This component is the same as combo box. When a user clicks on the dropdown arrow, We will
get a list of items, only one item is selectable at a time.
LIST: This is a variation of the above component. Users can select multiple items at a time.
What is HTML?
HTML is a language for describing web pages.
 HTML stands for Hyper Text Markup Language
 HTML is not a programming language, it is a markup language
 A markup language is a set of markup tags
 HTML uses markup tags to describe web pages

HTML Tags
HTML markup tags are usually called HTML tags
 HTML tags are keywords surrounded by angle brackets like <html>
 HTML tags normally come in pairs like <b> and </b>
 The first tag in a pair is the start tag, the second tag is the end tag
 Start and end tags are also called opening tags and closing tags

HTML Documents = Web Pages


 HTML documents describe web pages
 HTML documents contain HTML tags and plain text
 HTML documents are also called web pages

mnnappaji@gmail.com
87
Program 1:

class VariableExample
{
public static void main(String args[ ] )
{
long a = 1 L;
long b = 10894356L
char c = ‘F’;
a = b * a ++ * (b+3);
System.out.println(“Values of a, b, c are : “);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}

Program 2: Print the Largest of two Numbers

class LargeNum
{
public static void main(String args[ ] )
{
int a=20, b = 10;
if (a>b)
System.out.println(a);
else
System.out.println(b);
}
}
Program 3: Print the Largest of three Numbers

class LargeNum2
{
public static void main(String args[ ] )
{
int a=20, b = 10, c = 30;
if (a>b)
{
if (a>c)
System.out.println(a);
else
if (c>b)
mnnappaji@gmail.com
88
System.out.println(c);
}
else
System.out.println(b);
}
}

Program 4: To display the name of the day using Switch Case

Class Week
{
Public static void main(String args[ ] )
{
int day = 6;
switch (day)
{
case 1:
System.out.println(“Sunday “);
break;
case 2:
System.out.println(“Monday “);
break;
case 3:
System.out.println(“Tuesday “);
break;
case 4:
System.out.println(“Wednesday “);
break;
case 5:
System.out.println(“Thursday “);
break;
case 6:
System.out.println(“Friday “);
break;
case 7:
System.out.println(“Saturday “);
break;
default:
System.out.println(“Not a correct Number\n “);
break;
}
}
}

Program 4: To display the name of the day using Switch Case without break statement

Class Week
{
Public static void main(String args[ ] )
mnnappaji@gmail.com
89
{
int day = 6;
switch (day)
{
case 1:
System.out.println(“Sunday “);
case 2:
System.out.println(“Monday “);
case 3:
System.out.println(“Tuesday “);
case 4:
System.out.println(“Wednesday “);
case 5:
System.out.println(“Thursday “);
case 6:
System.out.println(“Friday “);
case 7:
System.out.println(“Saturday “);
default:
System.out.println(“Not a correct Number\n “);
}
}
}

Program 5:
class While
{
public static void main(String args[ ])
{
int i=0;
while (i<10)
{
System.out.println(“APPAJI”);
i++;
}
}
}

Program 6: To find the factorial of a given Number

class Factorial

public static void main(String args[ ])


{
int i=5; fact;
fact =1;
mnnappaji@gmail.com
90
do
{
Fact = fact * n;
N = n + 1;
}
While (n>1);
System.out.println(fact);
}
}

Program 7: To print Fibonacci Series


class Fibonacci
{
public static void main(String args[ ])
{
int a=0, e = 1, b = 1, c = 1, n = 10;
do
{
System.out.println(b);
b=e+a;
a=e;
e=b;
c=c+1;
}
while (n>=c);
}
}

Program 8: To print the given Series


class Series
{
public static void main(String args[ ])
{
int i;
for( i = 120; i>=0; i -= 2)
{
System.out.println(i);
}
}
}

Program 9:- WAP TO FIND GREATEST OF THREE NUMBERS.


class hiteshgreatest
{
public static void main(String arg[])
{
mnnappaji@gmail.com
91
int a,b,c;
a=Integer.parseInt(arg[0]);
b=Integer.parseInt(arg[1]);
c=Integer.parseInt(arg[2]);
if((a>b) && (a>c))
System.out.println("greatest :"+a);
else if((b>a) && (b>c))
System.out.println("greatest :"+b);
else
System.out.println("greatest :"+c);
}
}
Output:
C:\jdk1.3\bin>java hiteshgreatest9 1 6
greatest :9

PROGRAM 10:- WAP TO FIND FACTORIAL USING COMMAND LINE.


class hitfactorial{
public static void main(String arg[])
{
int fact=1,num;
num=Integer.parseInt(arg[0]);
for(int i=num;i>=1;i--)
{
fact=fact*i;
}
System.out.println("factorial="+fact);
}
}
OUTPUT:
C:\jdk1.3\bin>java hitfactorial7
factorial=5040

PROGRAM 11 :- WAP TO READ NUMBERS IN AN ARRAY AND FIND SUM AND AVERAGE.
public class sumavg{
public static void main(String a[])
{
int num[]={4,8,2,1,5};
int l=num.length;
int x,s=0;
float avg;
System.out.println("numbers inside num");
for(x=0;x<l;x++)
{
System.out.println(" "+num[x]);
}
System.out.println("Sum= ");
for(x=0;x<l;x++)
{
mnnappaji@gmail.com
92
s+=num[x];
}
System.out.println(" "+s);
avg=s/5;
System.out.println("Average="+avg);
}
}
OUTPUT:
C:\jdk1.3\bin>java sumavg
numbers inside num
4
8
2
1
5
sum=20
average=4

PROGRAM 12 :- WAP TO MAINTAIN STUDENT RECORD USING DATA MEMBER AND MEMBER
FUNCTION.
class csstudent{
int r.no,marks1,marks2,marks3;
String name;
void getdata(int r.no, int marks1, int marks2, int marks3, String name)
{
this.r.no=r.no;
this.marks1=marks1;
this.marks2=marks2;
this.marks3=marks3;
this.name=name;
}
int setdata()
{
return((marks1+marks2+marks3)/3);
}
void display()
{
System.out.println("CS Student record");
System.out.println("Roll no=:"+r.no);
System.out.println("subject1="+marks1);
System.out.println("subject2=“+marks2);
System.out.println("subject3="+marks3);
System.out.println("Average="+setdata());
System.out.println("Name "+name);
}}
class cs{
public static void main(String a[])
{
mnnappaji@gmail.com
93
csstudent stud=new csstudent();
stud.getdata(536,33,98,88,"ram");
stud.display();
}
}
}
OUTPUT:

C:\jdk1.3\bin>java cs
CS Student record
Roll no=536
Subect1=33
Subect2=98
Subect3=88
Average=73
Name ram
PROGRAM 13 :- WAP TO INCREMENT THE EMPLOYEE SALARY ON THE BASIS OF DESIGNATION.
import java.lang.*;
class employee
{
public static void main(String arg[])
{
int salary=12000;
if(arg[0].compareToIgnoreCase("ceo")==0)
{
salary += Integer.parseInt(arg[1]);

}
else if(arg[0].compareToIgnoreCase("manager")==0)
{
salary += Integer.parseInt(arg[1]);

}
else if(arg[0].compareToIgnoreCase("employee")==0)
{
salary += Integer.parseInt(arg[1]);

}
System.out.print(salary);
}
}

PROGRAM 14 :- WAP TO CREATE A CLASS BANK TO INPUT THE REQUIRED ATTRIBUTES.


class bankrecord
{
String name;
char type;
static double bal;
bankrecord(String name,char type,double bal)
mnnappaji@gmail.com
94
{
this.name=name;
this.type=type;
this.bal=bal;
}
void deposit(double d)
{
bal=bal+d;
System.out.println("Balance after deposit:"+bal);
}
void withdraw(double amt)
{
if(bal>500)
{
bal=bal-amt;
System.out.println("Balance after withdrawal:"+bal);
}
else
System.out.println("Sorry, You cannot withdraw");
}
void display()
{
System.out.println("Name:"+name);
System.out.println("Type of account:"+type);
System.out.println("Net Balance:"+bal);
}
}
class record
{
public static void main(String a[])
{
bankrecord br=new bank("raghav",'savings',4400.0);
br.display();
br.deposit(1000.0);
br.withdraw(1900.0);
System.out.println("\n\nCustomer Information");
br.display();
}
}
OUTPUT:
C:\jdk1.3\bin>java record
Name:raghav
Type of account:savings
Net Balance:4400.0
Balance after deposit:5500.0
Balance after withdrawal:3500.0
Customer information
Name:raghav
Type of account:savings
mnnappaji@gmail.com
95
Net Balance:3500.0

PROGRAM 15 :- WAP TO CREATE THREE CLASSES STUDENT, EXAM AND RESULT. CALCULATE THE
MARKS AND AVEREAGE.

class csstudent{
int r.no,marks1,marks2,marks3;
String name;
void getdata(int r.no, int marks1, int marks2, int marks3, String name)
{
this.r.no=r.no;
this.marks1=marks1;
this.marks2=marks2;
this.marks3=marks3;
this.name=name;
}
int setdata()
{
return((marks1+marks2+marks3)/3);
}
void display()
{
System.out.println("CS Student record");
System.out.println("Roll no=:"+r.no);
System.out.println("subject1="+marks1);
System.out.println("subject2=“+marks2);
System.out.println("subject3="+marks3);
System.out.println("Average="+setdata());
System.out.println("Name "+name);
}}
class cs{
public static void main(String a[])
{
csstudent stud=new csstudent();
stud.getdata(536,33,98,88,"ram");
stud.display();
}
}
}

OUTPUT:
C:\jdk1.3\bin>java cs
CS Student record
Roll no=536
Subect1=33
Subect2=98
Subect3=88
Average=73
Name ram
mnnappaji@gmail.com
96
PROGRAM 16 :- WAP TO CALCULATE AREA OF DIFFERENT GEOMETRICAL FIGURES USING
FUNCTION OVERLOADING.
class differentareas{
double area(int length,int breadth){
System.out.println("\nLength of rectangle:"+length);
System.out.println("Breadth of rectangle:"+breadth);
return length*breadth;
}
double area(double radius){
System.out.println("\nRadius of circle:"+radius);
return 3.14*radius*radius;
}
double area(int side){
System.out.println("\nSide of square:"+side);
return side*side;
}
}
class main{
public static void main(String a[])
{
double r,c,sq;
differentareas s=new differentareas();
sq=s.area(5);
System.out.println("Area of square:"+sq);
c=s.area(2.2);
System.out.println("Area of circle:"+c);
r=s.area(10,13);
System.out.println("Area of rectangle:"+r);

}
}
OUTPUT:
C:\jdk1.3\bin>java main
Side of square:5
Area of square:25

Radius of circle:2.2
Area of circle:15.197

Length of rectangle:10
Breadth of rectangle:13
Area of rectangle:130

PROGRAM 17 :- WAP TO CREATE A CLASS EMPLOYEE WITH THREE DIFFERENT DESIGNATION.


class employee{
int id;
String name;
String desg;
mnnappaji@gmail.com
97
int sal;
void getdata(int id,String name,String desg,int sal){
this.name=name;
this.id=id;
this.desg=desg;
this.sal=sal;
}
void display(){
System.out.println("ID No.: "+id);
System.out.println("Name: "+name);
System.out.println("Designation: "+desg);
System.out.println("Salary: "+sal);
}
}
class emp{
public static void main(String a[]){
employee c = new employee();
c.getdata(1,"hitesh","ceo", 80000);
c.display();
employee m = new employee();
m.getdata(11,"atul","manager", 40000);
m.display();
employee w = new employee();
w.getdata(98,"rakesh","worker", 20000);
w.display();
}
}

OUTPUT:
C:\jdk1.3\bin>java emp
ID No.: 1
Name: Appaji
Designation: ceo
Salary: 80000
ID No.: 11
Name: Rajesh
Designation: manager
Salary: 40000
ID No.: 98
Name: Naveen
Designation: worker
Salary: 20000

PROGRAM 18 :- WAP TO HANDLE ARITHMETIC EXCEPTION AND ARRAY INDEX OUT OF BOUNDS
EXCEPTION.

class ArrayIO
{
public static void main(String arg[])
mnnappaji@gmail.com
98
{
try
{
int a= arg.length;
System.out.print(a);
int b=42/a;
int c[]={1};
c[42]=99;
}
catch(ArithmeticException e)
{
System.out.print("Divide by zero" + e);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.print("Array Index Higher" +e);
System.out.print("After try catch");
}
}
}
Program 19:

class Example2 {
public static void main(String args[]) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
}
}
When you run this program, you will see the following output:
This is num: 100
The value of num * 2 is 200

Program 20:
// Demonstrate the basic arithmetic operators.
class BasicMath
{
public static void main(String args[ ])
{
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
mnnappaji@gmail.com
99
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
// arithmetic using doubles
System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}
When you run this program, you will see the following output:
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
Floating Point Arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5

Program 21:
// Demonstrate the % operator.
class Modulus
{
public static void main(String args[ ])
{
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
When you run this program, you will get the following output:
x mod 10 = 2
y mod 10 = 2.25

mnnappaji@gmail.com
100
Program 22:
// Demonstrate several assignment operators.
class OpEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
The output of this program is shown here:
a=6
b=8
c=3

Program 23:
// Demonstrate ++.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

The output of this program follows:


a=2
b=3
c=4
d=1

Program 24:
// Demonstrate the bitwise logical operators.
class BitLogic {
public static void main(String args[]) {
mnnappaji@gmail.com
101
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
System.out.println(" ~a = " + binary[g]);
}
}

a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100

Program 25:
// Left shifting a byte value.
class ByteShift {
public static void main(String args[]) {
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}
The output generated by this program is shown here:
Original value of a: 64
i and b: 256 0

Program 26:
// Left shifting as a quick way to multiply by 2.
class MultByTwo {
public static void main(String args[]) {
mnnappaji@gmail.com
102
int i;
int num = 0xFFFFFFE;
for(i=0; i<4; i++) {
num = num << 1;
System.out.println(num);
}
}
}
The program generates the following output:
536870908
1073741816
2147483632
-32

Program 27:
// Demonstrate the boolean logical operators.
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}

a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false

Program 28:
// Demonstrate ?.
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
mnnappaji@gmail.com
103
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
The output generated by the program is shown here:
Absolute value of 10 is 10
Absolute value of -10 is 10

Program 29:
// Using a do-while to process a menu selection
class Menu {
public static void main(String args[])
throws java.io.IOException {
char choice;
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while( choice < '1' || choice > '5');
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
mnnappaji@gmail.com
104
case '4':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}
Here is a sample run produced by this program:
Help on:
1. if
2. switch
3. while
4. do-while
5. for
Choose one:
4
The do-while:
do {
statement;
} while (condition);

Program 30:
public class cmdln
{
public static void main(String[] args)
{
System.out.print("Hi, ");
System.out.print(args[0]);
System.out.println(". How are you?");
}
}
Exe: java cmdln Appaji
Output: Hi, Appaji. How are you?

Program 31:
Write a java program to count frequency of words

import java.io.*;
import java.util.*;
class wordcount
mnnappaji@gmail.com
105
{
public static void main(String arg[]) throws IOException
{
int ctr=0;
String s,s1,s2;
DataInputStream in=new DataInputStream(System.in);
System.out.println("Enter a string with Words: ");
s=in.readLine();
StringTokenizer token1=new StringTokenizer(s);
StringTokenizer token2;
while(token1.hasMoreTokens())
{
token2=new StringTokenizer(s);
s1=token1.nextToken();
ctr=0;
while(token2.hasMoreTokens())
{
s2=token2.nextToken();
if(s1.equals(s2))
ctr++;
}
System.out.println("'"+s1+"' Frequency "+ctr+"Times");
}
}
}

Program 32:
Program to read a file and print char count,word count,line count.

import java.io.*;
class filestat
{
public static void main(String args[]) throws IOException
{
int pre=' ' , ch , ctr=0 , L=0 , w=1;
String fname;
DataInputStream in=new DataInputStream(System.in);
System.out.print("Enter a file name?");
fname=in.readLine();
//opening file
FileInputStream f=new FileInputStream(fname);
while((ch=f.read())!=-1)
{
if(ch!=' ' && ch!='\n') //char count
ctr++;
if(ch=='\n') //line count
L++;
if(ch==' ' && pre!= ' ') //word count
w++;
mnnappaji@gmail.com
106
pre=ch;
}
System.out.println("Char Count= "+ctr);
System.out.println("Word Count= "+(w+(L-1)));
System.out.println("Line Count= "+L);
}
}

Program 33:Write a program to Arrange the Given Strings in Alphabetical Order:

Madras
Delhi
Ahmedabad
Calcutta
Bombay

class StringOrdering
{
static String name[]={"Madras","Delhi","Ahmedabad","Calcutta","Bombay"};
public static void main(String args[])
{
int size=name.length;
String temp=null;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(name[j].compareTo(name[i])<0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for(int i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}

Program 34: Getting the result to the Screen


class Displaying
{
public static void main(String args[])
{
System.out.println(“Screen display”);
for (int i =1; i<=9; i++)
mnnappaji@gmail.com
107
{
for (int i =1; i<=9; i++)
{
System.out.print (“ “);
System.out.print(i);
}
System.out.print(“\n”);
}
System.out.println(“Screen Display Done”);
}
}

mnnappaji@gmail.com
108
What is Java?
Java is an object oriented programming language

Is Java invented for Internet?


No, it was developed for programming towards tiny devices

What is byte code?


It is machine understandable code and targeted for JVM (Java Virtual Machine). It is class file.

What is JVM?
Java Virtual Machine which accepts java byte code and produces result

What are java buzzwords?


Java buzzwords explain the important features of java. They are Simple, Secured, Portable, architecture
neutral, high performance, dynamic, robust, interpreted etc.

Is byte code is similar to .obj file in C?


Yes, both are machine understandable codes
No, .obj file directly understood by machine, byte code requires JVM

What is new feature in control statements comparing with C/C++?


Labeled break and labeled continue are new

What are new features in basic features comparing with C/C++?


Data types: All data types on all machines have fixed size;
Constants: final is used to declare constant
Boolean Type: boolean is new data type in Java which can store true/false
There are no structures/unions/pointers

Is String data type?


No, Strings are classes in Java (Arrays are classes)

What are length and length( ) in Java?


Both gives number of char/elements, length is variable defined in Array class, length( ) is method defined
in String class

What is class?
Class is blue print for objects; Class is collection of objects; Class gives the general structure for objects.

mnnappaji@gmail.com
109
What is object?
Object is an instance of class. Object is real world entity which has state, identity and behavior.

What is encapsulation?
Encapsulation is packing of data with their methods

What is abstraction?
Abstraction is the process of identification of essential features of objects
What is data hiding?
Implementation details of methods are hidden from the user

What is hierarchy?
Ordering of classes (or inheritance)

What is inheritance?
Extending an existing class is called inheritance. Extracting the features of super class

Why inheritance is important?


Reusability is achieved through inheritance

Which types of inheritances are available in Java?


Simple, Hierarchical and Multilevel

Can we achieve multiple inheritances in Java?


With the help of interfaces we can achieve

What is interface?
Interface is collection of final variables and abstract methods
(We need not give final and abstract keywords and By default they are public methods)

What is the difference between class and interface?


Class contains implemented methods, but interface contains non-implemented methods

What is polymorphism?
Multiple (poly) forms (morphs) Same instance can respond different manners is called polymorphism

Can we achieve run time polymorphism in Java?


Yes, also called as dynamic polymorphism. Possible by dynamic method dispatch

What is dynamic method dispatch?


When you assign object of sub class for the super class instance, similar methods of super class are
hidden

What is overloading?
Same method name can be used with different type and number of arguments (in same class)

What is overriding?
Same method name, similar arguments and same number of arguments can be
mnnappaji@gmail.com
110
defined in super class and sub class. Sub class methods override the super class methods.

What is the difference between overloading and overriding?


Overloading related to same class and overriding related sub-super class. Compile time polymorphism
achieved through overloading, run time polymorphism achieved through overriding

What is keyword?
Java reserved word which should is not used as variable/class-name (e.g.: break, for, if, while etc)

What is final keyword?


Used before variables for declaring constants
Used before methods for preventing from overriding
Used before class-name for preventing from inheritance

What is static keyword?


Used before variable for defining shared variables
Used before method for defining class-level methods, these methods
can be called without creating objects (e.g.: parseInt method of Integer class)

What is abstract keyword?


Used for creating abstract class, class which doesn't have any instance

What is this keyword?


To call current class variables and current class methods we can use this key word

What is this( )?
Used for calling another constructor of current class

What is super keyword?


To call super class variables and super class methods we can use super key word

What is super( )?
Used for calling of super class constructor and it should be first executable statement in sub class
constructor

What is package?
Package is collection of classes and interfaces

How to define package?


By using package keyword before the definition of class

mnnappaji@gmail.com
111
What is CLASSPATH?
It is an environment variable which is used for defining the location of class files

What is jar?
Jar stands for Java archive files, compressed set of class files and can be used in CLASSPATH
What is the meaning of import java.awt.*;?
Import all the classes and interfaces in the java.awt.package. This doesn't imports other packages
defined in java.awt. package.

Is it necessary to give import java.awt.event.*;, when already import java.awt.* given?


Yes, import java.awt.* doesn't imports event package defined in java.awt. package.

What is exception?
Abnormal termination of program is called exception

What is exception handler?


A method which controls abnormal termination of program
What are the keywords used for exception handling?
try, catch, throw, throws and finally

What is the difference between throw and throws keywords?


throw keyword is used for invoking an exception (For raising)
throws keyword lists exception names which can be ignored from the method execution

What is the difference between final and finally?


final is used for defining constants
finally is used for executing code after completion of exception handler

What is catch( ) block?


Exception handler that controls abnormal termination of program

Can we have multiple catch( ) blocks?


Yes, but first sub class exceptions should be handled

What happen is we not handle sub class exception first?


Generates compile time error saying that unreachable code is defined in the program

What is thread?
Thread is a part of process, also called as light weight process

What is multithreading?
Simultaneous execution of threads is called multithreading

What is a process?
Program under execution is called process
mnnappaji@gmail.com
112
How to create thread?
By creating instance of Thread class or implementing Runnable interface

Can you name any methods of Thread class?


currentThread( ), setName( ), getName( ), setPriority( ), getPriority( ), join( ), isAlive( )

What is join( ) method of Thread?


Combines two or more threads running process and wait till their execution is completed

What are the states in Thread Life Cycle?


Ready, running, block, wait, dead

What is an applet?
Applet is a java program which runs via java-enabled browser

Is graphics possible only in applets?


No, standalone program frames can also display graphics

What is the relation between java and Internet?


With the help of java applets, we can write programming for Internet

Which package is required to write GUI (Graphical User Interface) programs?


Java.awt

Which package is required to write Applets?


Java.applet

What is an event?
A kind of action

What is event handling?


A procedure which gives functionality for the events

How to implement event handling?


By using interfaces like ActionListener, MouseListener

What is the method available in ActionListener Interface?


public void action performed(AcitonEvent e)

How to pass parameters to Applets?


By using PARAM tag.

mnnappaji@gmail.com
113
INTRODUCTION TO DATA STRUCTURES

The organised collection of data is called a data structure. One such basic data structure called
arrays. Arrays are basic building block for more complex data structures. Data structures are classified
as:

i) Linear and Non-linear data structures: In linear data structure the data items are arranged in a
linear sequence like in an array. In a non-linear, the data items are not in sequence. An example of
non-linear data structure is a tree.

ii) Homogeneous and Non-Homogeneous data structures: An array is a homogeneous structure in


which all elements are of same type. In non-homogeneous structures the elements may or may
not be of the same type.

iii) Static or Dynamic data structures: Static structures are ones whose sizes and structures associated
memory location are fixed at compile time. Dynamic structures are ones, which expand or shrink
as required during the program execution.

LINKED LISTS:

Linked lists are data structures, which can dynamically change their size. Linked lists can be of
many types:
 Single linked list
 Double linked list
 Circular linked list

Single Linked List:

A single linked list is a list of objects belonging to the same data type. Each of its elements have
data and a pointer pointing to next element of the list. An element in a linked list is called a node. The first
element of a list is called head and the last element is called the tail of list. The last node i.e., tail in the list
will have a pointer containing NULL.

Following are some of the basic operations that may be performed on a list:
 Create a list
 Check for an empty list
 Search for an element in a list
 Delete an element from a list
 Add an element at a specified location of a list
 Retrieve an element from a list
 Update an element of a list
The following figure illustrates the structure of a single linked list:
Head Tail

Blue Red Yellow Orange White


Null
The linked list in the above figure consists of five nodes. Each node has two parts:
- data and
- a pointer pointing to next element of the list
mnnappaji@gmail.com
114
The primary advantage of Linked Lists can grow and shrink in size during their lifetime. A second
advantage of Linked Lists is that the items to be rearranged efficiently.

Insertion in a List:

Algorithm for inserting an element in a linked list

1. Check if List is empty, return if yes


2. Search for the element
3. Create a memory space for element to be inserted
4. Assign a data value
5. Assign its pointer of the element

Let us consider a list as given in above fig:

We want to insert PINK before YELLOW. We must create space for element with data PINK.
Pink Null

Now we need to assign the pointer of new element, which has a value NIL at present; i.e.,

Blue Red Yellow Orange White


Null
Pink Null

Now we need to delink YELLOW from RED and assign it to the new element created. Therefore, we
will have

Head Tail

Blue Red Yellow Orange White


Null

Pink Null

Deletion from a List:

Deletion of an element from a single linked List requires

1. List to be checked for empty list


2. Search for the element with key value same as the element to be deleted
3. Its pointer to next element be saved and later assigned to next element
4. Dispose the memory space held by the deleted element.

Double Linked List:


mnnappaji@gmail.com
115
In the single linked list traverse the list in one direction. In many applications it is required to
traverse a list in both directions. This 2-way traversal can be realized by maintaining two link fields in
each node instead of one. Such a structure is called a Doubly Linked List. Each element of a Doubly Linked
List structure has three fields:

- data value
- a link to its successor
- a link to its predecessor

The predecessor link is called the left link and the successor link is known as the right link. Thus
the traversal of the List can be in any direction.
Head Tail

NULL Data Next Prev Data Next Prev Data Null

Circular Linked List:

A circularly linked list is a list in which the link field of the last element of the list contains a
pointer to the first element of the list. The last element of the list no longer points to a NIL value.

Blue Red Yellow Orange White


Null

How to create a node:


struct node
{
int data;
node *link;
};
node *head;

head = new node;

head->data=10;

head->link=NULL;

mnnappaji@gmail.com
116
STACKS

A Stack is a linear data structure in which data is inserted and deleted at one end (same end). The
data is stored and retrieved in a Last In First Out (LIFO) order. The Stack is dynamic in nature as
changing its size due to the addition and deletion of data.

POP PUSH

The open end of the Stack is called the top of the Stack. When an item is added to a stack, the
operation is called PUSH, and when an item is removed from the stack the operation is called POP.

Stack Operations:

Basic operations on stack are as given below:

 Create a stack
 Check whether a stack is empty
 Check whether a stack is full
 Initialize a stack
 Push an element onto a stack (if not full)
 Pop an element from a stack (if not empty)
 Read a stack top
 Print the entire stack

Stack Applications:

 Passing values with function calls


 Validating arithmetic expressions
 Evaluating Prefix and postfix notations

QUEUES

A queue is a data structure in which elements are deleted at one end, labeled FRONT, and
elements are added at the other end, labeled REAR.

Rear

Front 10 20 30 40 50

mnnappaji@gmail.com
117
A queue is called a First-In-First-Out (FIFO) structure, as the first item added to the queue is the
first one to get deleted.

Queue Operations:

 Create a queue
 Check whether a queue is empty
 Check whether a queue is full
 Add item at the rear queue
 Remove item from front of queue
 Read the front of queue
 Print the entire queue

Applications:

 Time sharing systems


 Operating system schedulers for scheduling activities to be processed by the
microprocessor
 Simulation applications

Queues can be classified into different types:

1. De Queues
2. Priority Queue

De queue:

The term dequeue stands for a double-ended queue. In such a queue, elements can be added or
removed from both ends of the queue. There are two types of deques:
1. Input restricted dequeue
2. Output restricted dequeue

In an input-restricted deque, elements can be inserted only from the end of the queue. Elements
can be deleted from both the ends of the deque.

In an output-restricted deque, elements are inserted from both ends of the deque, but elements
are deleted only from one end of the deque.

mnnappaji@gmail.com
118
Priority Queue:

In a priority queue, each element has a priority assigned to it. Priority queues can be used in a time
sharing system. Each element in the queue happens in the order given below:

1. An element with a higher priority is processed first


2. If two elements share the same priority, then the element that came in first, is processed first.

GRAPHS

1. What is a Graph explained with example?

A graph 'G' consists of a set V of vertices also called nodes and a set E of edges also called arcs. V is
a finite and non empty set of vertices. E is a set of pairs of vertices; these pairs are called edges. Therefore

V(G), read as V of G, is set of vertices,


mnnappaji@gmail.com
119
and E(G), read as V of G, is set of edges.

Thus G=(V,E) to represent a Graph. Generally Graphs are of two types, Undirected Graphs and
Directed Graphs.

In an Undirected graph, pair of vertices representing any edge is unordered. Thus (v, w) and (w, v)
represent the same edge.

Example:
1

2
5

3
4

Fig: Undirected Graph

Here, V(G)={1,2,3,4,5)
and E(G)={(1,2),(2,3),(3,4),(4,5),(1,5),(1,3)(3,5)}

In Directed Graph, each edge is an ordered pair of vertices, i.e. each edge is represented by a
directed pair. If e=(v, w), then v is tail or initial vertex and w is head or final vertex. Subsequently (v, w)
and (w, v) represent two different edges.

Example:
1

2
5

3
4
Fig: Directed Graph
An arrow indicates the direction. Therefore,

V(G)={1,2,3,4,5}
and E(G)={(1,2),(2,3),(3,4),(5,4),(5,1),(1,3),(5,3)}

Applications of Graphs:

In computer science, graphs are used in many areas one of which is computer design.

Travelling Salesman Problem:


mnnappaji@gmail.com
120
A salesman has to visit several cities. He is required to visit each city exactly once. Graph theory
can be used to solve this transportation system.

Path: A path from vertex v to vertex w is a sequence of vertices, each adjacent to the next. Consider the
above Fig:1
1,2,3 is a path
1,3,5 is a path
2,3,5 is a path
Is 1,2,5 is a path ?

Cycle: A Cycle is a path in which first and last vertices are the same. That is path 1,3,4,5,1 is a cycle.

2. Explain the different Graph Representations?

Graphs can be represented in different ways. Two such representations are commonly used. These
are Adjacent Matrix and Adjacency List representations.

Adjacency Matrix:

The adjacency matrix A for a Graph G=(V, E) with n vertices, is an n x n matrix of bits, such that
Aij=1, iff there is an edge from vi to vj and
Aij=0, if there is no such edge.
The following example shows the adjacency matrix for the graphs:
1

2
5

3
4

Fig: Undirected Graph

mnnappaji@gmail.com
121
Vertice 1 2 3 4 5
s
1 0 1 1 0 0
2 1 0 1 0 1
3 1 1 0 1 1
4 0 0 1 0 1
5 1 0 1 1 0

Fig: Adjacency Matrix for Undirected Graph

The adjacency matrix for an undirected graph is symmetric. Also all the diagonal elements are
zero.

Example 2: 1 4 6

2 3 5 7
Fig: Directed Graph
Vertice 1 2 3 4 5 6 7
1 0 1 1 1 0 0 0
2 0 0 0 0 0 0 0
3 0 0 0 0 1 0 0
4 0 0 0 0 0 1 0
5 0 0 0 1 0 0 0
6 0 0 0 0 0 0 0
7 0 0 0 0 0 1 0

Fig: Adjacency Matrix for Directed Graph

The total number of 1's account for the number of edges in the directed graph.The adjacency
matrix is a simple way to represent a graph.

Adjacency List Representation:

In this representation, stores a graph as a linked structure. It is a linked list of its adjacent vertices.
Consider the graph:

V1
V4

V6
V3

V5
V2

mnnappaji@gmail.com
122
The adjacency list representation needs a list of all of its nodes, i.e.,

V1

V2

V3

Therefore we shall have:

V1 V2 V3
V1
V2
V2 V3 V3
V4
V5
V6 V1
V3 V4

V4

Note: That adjacent vertices may appear in the adjacency list in arbitrary order.

3. Explain the different Graph Traversal Methods:

A Graph traversal means visiting all the nodes of the graph. Graph traversal may be needed in
many of application areas and there may be many methods for visiting the vertices of the graph. Two
Graph traversal methods which are commonly used and efficient Graph traversal methods. These are

 Depth First Search or DFS


 Breadth First Search or BFS

Depth First Search (DFS):

The traversal may start from any arbitrary vertex. We start with say, vertex v. An adjacent vertex
is selected and a Depth First Search is initiated from it, i.e. let V1, V2...vk are adjacent vertices to vertex V.
We may select any vertex from the list. Say, we select V1. Now all the adjacent vertices to V1 are
identified and all of those are visited; next V2 is selected and all its adjacent vertices visited and so on.
This process continues till all the vertices are visited. Let us see through an example. Consider the
following graph:
V1

mnnappaji@gmail.com
V2 V3 123
Example Graph for DFS
Let us start with V1.

Its adjacent vertices are V2, V8 and V3. Let us pick on V2.

Its adjacent vertices are V1, V4, and V5. V1 is already visited. Let us pick on V4.

Its adjacent vertices are V2, V8. V2 is already visited. Let us visit V8. Its adjacent vertices are V4,
V5, V1, V6, and V7.

V1 and V4 are already visited. Let us traverse V5.

Its adjacent vertices are V2 and V8. Both are already visited. Therefore we back track.

We had V6 and V7 unvisited in the list of V8. We may visit any. We visit V6.

Its adjacent are V8 and V3. Obviously the choice is V3.

Its adjacent vertices are V1, V7. We visit V7.

All the adjacent vertices of V7 are already visited, we back track and find that we have visited all the
vertices.
V1

V2 V3

V4 V5

V6

Therefore the sequence of traversal is


V1, V2, V4, V8, V5, V6, V3, V7.
This is not a unique or the only sequence possible using this traversal method.
mnnappaji@gmail.com
124
We may implement the Depth First Search method by using a stack, pushing all unvisited vertices
adjacent to the one just visited and popping the stack to find the next vertex to visit.

ALGORITHM:
Step 1: Initialize all nodes to the ready state(status=1)
Step 2: Put the starting node A onto STACK and change its status to the waiting state (status=2)
Step 3: Repeat steps 4 and 5 until stack is empty
Step 4: Pop the top node N of STACK. Change its status to the processed state (Status=)
Step 5: Push onto STACK all the neighbor that are in the ready state (status=1) and change their
status to the waiting state (status=2)
Step 6: Exit.

Breadth First Search (BFS):

In DFS we pick on one of the adjacent vertices; visit all of its adjacent vertices and back track to
visit the unvisited adjacent vertices. In BFS, we first visit all the adjacent vertices of the start vertex and
then visit all the unvisited vertices adjacent to these and so on. Let us consider the same example. We
start say, with V1. Its adjacent vertices are V2, V8, and V3. We visit all one by one. We pick on one of
these, say V2. The unvisited adjacent vertices to V2 are V4, V5. We visit both. We go back to the remaining
visited vertices of V1 and pick on one of those, say v3. The unvisited adjacent vertices to V3 are V6, V7.
There are no more unvisited adjacent vertices of V8, V4, V5, V6 and V7.

V1 V1

V1
V2 V3 V2 V8 V3

V8
V4 V5

(a) (b) (c)

V1

V2 V3

V4 V5 V6 V7

V8

(d)
Thus, the sequence is so generated is V1, V2, V8, V3, V4, V5, V6, V7.
mnnappaji@gmail.com
125
Here we need a queue instead of a stack to implement it.
ALGORITHM:
Step1: Initialize all nodes to the ready state (status=1)
Step 2: Put the starting node A in QUEUE and change its status to the waiting state (status=2)
Step 3: Repeat steps 4 and 5 until Queue is empty
Step4: Remove the front node of Queue and change the status of N to the processed state
(status=3)
Step 5: Add the rear of queue that are in the ready state (status=1) and change their status to the
waiting state (status=2)
Step 6: Exit.

4. Kruskal's Algorithm And Prim's Algorithm:

Kruskal's Algorithm:
Step 1: Choose e1, an edge of G, such that weight of e1, w(e1) is as small as possible and e1 is not a
loop.
Step 2: If edges e1,e2,.....ei have been chooses then choose an edge ei+1, not already chosen, such
that
i) the graph G[{e1,e2,.....ei+1}] is acyclic and
ii) w(ei+1) is as small as possible
Step 3: If G has n vertices, stop after n-1 edges have been chooses. Otherwise repeat step 2.

Prims Algorithm:

Step 1: Choose any vertex v1 of G

Step 2: Choose an edge e1=V1,V2 of G such that V2 not equal to V1 and e1 has smallest weight
among the edges of G incident with V1.

Step 3: If edges e1,e2,.....ei have been chosen involving end points V1,V2,....Vi+1.

Step 4: Stop after n-1 edges have been chosed. Otherwise go to step 3.

mnnappaji@gmail.com
126
TREES

1. What is A Tree and What are the Related Terms In Tree

A Tree is a cyclic, connected graph. A Tree contains no loops or cycles. The concept of trees is
one of the most fundamental and useful concepts in computer science. Trees find their use in
applications such as compiler construction, database design, windows, operating system programs
etc.

B C D

E F G

H I J

K L M
Fig: A Tree

Some of the Tree related terms:

A Tree is a non-empty collection vertices and edges that satisfies certain requirements.

A vertex is a simple object (also referred to as a node) that can have a name and can carry other
associated information
An edge is a connection between two vertices.
The nodes of a tree have a parent-child relationship.
The root does not have a parent. Each one of the other nodes has a parent node associated to it.
A node may or may not have children. A node that has no children is called a leaf node.
A line from a parent to a child node is called a branch or edge.
If a tree has n nodes, then there would be n-1 branches.

Nodes with the same parent are called siblings. Consider the tree given in figure: K, L, and M are all
siblings. Nodes with no children are called leaves or terminal nodes (external nodes). Nodes with at
least one child are sometimes called non-terminal nodes (internal nodes). The length of a path is the
number of branches on the path. A path from A to K is A-D-G-J-K and the length of this pathis4. The
depth of any node is the length of the path from root. Thus the root is at depth 0. Depth of a node is
sometimes also referred to as level of a node. For the figure F is at height 1 and depth 2.

A set of trees is called a forest.


mnnappaji@gmail.com
127
Unit – 1: Java Fundamentals 24 hrs

Unit – 2: Oops Concepts in Java 24 hrs

Decision Making and Branching:


Decision Making with If statement
Simple If Statement
If else Statement
Nesting If Else Statement
the ElseIf Ladder
The switch Statement
The ?: operator.

Decision Making and Looping:


The while statement
The do statement
The for statement
Jumps in Loops.

Class, Objects and Methods:


Defining a Class
Fields Declaration
Methods Declaration
Creating Objects
Accessing class members
Constructors
Methods Overloading
Static Members
Nesting of Methods
Inheritance
Overriding Methods
Final Variables and Methods
Final Classes
Abstract Methods and Classes
Visibility Control.

(Chapters : 5,6,7,8 )

Unit – 3: Packages and Interfaces in Java 24 hrs

Arrays, Strings and Vectors:


One-dimensional Arrays
creating an Array
Two dimensional Arrays
Strings
Vectors
Wrapper Classes
Enumerated Types.

Interfaces:
Multiple Inheritance :
Defining Interfaces
Extending Interfaces
Implementing Interfaces
mnnappaji@gmail.com
128
Accessing Interface Variables.

Packages:
Java API Packages
Using system Packages
Naming Conventions
Creating Packages
Accessing a Package
Using a Package
Adding a Class to a Package
Hiding Classes
Static Import.

(CHAPTERS : 9,10,11 )

UNIT – 4: Multithreaded programming and Applets. 24 hrs

Multithreaded Programming:
Creating Threads
Extending the Thread Class
Stopping and Blocking a Thread
Life Cycle of a Thread
Using Thread Methods
Thread Exceptions
Thread Priority
Synchronization.

Managing Errors and Exceptions:


Types of Errors
– Exceptions
– Syntax of Exception Handling Code
– Multiple Catch Statements
– Using Finally Statement
– Throwing our own Exceptions
– Using Exceptions for debugging.

Applet Programming:
How Applets differ from Applications
Preparing to write Applets
Building Applet Code
Applet Life Cycle
Creating an executable Applet
Designing a WebPage
Applet Tag
Adding Applet to HTML file
Running the Applet
More about Applet Tag
Passing parameters to Applets
Aligning the display
More about HTML tags
Displaying Numerical Values
Getting Input from the user.

(Chapters : 12, 13, 14 )


mnnappaji@gmail.com
129
Unit – 5: Data Structures 24 hrs

Sorting:
Bubble Sort
Selection Sort
Insertion Sort
Quick Sort
Stacks and Queues:
Stacks
Queues
Circular Queue
Deques
Priority Queue
Parsing Arithmetic Expressions
Linked List
Simple Linked List
Finding and Deleting Specified Links
Double Ended Lists
Abstract Data types
Sorted Lists
Doubly Linked Lists
Advanced Sorting :
Quick Sort
Binary Trees :
Tree Terminology
Finding a Node
Inserting a Node
Traversing the Tree
Finding Maximum and Minimum values
Deleting a Node
Efficiency of Binary Trees
Trees Represented as Arrays
Graphs:
Introduction to Graphs
Searches
Minimum Spanning Tree
Topological Sorting with Directed Graphs
Connectivity in Directed Graphs.

(Chapters : 3,4,5,7 (Only Quick Sort), 8,13)


Prescribed books :
1. E.Balaguruswamy, Programming with Java, A primer, 3e, TATA McGraw-Hill Company (2008).(Chapters : 1 to 14 )
2. Robert Lafore, Data Structures & Algorithms in Java, Second Edition, Pearson Education(2008)
(Chapters: 3,4,5,7 (Only Quick Sort),8,13 )

mnnappaji@gmail.com
130

Vous aimerez peut-être aussi