Sie sind auf Seite 1von 219

Andhra Pradesh State Council of Higher Education.

B.Sc., Computer Science Under CBCS (Choice Base Credit System) with effect from Academic Year
Revised in April 2016.

II Year III Semester


Object Oriented Programming Using Java

UNIT – I
Chapter 1: Fundamentals of Object Oriented Programming.

Introduction of Java:-
 Java is Object Oriented Programming Language inventors primarily by “James Gosling”.
 Java is a General Purpose and Object Oriented Programming Language developed at “Sun Micro
Systems” of USA in 1991.
 In 1990‟s The Sun Micro Systems decided to developed special Software that could be used to
manipulate consumer electronics.
 1991‟s after exploring the possibility of using the most popular OOP‟s (Object Oriented
Programming) language as C++, the team announced a new language named as “Oak” (named
after the Oak trees outside Gosling‟s office).
 In 1993‟s the World Wide Web (WWW) appeared on the Internet and Transformed the Text based
into Graphical-Rich Environment.
 In 1994‟s the Team Developed a Web Browser Called “HotJava” to located and Run Applet Programs
on Internet.
 In 1995‟s “Oak” was renamed as “JAVA”.
 In 1996‟s Sun Micro Systems released “Java Development Kit 1.0 (JDK 1.0).
 In 1997‟s Sun Micro Systems released “Java Development Kit 1.1 (JDK 1.1).
 In 1998‟s Sun Micro Systems released Java with version 1.2 of the Software Development Kit 1.2.
 In 1999‟s Sun Micro Systems released Java2 Standard Edition (J2SE) and Java2 Enterprise Edition
(J2EE).
 2000‟s Java2 Standard Edition (J2SE) with Software Development Kit 1.3 (SDK 1.3) was released.
 2002‟s Java2 Standard Edition (J2SE) with Software Development Kit 1.4 (SDK 1.4) was released.
 2004‟s Java2 Standard Edition (J2SE) with Java Development Kit 5.0 (JDK 5.0) was released.
 2008‟s Java Development Kit 7.0 (JDK 7.0) “Dolphin” was released.

(Q) Object Oriented Paradigm (or) Object Oriented Methodology?

The major objective of Object Oriented approach is to element some of the flaws
encountered in the procedural approach. “Object Oriented Programming (OOP‟s) allows us to decompose a
problem development into a number of entities called as „Objects‟ and then build data and functions (knows
as methods in Java) around these entities”. The combination of Data and Methods make up an Object.

Method Method

Data

Method Method

Formula: Object = Data + its Methods

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

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 1 II.B.Sc., III Sem Java
Features of Object Oriented Paradigms (or) Object Oriented Methodology:-

1. Programs are divided into what are known as “Objects”.


2. Data is treated as main entity rather than procedures.
3. Methods that operate on the Data of an Object are tied together in the Data Structure.
4. Objects may communicate with each other through “Methods”.
5. New Data and Methods can be easily added whenever necessary.
6. It is Bottom – Up approach in program design.

(Q). What are the Basic Concepts of Object Oriented Programming (OOP‟S)?
(OR)
Characteristics of Object Oriented Programming (OOP‟S)?

The general concepts of Object Oriented Programming (OOP‟s) supporting the following concepts.

 Objects.
 Classes.
 Methods.
 Data Abstraction.
 Encapsulation.
 Inheritance.
 Polymorphism.
 Overloading.
 Message Passing.
 Dynamic Binding.

1. Objects: - Objects are the basic runtime entities in an Object Oriented System (OOS). An Object is
any of the following: External entities, Things, Events / Occurrences, Roles, Organizational Units,
Places, etc

Definition(1) of Objects: - “Any thing can be Objects”, in other words an Object be a Person, Place, or
Things which the computer must be understand or recognized.

Definition(2) of Objects: - An Object is a “Software bundle of Variable and related Methods”.

Definition(3) of Objects: - An Object is a set of Data its associated Methods. Object = Data + Methods.

Definition(4) of Objects: - An Object has defined as an identifiable entity with some Characteristics
and Behavior”.

Definition (5) of Objects: - Objects are run times entity. An object is distinguishable entity with some
Characteristics & Behavior. Every object has a defined as
 State.
 Behavior.
 Identity.

State: - The State of an Object encompasses all of the (Static) Properties of the Object plus the current
(Dynamic) values of each of these properties.

Behavior: - Behavior is how an Object acts and reacts, in terms of its state changes and message
passing.

Identity: - Identity is that property of an Object which Distinguishes or Unique it from all other Objects.

Examples of Objects in real world entity: - Vehicle, Furniture, etc.,

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 2 II.B.Sc., III Sem Java
Example (1): - We need some information about Cars (Car is Object). Car can have the following
features.

State: - Color, Size, Weight, Engine capacity etc.,


Behavior: - Start, Stop, Forward, Backward, Accelerate, etc.,
Identity: - Registration number, classic model shape, etc.,
Example (2): -
Person Object
Name Shaik Mohammad Fareed
Basic Pay 35000 Data (or) Characteristics
Salary ()
Methods (or) Behavior
Income Tax() (or) Functions.
Note: -
(1). Objects share two characteristics: they all have state and they all have behavior.
(2). Object maintains its state in variables and implements its behavior with methods.
(3). Everything that the software object knows (state) and can do (behavior) is expressed by the
variables and methods within that objects.

Variables

Methods

2. Classes: - The most important feature of OOP‟s is the Class. A class is the way to bind the “Data & its
associated Functions” or some time called also “Variables & Methods”. The keyword “class” specifies the
class name.

Definition (1) of Class: - “A Class is a collection of objects of similar type”.

Definition (2) of Class: - “A group of Objects that share common properties and relationships”.

Definition (3) of Class: - “A Class is a set of Objects that share a common structure and common
behavior.

Definition (4) of Class: - “The Objects with the same data structure (attributes) and behavior
(operations) are grouped into a class.

Definition (5) of Class: - A Class is a “blueprints” or “prototype” that defines the variables and methods
common to all objects of a certain kind. Software “blueprints” for objects are called classes.

In Java, a Class is a new data type that contains member variables and member functions
that operate on the variables. A class is defined with key word “Class”.

Example(1): - Motor bicycle object is an instance of the class of objects known as Motor bicycle. Motor
bicycles have some state (current gear, etc) and behavior (change gears, brake, etc) in common.
However each motor bicycle‟s state is independent of and can be different from other motor bicycles.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 3 II.B.Sc., III Sem Java
Change Speed and
Gears Gear

Methods Brake

Example(2): - For example in the case of Student Class, all objects have similar attributes like s_number,
s_name, marks in three subjects and similar operations like total(), average(). Related objects exhibiting
the same behavior are grouped and represented by a class in the following style.

class Student
{
int s_number;
string s_name;
int m1,m2,m3;
int total()
{
int tot;
tot=m1+m2+m3;
return(tot)
}
float average()
{
float avg;
avg=(float)(m1+m2+m3)/3;
return (avg);
}
}

3. Methods: - The term Method comes from the Object-Oriented language small task. The function that
operates on an object is known as Methods. Methods are used to change the objects attitude values or to
return the values of selected Object attributes. Methods represented a real-world action.

Example: -
int total()
{
int tot;
tot=m1+m2+m3;
return(tot)
}

4. Data Abstraction: - An Abstraction denotes the essential characteristics of objects that distinguish it
from all other kinds of objects and thus provide crisply define conceptual boundaries, relative to the
perspective of the viewers.

Some User application requires special kind of data type which not available in built-in data
type. The programmer burden to create own data type. The technique of creating a New data type
abstraction process are known as Abstract data type (ADT). The user created data type are called Abstract
data type or some times called as user defined data type.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 4 II.B.Sc., III Sem Java
5. Encapsulation: -The binding of “Data & Methods” together into a single component. Is known as
Encapsulation. The data is not accessible by outside function. Data hiding is the highly important
characteristics.

In Data Out
&
Methods

Definition (1) of Encapsulation: - The wrapping up of Data and Methods into a single unit is known as
Encapsulation. Data encapsulations are the most striking feature of a class. The Data is not accessible to
the outside and only those methods, which are wrapped in the class, can access it.

Definition (2) of Encapsulation: - Encapsulation is the mechanism that associated data with the code
that manipulates it. Direct access to the data from other software is not permitted.

Definition (3) of Encapsulation: - Encapsulation is the most often achieved through information hiding,
which is the process of hiding all the secrets of an object that do not contribute to it essential
characteristics.

Benefits of Encapsulation: - Encapsulating related variables and methods into a neat software bundle is
a simple yet powerful idea that provides two primary benefits to software developers.

1. Modularity: - The source code for an object can be written and maintained independently of the
source code for other objects.
2. Information Hiding: - An object has a „Public‟ interface that other objects can use to communicate
with it. But the object can maintain „Private‟ information and methods that can be within
environment.

Example: - In a company different departments work independently with their own data. One department
cannot access data of the other department directly, rather a request is made for the required data and the
data is handed over by the members of the requested department. We may say that department data and
department employees are encapsulated.

6. Inheritance: - Inheritance is a mechanism to derive a New Class from the Existing Class. Here Existing
Class is a Base class, New class is know as derived class.

Bird

Flying Bird Non-Flying Bird

Definition (1) of Inheritance: - Inheritance is the property that allows “the reuse of an Existing Class to
build a New Class”.

Definition (2) of Inheritance: - Inheritance is a mechanism to derive a New Class from the Existing
Class. Here Existing Class is a Base class, New class is know as derived class.

Definition (3) of Inheritance: - Inheritance is the process by which objects of one class acquire the
properties of objects of another class.

Definition (4) of Inheritance: - A Class inherits state and behavior from its superclass. Inheritance
provides a powerful and natural mechanism for organizing and structuring software programs.

The mechanism of deriving a New Class from an Existing Class can be called as
Inheritances. The Existing Class which is used for creating a New Class is Called Base Class / Parent Class /
Super Class and the newly created class is called Derived Class / Child Class / Sub Class.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 5 II.B.Sc., III Sem Java
NOTE: - Programmers can implements superclass called „abstract class‟ that define “generic” behaviors.
The abstract superclass defines and may partially implement the behavior but much of the class is
undefined and unimplemented. Other programmers fill in the details with specialized subclass.

7. Polymorphism: - Polymorphism comes from the Greek word “Poly” & “morphism”. „Poly‟ means Many
or Several and „Morphism‟ means Forms. In object-oriented programming Polymorphism refers to
identically name methods have different behavior depending on the type of the Object.

Definition (1) of Polymorphism: - Polymorphism means the ability to take more than one form.

Definition (2) of Polymorphism: - Polymorphism means different objects responding to the same
message in different manners.

Definition (3) of Polymorphism: - Polymorphism means is the process of representing different entities
with the same name however their behavior depends on the context.

NOTE: - Polymorphism plays an important role in allowing objects having different internal structure to
share the same external interface. General class of operations may be accessed in the same manner even
though specific actions associated with each operation may be differing.

Example: -
Shape
Draw()

Circle Rectangle Triangle


Draw() Draw() Draw()

In above figure illustrates that a single functions name Draw() can be used to handle different number
of arguments.

8. Overloading: - Overloading is a language feature that allows a function or operator to be given more
than one definition. The type of arguments with which the function or operator is called Overloading.

Definition of Overloading: - Overloading means same things for different purposes and we can use the
same function name to perform a variety of different task, we can design function with the same function
name but with different argument list”.

Techniques: - Overloading is broadly two types of technique.

1. Operator Overloading.
2. Function Overloading.

1. Operator Overloading: - “One operator can be used for different purposes, depending on the content”.
This concept is called as Operator Overloading.

Consider the following example, here addition operation is case of perform sum of two numbers. If
the operands of addition operator (+) is used for addition. The addition operator (+) will also give
concatenation of two strings.

Examples: - 10 + 2 = 12.  This is performing the Numerical values of addition.

Mohammad + Fareed = Mohammad Fareed  This is perform the String Concatenation.

Rules of Overloading Operators: - While representing the operators user has to follow certain rules.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 6 II.B.Sc., III Sem Java
1. Only Existing Operators can be overloaded.
2. We can‟t change the basic meaning of the operators.
3. They are some operators that cannot be overloaded. They are ?, :, . etc.,
4. Binary Arithmetic Operators such as +, -, *, /, % must be explicitly returns a values. They must be
not attempting changes their own definitions.

2. Function Overloading: - Overload means “Same thing for different purpose”. Function Overloading
means “We can use the same functions name to perform a verity of different tasks”. We can design
functions with the same function name but different arguments lists.

9. Message Passing (or) Message Communication: - An Object Oriented Programming (OOP‟s)


consists of a set of objects that communicate with each other. The process of programming in an Object
Oriented language. The involves the following basic steps.

Step (1): - Creating Classes that define objects and their behavior.
Step (2): - Creating Objects from class definitions.
Step (3): - Establishing communication among objects.

Objects communicate with one another by sending and receiving information much the same
way as people pass message to one another.

Object 1

Object 5 Object 2

Object 4 Object 3

Example: - Message passing involves specifications the name of the objects, the name of the method
(message) and the information to be sent. Here consider the statement.

Employee.Salary (Name)

Here Employee is the Object, Salary is the Message and Name is the parameter that consists information.

10. Dynamic Binding: - Binding refers to the “linking (or) tie-up a procedure call” to the code can
executed. Dynamic Binding means that the code associated with a given procedure until the run-time is
called as a Dynamic Binding. A function call associated with a Polymorphic and inheritance.

(Q) Benefits of Object-Oriented Programming language?

Object-Oriented Programming offers several benefits to both the program designer and the
user. OOP‟s gives greater programmer productivity better quality of software and lesser maintenance cost.

1. The Principle of data hiding helps the programmer to build secure programs. That cannot be access
code in other parts.
2. Through Inheritance, we can eliminate redundant code and extend the use of exiting classes.
3. We can build programs from standard working modules that communicate with one another. This
leads to saving of development time and give higher productivity.
4. It is possible to have creating multiple objects.
5. It can easy to partition the work in a project based objects.
6. Object-Oriented systems can be easily upgraded from small to large systems.
7. Message passing techniques for communicate between objects.
8. Software complexity can be easily managed.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 7 II.B.Sc., III Sem Java
(Q) Application of Object-Oriented Programming (OOP‟s)?

The following applications arrears we can use OOP‟s.

1. Real-Time system.
2. Simulation & Modeling.
3. Object Oriented Databases.
4. Artificial Intelligence (AI) and Expert System.
5. Neural Network and Parallel Programming.
6. Office Automation System.
7. Multimedia Application.
8. Graphical User Interface (GUI).
9. Computer Aided Design (CAD) System.

Chapter – 2
Overview of Java Language.
History of JAVA:-

 Java is Object Oriented Programming Language inventors primarily by “James Gosling”.


 Java is a General Purpose and Object Oriented Programming Language developed at “Sun Micro
Systems” of USA in 1991.
 In 1990‟s The Sun Micro Systems decided to developed special Software that could be used to
manipulate consumer electronics.
 Initially it was designed to created products for smart electronic devices, such as microwave ovens
and remote control appliances.
 If they use C / C++ then it was necessary to have a full complier to compile a C++ program. The
problem was that compilers are very expensive and time consuming to create for each type of
applications. For that reason „James Gosling‟ and his teammates decided to develop a Simple,
Portable and Platform Independent language to generate a code that would run on a variety of
CPU‟s under differing environments.
 At that time, the World Wide Web (WWW) appeared on the Internet. The Internet allows many
different types of computers to connect together, including computers that use fundamentally
different CPU‟s and Operating Systems. Therefore, the ability to write a Portable program is as
beneficial to the Internet as it is to consumer electronic devices.
 “Java‟s Write once, runs any where” philosophy provided a tremendous advantage.

What is JAVA: - Java is a Simple, Object Oriented Architectural, Neutral Platform Independents, Robust,
Multi threaded, GUI Compatible, Distributed, Network Compliant and Internet Supported.

Java is Two things:


(1). Programming Language.
(2). Platform.

(1). Java is Programming Language: -

Java is a High-Level programming Language that is all of the following.

 Java Program is both Compiled and Interpreter. With a Compiler, you translate a Java Program into
an Intermediate language called “Java bytecodes” the platform independent codes interpreted by
the Java Interpreter. With an Interpreter, each Java bytecode instruction is parsed and run on the
computer. Compilation happens just once; Interpretation occurs each time the program is executed.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 8 II.B.Sc., III Sem Java
*** Java bytecode: - Java bytecode as the machine code instructions for the Java Virtual Machine (JVM).
Bytecode instructions are the intermediate codes of a Java Source Code Class file. The Java program is first
converted into Bytecode instructions which are to be submitted to the Java Virtual Machine (JVM) and
translate them into machine language instructions. The size of each bytecode instruction is only one byte.

Java Bytecode help make “Write once, run anywhere” possible. You can compile your
Java program into bytecodes on any platform that has a Java compiler. The bytecodes can then be
run on any implementation of the Java Virtual Machine (JVM). For example, the same Java Program
can run on Windows, NT, Solaris, etc.

(2). Java Platform: -

A Platform is the Hardware or Software Environment in which a program runs. The Java
Platform differs from most other platforms in that it‟s a software only platform that runs on top of other,
hardware-based platforms. Most other platforms are described as a combination of Hardware and
Operating System.

The Java Platform has Two components: -


(1). The Java Virtual Machine (JVM).
(2). The Java Application Programming Interface (Java API).

(1). The Java Virtual Machine (JVM): - Java Virtual Machine (JVM) is the base for the Java Platform and
is ported onto various hardware-based platforms.

(2). The Java Application Programming Interface (Java API): - The Java Application Programming
Interface (Java API) is a large collection of „ready-made‟ software components that provide many useful
capabilities, such as Graphical User Interface (GUI) widgets. The Java Application Programming Interface
(Java API) is grouped into libraries (Packages) of related components.

(Q). Explain the Basic Java Features?

Sun Microsystems officially describes the following features.

1. Simple and Small.


2. Object Oriented.
3. Distributed Computing.
4. Interpreted.
5. Robust.
6. Secure.
7. Architecture-Neutral.
8. Portable.
9. High Performance.
10.Multithreaded.
11.Dynamic and Extensible.

1. Simple and Small: -


 Java is simple because it consists of only three primitive data types Numbers, Boolean types and
Arrays.
 Java has no preprocessor. This means that the concepts behind #define and typedef are not
necessary in Java.
 Java reduces the redundancy of C++ by removing structures and unions from the language.
 Java does not allowed pointers.
 One of the most important features is automatic memory management, usually known as Garbage
collection. Garbage collection is really just a blue-collar team that means that you don‟t need to
free memory that you allocate the Java Virtual Machine (JVM) takes care of doing.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 9 II.B.Sc., III Sem Java
2. Object Oriented: -
 Java is pure Object Oriented Programming (OOP‟s) language that provides Data Abstraction, Data
Encapsulation, Inheritances and Polymorphism etc.
 Except for its primitive data types (Number, Boolean Types and Arrays), everything in Java is an
objects. Strings are Objects, Threads are Objects, and even Applets are Objects.

3. Distributed Computing: -
 Java is designed for the distributed environment of the Internet, because it handles TCP/IP Protocol
 Java has various libraries to deal with Network protocols. A protocol refers to a set of rules and
regulations to be following while transferring data on the Internet.
 Java provides new technique called Remote Method Invocation (RMI) that allows objects on two
different computers to execute procedures remotely.

4. Interpreted: -
 Java is both Compiled and Interpreted. That is a Java Source Code (program) is first compiled and
then interpreted. This is made possible by the Java Virtual Machine (JVM). The Java Virtual Machine
(JVM) converts the intermediate bytecode into the machine code.

Compile
Source Code Byte Code
(Compiler)

As shown in the above figure a C++ source code is only compiled, not interpreted.
 A Java source code as first compiled to produce the bytecode which is then interpreted using the
java interpreter to produce the machine code.

Compiler Interpret
Source Code Byte Code Machine Code
(Compiler) (Interpreter)

 Java Source Code goes through two processes Compilation and Interpretation. The Java Interpreter
is names „java‟ and „Java Compiler‟ name is called „javac‟.

5. Robust: -
 Java is a Robust Programming Language, provides many safeguards to ensure reliable code. It has
strict compile-time and run-time checking for data types.
 It is a designed as a “Garbage collection”. Java has extensive Memory management system. Java
also incorporates the concepts of Exception Handling, which helps to programmer to make the
program, which is safer from any type of run-time errors.
 Memory management has been simplified in Java in two ways. First, Java does not support direct
pointer manipulation or arithmetic. This makes it impossible for Java program to overwrite memory
or corrupt data. Second, Java uses runtime Garbage collection instead of explicit freeing of memory.

6. Secure: - Java is secure because

 No Pointers are forged.


 No illegal objects casts are preformed.
 Rules regarding Private, Protected, and Public class memberships are followed.
 Java is highly secure. The security of Java is First the Java Interpreter verifies the bytecode before
executing it. If the bytecode turns out to be invalid, it will not be executed at all. The following
figure shows this schematically.

Bytecode Java Interpreter

Verify Code If Valid Executed

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 10 II.B.Sc., III Sem Java
7. Architecture-Neutral: -
 Java Program can be easily moved from one computer to another system, any where and any time,
changes and upgrades in Operating System, System Resources and Processors will not force any
changes in Java programs. So Java is „Platform Independent Programming language or Architecture-
Neutral‟.
 By Architecture Neutral, we means that Java is not dependent on the on the architecture of a
particular machine. The same Java program can be run on the verity of CPU‟s and Operating
Systems.
 The Java compiler converts the Java source code in to bytecodes, which is architecture neutral. If
Java Interpreter exists on a machine, we can run Java bytecode on that machine.

Java Program Run in Sun Solaris OS

Java Program Run in Windows

Java Program store in a Hard disk

Java Program Run in Apple Macintosh OS

8. Portable: -
 Java is a Portable language. Apart from the bytecodes, which is machine independent and hence,
can be implemented on any system with Java Virtual Machine (JVM) installed?.
 The data types of Java also account for its portability. The size of the basic data types in Java is
compatible with for all systems making Java programs highly portable.
 In Java all primitive data types (Integers, Floats, Longs, doubles, and so on) are of defined sizes,
regardless of the machine or operating system on which the program is run.

Example: - For example, in Java an „Int data type‟ is always 32-bit value, no matter in which system it
is used. Similarly, the size of other data types is also explicitly specified. The following figure represents
the above feature of Java.

32-bit integer value for Sun Solaris OS

Int (32-bit
Integer
Value) 32-bit integer value for Windows
OS (operating System)
Java data type

32-bit integer value for Apple Macintosh OS

9. High Performance: -
 Java is „High Performance‟ speed is an important feature of a programming language because its
bytecode is efficient and perform multiple concurrent activities.
 Since the Java source code is first compiled and then interpreted, Java programs are executed very
fast. Java bytecode is run by the interpreter.

10. Multithreaded: -
 Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded
programs. That means that we need not wait for the application to finish one task before beginning
another. Java has very good mechanism for running and coordinating parallel processes.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 11 II.B.Sc., III Sem Java
 But in Non-Threaded environment only one line of executions takes place at a time. Only after the
computer has finished executing one line will it proceed to the next line. Hence one task has done to
be completed before another one can be preformed.
 In a multithreaded environment, we need not wait for the application to finish one task before
starting another.
 A good example of multithreading is that when you are downloading a file from the Internet, you
can surf through a web page.

11. Dynamic and Extensible: -


 Java is an extremely Dynamic language. At runtime, the Java environment can extend itself by
linking libraries, functions, methods and classes. (For example the Internet).
 At runtime, the Java interpreter performs name resolution while linking in the necessary classes.
The Java interpreter is also responsible for determining the placement of objects in memory.

Additional Features of Java2 Standard Edition 5.0 (J2SE 5.0):-

1. Easy of Development.
2. Scalability and Performance.
3. Monitoring and Manageability.
4. Desktop Client Support.
5. Core Extendable Markup Language (XML) supported.
6. Java Database Connectivity (JDBC) row sets.

(Q). Explain difference between C and C++?

Difference between C and C++: -

C – Language C ++ Language
C – Language is a Structure / Procedure C ++ Language is a Object Oriented
Oriented Programming Language. Programming Language.
A large program can be divided into smaller A large programming can be divided into smaller
modules called as Procedures. modules called as Objects.
Its followed as the designed program. Its also follows some rules in program.
To declared the variable at first to need. To declare the variables at any place in the
program can be use.
The variables are declared after main() function. The variables are declared any where in the
program but before using it.
They don‟t permit data hiding. They permit data hiding.
They don‟t allow the ADT (Abstract Data Type). They allow the ADT (Abstract Data Type).
It follows Top-Down approach. It follows Top-Down or Bottom-Up approach.
They can‟t work dynamic binding. They can run dynamic binding.
To write any function in C-Language Function To write any Function in C++ Language Function
Prototype, Function return type is optional. Prototype, Function return type is necessary.
C-Language can‟t support Inheritances, C++ Language can support Inheritances,
Polymorphism, Encapsulation etc, and concepts. Polymorphism, Encapsulation etc., and concepts.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 12 II.B.Sc., III Sem Java
(Q). Explain How Java differs from C and C++?

Java was differs from C and C++ languages in many ways. Java does not incorporate a number of
features available in C and C++. The following are the major differences between C and C++ and Java.

Differences with Java and C: -


 Java is an “Object Oriented Programming language” where C is a “Structured Oriented Language.
 Java does not have a preprocessor and therefore we can‟t use #define, #include etc statements.
 Java does not contain the data types like “Struct, Union and enum”.
 Java does not define the type modifiers keywords “auto, register, signed, unsigned, extern”.
 Java does not include the C unique statements keywords “goto, sizeof and typedef”.
 Java does not support an explicit “pointer types”.
 Java support adds “labeled, break and continue statements.

Java is true Object Oriented Programming language while C++ is basically c with Object Oriented
extension. However, there are few basic points where Java differs from C++.

Differences with Java and C++: -


 Java there is no header files.
 Java does not support Operator Overloading.
 Java does not have templates.
 Java does not support multiple inheritances concepts.
 Java does not use any pointers.
 Java has no Global variables, because all Java programs elements must exist inside a class.
 Java has replaced the Destructor function with a „finalize ()‟ function.
 Java is both Compiled and Interpreted but C++ which is only compiled language.
 The Plus (+) operator can be used to concatenate strings in Java.
 Class definitions are similar in Java and C++, but there is no closing semicolon (;) in Java.
 Modulus operator can be applied to float values in Java which is not permitted in C++.
 There is no „goto‟ in Java. The „Break and Continue‟ statements can be used to jump out of the loop
 There is no scope resolution operator (::) in Java.

(Q). Discuss Java and Internet?

Java is designed in such a way that it can easily create Internet-enabled applications. Java
programs are of the following three types.

1. Stand-alone Application or Application.


2. Web Applets.
Java Source
3. Web Servlet.
Code

Java Compiler

Applet Type Servlet Type


Application Type

Java Interpreter Web Browser Java Interpreter

Output Output Output

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 13 II.B.Sc., III Sem Java
1. Stand-alone Application (or) Application: - A stand-alone application is programs written in Java
carry out certain task on a stand-alone local computer. Executing a stand-alone Java program involves

Step 1: - Compiling Source Code into Bytecode using “javac” compiler.


Step 2: - Executing the Bytecode program using “java” interpreter.

2. Web Applets: - Applets are small Java programs developed for Internet Application. An Applet located
on a distant computer (Server) can be downloading via Internet and Executed on a local computer (Client)
using a Java capable browser.
Applets are programs that run in web browsers. Java is often referred to as an internet
programming language because it supports Applets. Applets form one of the most distinguishing features
of Java. “Applets arte programs are generally executed on the web browser. Java also provides a utility
called Applet Viewer to executed Applets”.

3. Web Servlet: - Servlet are small programs that executed on Server side or site of a web connection.
Like Applets, Servlets dynamically extend the functionality of the web server. Servers are platform
independent, because they are written in Java.

(Q). How is Java associated with World Wide Web (WWW)?

World Wide Wed (WWW) is commonly abbreviated as „Web‟. Web is a global information
media which users can read and write via computers connected to the Internet. The information available
in the Web is accessed with the help of a language called as a “Hypertext Markup Language (HTML)”. The
Web pages contains HTML tags that enable you to find, retrieve, display and manipulate documents on the
World Wide Wed (WWW).

Figure: - Web Structure

Java could be easily incorporated into the web systems. This system contains web pages that
provide both text and graphics. The incorporation of Java into web pages has made it capable of supporting
animations, graphics, games and many special effects with the support of Java the web has become more
interactive and dynamic.

The widely used protocols like HTTP (Hyper Text Transfer Protocol) and FTP (File Transfer
Protocol) are developed in Java. Internet programmers can call functions on these protocols and can get
access the files from any remote machine on the internet rather than writing codes on their local system.

Java communicates with a web page through a special tag called <Applet>. The figure shows
Client Request Client Request

Network
Client Web Server

Server Send response Server Send response


as web page as web page

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 14 II.B.Sc., III Sem Java
The following are communication steps.

Step 1: - The User sends a request for an HTML (Hyper Text Markup Language) document to the remote
computer‟s web server. The web server is a program that accepts a request, processes the
request and send the required document.

Step 2: - The HTML (Hyper Text Markup Language) document is return to the User‟s browser the
document contains the “Applet” tag which can identify the „Applet‟.

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

Step 4: - The Java enable browser on the User‟s computer interprets the bytecode and provides output.

Step 5: - The User may have further interaction with the Applet but with no further downloading from the
provides web server this is because the bytecode contains all necessary information to
interpreter the Applet

User‟s Computer Remote Computer

Bytecode Applet Source Code

HTML Bytecode
Document
Java Web Browser

Request Applet Tag HTML

Outputs Web Server

User

Fig: - Java‟s Interaction with the Web

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 15 II.B.Sc., III Sem Java
(Q). Explain various kinds of Web Browsers?

Internet is huge collection information represented in many formats stored on many computes. Web
Browsers are used to navigate through the information found on the Internet. They allow us to retrieve the
information spread across the Internet and display it using the Hyper Text Markup Language (HTML).
The following are some of the popular Web Browsers used Now-a-days to retrieve
information on the Internet.

 HotJava.
 Netscape Navigator.
 Internet Explorer.
 Mozilla Firefox. etc.

1. HotJava: -

HotJava is the name given by “Sun Microsystems” to its Java World Wide Web Browser (JWWW).
HotJava is written entirely in Java. Although HotJava‟s purpose is to view Applets embedded in HTML
(Hyper Text Markup Language) documents.

HotJava presents the user with a very clean and simple interface. Because HotJava includes
a Java Virtual Machine (JVM), it is possible to create Web Pages with active, dynamic and interactive.

2. Netscape Navigator: -

Netscape Communications Corporation develops a browser called „Netscape Navigator‟ to interact


with the Web. It is a general purpose browser that can run Java Applets. It supports many platforms to
work on. It supporting scripting languages like JavaScript, VBScript etc language used in HTML document.

3. Internet Explorer: -

Microsoft developed another popular browser called „Internet Explorer‟. It uses a Just-In-Time (JIT)
compiler which greatly increases the speed of execution.

4. Mozilla Firefox: -

Mozilla Firefox is one of the best browsers out there on the market, and its free. Through the unique
development methods of Open Source, they are able to make a product with impressive speed and then
programs developed by traditional methods. Mozilla Firefox has a number of unique features and it is
overall a good product.

(Q). What are the Hardware and Software Requirements for running Java program in machine?

Java language supports programming of different platforms like Unix Operating System, Windows
Operating System, Sun Solaris Operating System etc. since it support majority of the operating systems
available now, it is called „Cross-Platform programming language‟ or „Platform-independent programming
language‟. To implement Java programs we need that following Hardware and Software as minimum.

Hardware Requirement Software Requirement


Minimum of 8 MB RAM. Windows / Unix Operating System.
IBM-Compatible 486 System. Java Run-time Environment.
Hard Disk Drive.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 16 II.B.Sc., III Sem Java
(Q) Java Support Systems?

The following form discussion Java support systems.


 Internet Connection.
 Web Browser.
 Web Server.
 HTML (Hyper Text Markup Language).
 Applet Tags.
 Java Code.
 Bytecode.

Internet Connection: - Local computer should be connected to the Internet.


Web Browser: - A program that provides access to World Wide Web (WWW) and run Java Applets.
Web Server: - A program that accepts requests for information and sends the required documents.
HTML (Hyper Text Markup Language): - A language for creating hypertext for the web pages.
Applets Tags: - For placing Java Applets in HTML (Hyper Text Markup Language) documents.
Java Code: - Java Code is used for defining Java Applets.
Bytecode: - Compiled Java code that is referred to in the Applet Tag and transferred to user computer.

(Q). Explain the various Java Tools?

In order to write Java Application or Applets, you need more than a language you need the tools
that lets you write, test and debugging your program.

The following tools can supported to design Java Programs or Applications.

 Compiler.
 Interpreter.
 Debugger.
 Disassembler.
 JavaDoc.
 Applet Viewer.

1. Compiler: - Java Compiler, named „javac‟. The Java Compiler takes input source code files and
converts them into compiled bytecode files.

2. Interpreter: -The Java Interpreter named „java‟ can be used to execute Java applications. The
Interpreter translates bytecodes directly into program actions.

3. Debugger: - The Java Debugger name „jdb‟ enables your Java classes. The Java debugger is a
command-line debugger. You can use the „jdb‟ to set breakpoints, inspect objects and variables and
monitor threads.

4. Disassembler: - Java Developer‟s Kit (JDK) a Disassembler, „javap‟, that can be used to display the
public interface, both methods and variables, of a class. Additionally the Java Disassembler includes
options to display private members or to display the actual bytecodes for the class‟s methods. This last
option can be particularly useful if you want to achieve a greater understanding of the bytecodes used by
the Java interpreter.

5. JavaDoc: - Using the JavaDoc utility provided with the Java Developer‟s Kit (JDK), you can easily
generate documentations in the form of HTML (Hyper Text Markup Language) files. You can embed special
comments and tags in your source code and then process your code through JavaDoc. All of the on-line
Java API (Application Program Interface) documentation was created with JavaDoc.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 17 II.B.Sc., III Sem Java
6. Applet Viewer: - This is small program provides real Java Environment for testing Applets. It loads the
HTML (Hyper Text Markup Language) file in which the Applet has been embedded and displays the
application in a browser-like window.

(Q). Explain 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)”. Classes
and Methods are parts of the “Java Standard Library (JSL)” also known as the “Application Programming
Interface (API)”.

Java Environment

(I). Java Development Kit (JDK) (II). Java Standard Library (JSL)
(or)
Application Programming Interface (API).

 Java Development Kit (JDK) based on part of „Development Tools‟.


 Java Standard Library (JSL) or Application Programming Interface based on part of „Classes & Methods‟.
(I). Java Development Kit (JDK): -

Java Development Kit (JDK) comes with a collection of tools which are essential to developing and
running Java programs. The Java Development Kit (JDK) following elements are:

 javac. (Java Compiler)


 java. (Java Interpreter)
 javap. (Java Disassembler)
 jdb. (Java Debugger)
 javadoc. (Java Document)
 javah. (Java Header File Generator)
 Appletviewer. (Java Applets)
 Text Editor.

1. javac: - Java Compiler, named „javac‟. It translates Java Source Codes to bytecodes file, that the
Interpreter can read or understands.
2. java: - Java Interpreter, names „java‟. Which runs Applets and Applications by reading and interpreting
bytecode files.
3. javap: - Java Disassembler named „javap‟. It encodes bytecodes to program files.
4. jdb: - Java Debugger named „jdb‟. Which helps us to find errors and remove them from the programs?
5. javadoc: - Java Documentation named „javadoc‟. It creates HTML formats documents from java code.
6. javah: - Java Header File Generator named „javah‟. It is produces Header files for native C-Language.
7. Appletviewer: - Java Applet Viewer named „Appletviewer‟. It enables us to run Java Applets.
8. Text Editor: - To create a Java program, we need to create a source code file using Text Editor.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 18 II.B.Sc., III Sem Java
The way these tools are applied to build and run application programs is illustrated below.

Text Editor

Java Source Code JavaDoc HTML

javac

Java Class File Javah Header Files

java jdb

Java Program
Output

Figure: - Process of building and Running Java Application Programs.

(II). Java Stranded Library (JSL) or Application Programming Interface (API): -

Java API (Application Programming Interface) or JSL (Java Stranded Library) consists of nearly
about 1500 classes and interfaces and more than 13000 methods. These classes and methods are grouped
in to several packages. The most commonly used packages are following below.

Name of the Package Description of about Package


java.lang Package Provides a number of Classes, Interfaces and Methods that are required
for implementing basic features of Java.
java.util Package Provide utility functions such as date, time, calendar etc.
java.Applet Package Provide basic functionality for the creation of Applets.
java.awt Package Provides classes that implement platform independent Graphical User
Interface (GUI), Painting Graphics and Images.
java.io Package Provide a collection of classes required for Input and Output operations.
java.net Package Provides a set of classes for communicating with other computer via
Internet.
java.sql Package Provide interaction with any Database.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 19 II.B.Sc., III Sem Java
(Q). How to Install Java Software in your home or local Machine?

They have following steps will be followed by installing any version of Java software packages.

Step 1: - Select the Java Software location (Hard disk or CD ROM).


Step 2: - Click on “Java jdk1.8.exe” icon application to be setup Java.
Step 3: - Java will started initialization in your computer.
Step 4: - Click on “Next” button on wizard of Java.
Step 5: - Click on “Next” and “Next” and “Finish” button.
Step 6: - Java Software is setups completed and setup the Java path into your system.
Step 7: - Open the “C-Drive” and select the “Program file” choose the “Java Folder” and Click on “jdk1.8”
and press double click on “Bin Folder” and press enter.

D:\ Program Files \ Java \ jdk1.8 \ bin

Step 8: - Click on “My Computer” icon on desktop right click select “Properties” click on “Advanced”
button choose “Environment Variable” double click on “Path”.

My Computers  Properties  Advanced  Environment Variable  Path.

Step 9: - Put semicolon (;) and paste the path as earlier copied of the path again put semicolon (;) end of
the path.
Step 10: - After doing all above steps to check its run or not.
Step 11: - Goto Run Command and type “Javac” it display all auto exe files and close the DOS window.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 20 II.B.Sc., III Sem Java
(Q) Discuss Simple Java Application Program?

The Java Program can be typed in any text editor, such as Notepad of windows or edit of DOS (Disk
Operating System). The only necessary condition is that it will have the extension as „dot (.) Java‟.

First Example Program: -

1. Import java.lang.*;
2. Class HelloWorld
3. {
4. public static void main(String args[])
5. {
6. System.out.println(“Hello! Welcome to Java. Mr.Shaik Mohammad Fareed, MCA, M.Sc.,”);
7. }
8. }

Save: - HelloWorld.java
Compile: - D:\Fareed Javaprog> javac HelloWorld.java
Run: - D:\Fareed Javaprog> java HelloWorld

Output: - Hello! Welcome to Java. Mr. Shaik Mohammad Fareed.

Analyzing the above program: -

Let‟s therefore discuss the program line by line and understand the unique features that consist of Java.

(1). Import Statement: - Import Statement is used to instruct the Interpreter to load a class or set of
classes or an interfaces or set of interfaces into a program. Import java.lang.* This Import is API
(Application Programming Interface) or JSL (Java Stranded Library) consists the respected classes and
methods.

Syntax of Representation of Import Statement: -

Import Package_Name.Sub_Package_Name.Class_Name;

(2). Class Declaration: -

 The Second line of the program is Class Declaration or class header.


 Class declaration is the keyword of “„class” along with the name of the class.
 Syntax of Declaration class: - Class <Class Name>
 In this above example „Class HelloWorld‟ is the class declaration.
 Here above example „HelloWorld‟ is an identifier that is the name of the class.
 Class name must be case sensitive; it distinguishes between upper and lower cases.
 The entire class definition will be between the braces ( {} ).

(3). Parenthesis (or) Braces: -

 Every Class definition in Java begins with an Opening Braces “ { ”.


 And Ends with a matching Closing Braces “ } ”.
 In above example program Line 3 and 8 the definition of the “HelloWorld” starts from Line 3 which
contains the Opening braces “ { ”.
 And end on line 8 which has the closing brace “ } ”.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 21 II.B.Sc., III Sem Java
(4). Main () Method: -

 Every Java Application program must include the “Main ()” method.
 “public static void main(String args[])” defines a method named main.
 This is the starting point for the Interpreter to begin the execution the program.
 Java Application can have any number of classes, but „only one of the must include main() method‟
 Every main() method contain a number of keywords like „public‟, „static‟, „void‟ and „String[] args‟.

 Public: - The keyword „public‟ as an access specifier. When a class member is declared as public,
then that member may be accessed by outside the class in which it is declared.

 Static: - The keyword „static‟ allows main() to be called with out creating or having to instantiate a
particular instances of the class.

 Void: - The keyword „void‟ tells the compiler that main() does not return a value.

 Any information that you need to pass to a method is received by variables specified with in a set of
parenthesis that follow the name of the method.

 String args[]: - String args[] declares a parameter named args (arguments), which is any array of
instances of the class String. Object of type String store array of characters strings. args
(arguments) receives any command line arguments, however this arguments is optional, present in
the program is executed.

(5). Output Statements: - This is similar to the „Printf()‟ statement in C-Language or „Cout<<‟ construct
of C++ languages. This line contain single statement inside the main() method. Where executed, it prints
the string specified in the parentheses on the screen. Let us understand this statement in detail.

Object to System Class

System.out.println(“Hello! Welcome to Java. Mr. Shaik Mohammad Fareed”);

Member of Method of String Argument


System Class System Class

The various components of this statement are indicating above the explanation of each of these elements.

System: - This is a pre-defined class present in the Standard Java Library (SJL) that comes along with
Java Development Kit (JDK). All variables and methods in the system class are static.

Out: - It is an Object of the System Class.

Println (): - This is s method of the “Out” object. Its main function is to print the specified string on the
screen and terminate (;) the line. It takes one string argument.

NOTE: -

 In Java all Code must be reside inside a Class and therefore each java program must have at least
one class. By conversion, the name of the Java program should match with the name of the class
which has main () method in itself.

 If there are more than one class in a Java program then at least one class can have main ()
method. If you do not do this the compiler will compile it successfully, but the interpreter will not
run it. The main reason is that when we compile a Java program then each individual class is put in
to its own output file named after the class and using the dot (.) class extension.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 22 II.B.Sc., III Sem Java
Comments Line in Java Program: -

Comments are actually non-executable statements which are meant for the programmers own
convenience. A comment is usually an explanation regarding the statement. A comment does not affect the
output. Java permits both the single line comments and multi line comments available in Java.

 The Single line comment begin with “//” symbol and end at the end of the line.
 Multi line comment by starting with “/*” symbol and ends with “*/”.

Java Programming language can supports three kinds of comments.

1. // Shaik Mohammad Fareed.


2. /* Shaik
Mohammad
Fareed */
3. /** Mr.Shaik Mohammad Fareed, MCA.,IRPM., * /

Example Program: -

1. Import java.lang.*; // Java Stranded Library (JSL).


2. Class HelloWorld // Class Declaration.
3. { // Parenthesis or Braces.
4. public static void main(String args[]) // Main() Method.
5. {
6. System.out.println(“Hello! Welcome to Java. Mr.Shaik Mohammad Fareed”); //Output statement
7. }
8. }

Save, Compile and Run the Java Application: -

(1). Save: - To open the Notepad (or) Java Editor and type the program code in the editor and save.

Syntax for Saving: - <File Name>.Java

Example: - HelloWorld.Java

NOTE: - To give the file name as equal to class name is most and case sensitive.

(2). Compile: - After prepare the Java code and Save the file name as class name and now compile the
program. If program has any logical and syntax error can be find out by compiler.

Syntax for Compile: - D:\ Folder Name> Javac <File Name>.Java

Example: - D:\ Fareed Javaprog> javac HelloWorld.java

NOTE: - If you have no error the program will run, otherwise it can display the location of errors in
program.

(3). Run: - If after complete the compilation the program will be run it.

Syntax for Run: - D:\Folder Name> Java <File Name>

Example:- D:\J Fareed Javaprog> java HelloWorld

NOTE: - It will display the specified results in output statement.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 23 II.B.Sc., III Sem Java
Example Program: - Write the simple program in Java to calculate the Square Root of vales?

Import java.lang.math;
Class SquareRoot
{
public static void main(String args[])
{
double x=5; // Declaration and Initialization.
double y;
y = Math.sqrt(x);
System.out.println(“ Y = “ + y);
}
}

Save: - SquareRoot.Java
Compile: - D:\ Fareed Javaprog>javac SquareRoot.java
Run: - D:\ Fareed Javaprog> java SquareRoot

Output: - Y = 2.23607.

(Q). Discuss about Java Program Structure?

Every programming language follows certain program structure which is followed by the programmers.
A 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 as shown in below figure.

Documentation Sections Suggested

Package Statements Optional

Import Statements Optional

Interface Statements Optional

Class Definitions Primary Essential

Main Method class


{
Essential
Main Methods Definition
}

Figure: General Structure of Java Program.

1. Documentation Selection: -

The Documentation section comprises a set of „Comment lines giving the name of the program‟.
Java permits both single and multiple line comments available. This is Documentation Selection is
Suggested.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 24 II.B.Sc., III Sem Java
2. Package Statements: -

The first statement allowed in a Java file is a package statement. This statement declares a package
name and informs the compiler that the classes defined here belong to this package. The Package
statement is optional.

Example: - Package Student;

3. Import Statement: -

After Package declaration statement, the immediate next line must be the “Import Statement”.
Example: - Import Student.marks;
This Statement instructs the interpreter to load the “marks” class contained in the package
“Student” using import. We can access the classes that are part of the package.

4. Interface Statement: -

An Interface is like a class but include a „group of method declaration‟. This is also an optional.

5. Class Definition: -

A Java program may contain multiple class definition. 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.

6. Main Method Class: -

Since every Java stand-alone program requires a main method as it starting point, this class is the
essential part of the 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.

(Q). Explain Language Building Blocks (OR) Java Tokens?

Smallest individual units in a program are known as Tokens. The compiler recognized them for
building up expressions and statements.

Java programming language is defined by grammar rules that specify how syntactically legal
constructs can be formed using the language elements and by a semantic definition that specifies the
meaning of syntactically legal constructs. The Java language includes five types of tokens they are:

1. Reserved Keywords.
2. Identifiers.
3. Literals.
4. Operators.
5. Separators (or) Delimiters.

(I). Reserved Keywords: -

Keyword is an essential part of a language definition. Keywords are reserved identifiers that have a
special meaning in Java. Keywords are not available for use as names of things defined in program. Java
language has reserved 50 words as keywords. All keywords are to be written in lowercase letter. Since
Java is case sensitive. Some of the keywords are listed below.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 25 II.B.Sc., III Sem Java
Abstract Boolean Break Byte Case
Catch Char Class Continue Default
Do Double Else Extends False
Final Finally Float For If
Implements Import Instance of Int Interface
Long Native New Null Package
Private Protected Public Return Short
Static Super Switch Synchronized This
Throw Throws Transient True Try
Void Volatile while

The keyword, combined with operator and separators according to syntax, from definition of the Java.

Group Keywords Meaning / Function


Package Specifies the class in a particular source file should belong to name package.
Class Import Requests the named class or classes be imported into current application.
Interface Defines global data and method signatures that can be shared among class.
Class Class Defines a collection of related data behavior.
Definition. Extends Indicates which class to sub class.
Implements Indicates the interface for which a new class will supply methods.
Abstract Specifies the class cannot be instantiated directly.
Public Means the class, method or variables can be accessed from any where
Keywords Private Means only the class defining the method or variable can access it.
For Protected Means only the defining class and its subclass can access the methods.
Classes Static Specifies a class methods or variable.
And Synchronized Indicates only one object or class can access this variables at a time.
Variables Volatile Tells the compiler this variable may change asynchronously due to threads.
Final Means this variable or methods cannot be changed by subclasses.
Const Means this variable cannot be change.
Native Links methods to native code.
long It is a 64-bit integer value.
int It is a 32-bit integer value.
Short It is a 16-bit integer value.
Simple Byte It is a 8-bit integer value.
Datatype Double It is a 64-bit floating point value.
Float It is a 32-bit floating point value.
Char It is a 16-bit Unicode character.
Boolean It is a True of False value.
Void Indicate a method does not return a value.
False It is a Boolean value.
Values True It is a Boolean value.
and This Refers to the current instance in an instance methods.
Variables Super Refers to the immediate super class in a method.
Null Represents a non existent instance.
Throw Throw an exception.
Exception Throws Throws an exception.
Handling Try Marks a stack so that if an exception is throwing, it catches an exception.
Finally Says execute this block of code regardless of exceptions error handing flow.
Catch Catches an exception.
Instance New Creates New Instances.
Instance of Test whether an instance derives from a particular class or interface.
Control Switch Test a Variable.
Flow Cases Executes a particular block of code according to the values.
Default Means the default block of code execute.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 26 II.B.Sc., III Sem Java
Return Return form a method, optionally passing back a value.
Break Breaks out a particular block of code.
Continue Continue with next iteration of a loop.
Control goto Directs control to a specifies place.
Flow do Performs some statements or set of statement.
if Test for condition action, if True.
Else Performs action, the condition was False
For Signifier iteration.
While Performs some action while a condition is True.

Data Declaration Keywords Byte int float Char double


Loop Keywords Do while for break continue.
Conditional Keywords If else switch
Exception Keywords Try Throw catch
Structure Keywords Class extends interface implements
Access Keywords Public private protected

(II). Identifiers: -

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

 They can have alphabets, digits and the underscore ( _ ) and dollar sign ( $) characters.
 They must not begin with a digit.
 Uppercase and Lowercase letters are distinct.
 They can be of any length.

Example of Legal Identifiers: - Mohammad, fareed, Mohammad_fareed, Fareed_$

NOTE: - Identifiers must be meaningful, shot enough to be quickly and easily typed and long enough to be
descriptive and easily read.

Naming Conversions for Identifiers: -

 Names of all public methods and instances variables start with a leading lowercase letter.
Example: - mohammad, fareed, muneer, etc.
 When more than one word is used in a name, the second and subsequent words are marked with a
leading Uppercase letters.
Example: - mohammad_Fareed (valid), dayTemperature (Valid), firstdayofmonth (invalid). etc.
 All private and local variables use only lowercase letters combined with underscore.
Example: - fareed, mohammad_fareed.
 All classes and interfaces start with a leading uppercase letter with a leading uppercase.
Example: - MohammadFareed, HelloWorld, MotorCycle, HelloJava.
 Variable that represent constant values use all uppercase letters and underscore between words.
Example: - MOHAMMADFAREED, MOHAMMAD_FAREED, FAREED.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 27 II.B.Sc., III Sem Java
(III). 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.
2. Floating–Point Literals.
3. Character Literals.
4. String Literals.
5. Boolean Literals.

1. Integer Literals: -

 Integer Literals can be specified in Decimal, Hexadecimal or Octal notation.


 A Literal is an explicit value that is used in programs.
 Integer data types are comprised of the following primitive data types: Int, Long, Byte and Short.
 To specify a Decimal value, simply use the number as normal to indicate that a literal value is a
long, you can append either “L” or “1” to the end of the number.
 Hexadecimal values are given in base 16 and include the 0-9 and the letters A-F.
 Similarly an Octal value is identified by a leading „0‟ symbol.

Integer Long Octal Hexadecimal


0 0L 0 0X0
1 1L 01 0X1
10 10L 012 0XA
15 15L 017 0XF
16 16L 020 0X10
100 100L 0144 0X64

2. Floating-Point Literals: -

 Floating Point literals can be specified in either the familiar decimal notation (example: 3.145) or
exponential notation (example: 6.02e3d).
 To indicate that a literal is to treated as a single precision float, append either “f” or “F”.
 To indicate that it is to be treated as a double precision value, append either “d” or “D”.

Example of Valid Floating-Point Literals: - 43.3F, 3.1415d, -12.123f, 6.02e+23f, 6.02e23d. etc.

3. Character Literals: -

 A Character Literals is a single character or an escape sequence enclosed in single quotes.


 All character are represented are represented by a Unicode. The Unicode character set subsumes
the 8-bit ISO-Latin-1 and the 7-bit ASCII characters valid character literals.

Sequence \b \t \n \r \f
Purpose Backspace Horizontal New line feed Carriage return Form Feed

4. String Literals: - A String literal consist of zero or more characters enclosed in double quotes.

Example of Valid String Literal: - “Shaik”, “Mohammad Fareed”, “Fareed”, “MCA”, “IRPM”.

5. Boolean Literals: - Java Support Two Boolean Literals: True or False.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 28 II.B.Sc., III Sem Java
(IV). Operators: -

An Operator is a symbol which represents some particular action. Operators operate on operands.
Operand may be either variable or constant. There are several types of operators available in Java.

1. Arithmetic Operator ( +, -, *, /)
2. Relational (or) Comparison Operator (==, !=, <, >, <=, >=).
3. Logical Operator (or) Compound (Logical And &&, Logical OR ||, Logical NOT !).
4. Assignment Operator ( = ).
5. Incremental / Detrimental Operator ( ++, -- ).
6. Bitwise Operator (Bitwise And &, Bitwise OR |, Bitwise XOR ^, Left shift <<, Right shift >> etc.)
7. Special Operator. (Dot .)
8. Conditional Operator ( ?).

(V). Separators (or) Delimiters: -

Separators are symbols used to indicate where groups of code are divided and arranged. They
basically define the space and function of our code.

Separator Names Purpose


Parentheses () Encloses parameters in method declaration.
Braces {} Used to open and close a block of statements.
Brackets [] Declared Array types.
Semicolon ; Terminates Statement.
Comma , Separate consecutive in variable declaration.
Period . Separate package name from sub-packages name and class. Refers a
member of objects.

(Q). Explain Java Statements?

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. However, it is possible to control the flow
of execution. If necessary using special statements. Java implements several types of statements.

1. Expression Statements.
2. Label Statements.
3. Synchronization Statements.
4. Guarding Statements.
5. Selection Statements. (If, If –Else , Switch etc)
6. Iteration Statements. (While, Do-While, For)
7. Transfer Statements. (Break, Continue, Return)

(Q). Implementing a Java Program?

Implementation of Java Application Program involves a series of steps. They are

1. Creating the Program.


2. Compiling the Program.
3. Running the Program.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 29 II.B.Sc., III Sem Java
Method #1: - By Using MS-DOS Editor Window.

(I). Creating the Program: - The following steps are involving for creating or writing any Java program.

Step 1: - Click on START button on the Taskbar.


Step 2: - Select „Accessories‟ in the sub pop-up menu.
Step 3: - Select „Command Prompt‟ (MS-DOS) on the screen.

START Programs  Accessories  Command Prompt (MS-DOS).

Step 4: - Create a New Folder with the name of “Fareed Javaprog‟. By following type command in DOS.
D:\> md Fareed Javaprog
Step 5: - To make the „Fareed Javaprog‟ Folder as the current Folder. By following type command in DOS.
D:\> cd Fareed Javaprog
Step 6: - Now the current folder name becomes „Fareed Javaprog‟ like in DOS
D:\Fareed Javaprog>
So will save the all Java program files in this Folder (Fareed Javaprog).
Step 7: - Now open the „Edit Window of MS-DOS‟ by following command „Edit‟. And press enter.
D:\Fareed Javaprog>edit
Step 8: - Press Enter Key, the MS-DOS Edit Window appears on the screen.
Step 9: - Now write our Java Code in that Editor.

Step 10: - Save the Program by clicking on Save option in the File Menu of the Edit Window.
Step 11: - Type the Name „HelloWorld.java‟ against the file name option. (File name saved with “.java”).
Step 12: - Click on „OK‟ button the program gets saved under the file name “HelloWorld.java”.

(II). Compiling the Program: - Now return the MS-DOS Prompt and Compile the program before Run it

Step 1: - Click on File Menu and select the Exit option. Immediately the Edit Window closes and MS-DOS
Prompt appears on the screen.
Step 2: - Now Compile the Program by following command at the MS-DOS prompt.
“D:\Fareed Javaprog> javac HelloWorld.java”

(III). Running the Program: - Now Run the program for following command at the MS-DOS prompt.

D:\Fareed Javaprog> Java HelloWorld

Output: -

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 30 II.B.Sc., III Sem Java
Method #2: - By Using Notepad Window.

Step1: -Create a New Folder with the name of “Fareed Javaprog‟. By following navigation in any directory
Right Click on Mouse in specific Directory which you create a New Folder.
Right Click on Mouse  Find „New‟ option  Select „Folder‟ option  Give the Folder Name
as (Fareed Javaprog).
Step 2: - Click on START button on the Taskbar.
Step 3: - Select „Accessories‟ in the sub pop-up menu.
Step 4: - Select „Notepad‟ on the screen.
START Programs  Accessories  Notepad.
Step 5: - Now write our Java Code in that Notepad Editor.

Step 6: - Save the Program by clicking on Save option in the File Menu of the Notepad Window.
Step 7: - Type the Name „HelloWorld.java‟ against the file name option. (File name saved with “.java”).
Step 8: - Click on „OK‟ button the program gets saved under the file name “HelloWorld.java”.

(II). Compile the Program: - Now open the MS-DOS Prompt and Compile the program before Run it.

START Programs  Accessories  Command Prompt (MS-DOS).Type the following command in MS-DOS

(III). Running the Program: - Now Run the program for following command at the MS-DOS prompt.
D:\Fareed Javaprog> Java HelloWorld
Output:-

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 31 II.B.Sc., III Sem Java
(Q). Discuss briefly about the Java Virtual Machine (JVM)?

Usually all language Compilers translate source code into machine code for a specific computer.
Java compiler also does the same thing. But Java compiler produces an intermediate code known as
„Bytecode” for a machine that does not exist. This machine is called “Java Virtual Machine (JVM)”.

The heart of Java platform is the Java Virtual Machine (JVM). Most programming languages compile
source code directly into machine native code, suitable for execution on a particular microprocessor.

In the Java programming language, all source code is first written in plain text files ending with the
“.Java” extension. Those source files are then compiled into “.Class” files by the “Javac” compiler. A
“.Class” file does not contain code that is native to your processor; it instead contains “bytecodes”. The
„bytecodes‟ is not machine specific. The machine specific code is generated by the Java Interpreter (Java
Virtual Machine must installed in your machine) by acting as an intermediary between the „Virtual Machine
and the Real Machine‟. The Java Compiler is called „Javac‟ and Java Interpreter is called „Java‟.

Process of Compilation Machine Code

Java Bytecodes
Program (Virtual 010110010
(Source Machine)
Code)

File Name.Java Java Compiler File Name.class Java Interpreter Real Machine
Translated
Process of Converting Bytecode to Machine Code

Process of Compilation: -

1. Java Program (Source Code): - In the Java programming language, all source code is first
written in plain text files and ending saved as File Name with the “.Java” extension.

2. Java Compiler: - Those source files are then compiled (Translated) into “.Class” files by the
“Javac” compiler.

3. Bytecodes: - Java bytecode as the machine code instructions for the Java Virtual Machine (JVM).
Bytecode instructions are the intermediate codes of a Java Source Code Class file. The Java
program is first converted into Bytecode instructions which are to be submitted to the Java Virtual
Machine (JVM) and translate them into machine language instructions.

Process of Converting Bytecode into Machine Code: -

4. Java Interpreter: - The machine specific code is generated by the Java Interpreter (Java Virtual
Machine must installed in your machine) by acting as an intermediary between the „Virtual Machine
and the Real Machine‟.

5. Real Machine: - That executable program in system.

Java use both Compiler and Interpreter. The Job of Compiler is to convert source code to
Bytecode. Where the Job of Interpreter is to submit the Bytecode to Java Virtual Machine (JVM).

NOTE: - Java Virtual Machine (JVM) which is in builds in all Operating System. Latest system having Java
Virtual Machine (JVM) in the Motherboard with the help of Sun Microsystems.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 32 II.B.Sc., III Sem Java
Architecture of Java Virtual Machine (JVM): -

Java Virtual Machine (JVM)


Internet Server Additional class‟s files
Consisting of Java Class Loader. needs as the programs
Bytecodes. needs are loaded.

Bytecodes Verifiers.

Interpreter.

Run Time Environment.

 Loads the Class file into the memory along with related class files, with the helps of class loader.
 Verifies the Bytecode for runtime errors this is done with the help of the bytecode verifier.
 Executed the program.

The Java Object Framework (Java Application Programming Interface) acts as the
intermediary between the user programs and virtual machine which in turn acts as the intermediary
between the operating system and the Java object Framework.

Real Machine.

Operating System.

Java Virtual Machine (JVM)

Java Object Framework (API)

Compiler Interpreter

User Application Programs

Users.

Figure: - Java Framework.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 33 II.B.Sc., III Sem Java
(Q). Explain the Command Line Argument?

Sometime the programmer may want to execute the program to act upon the input provided at the
time of execution. Command Line Arguments are parameters that are supplied to the application program
at the time of invoking it for execution. It may be recalled that program was invoked for execution at the
command line argument.

We can write Java programs that can receive and use the arguments provided in the command line.

Public static void main (String args[])

Here “args[]” is declared as array of strings (known as string objects). Any arguments provided in the
command line (at the time of execution) are passed to the “args” as its elements.

Example: - Example for Consider the Command line : Shaik Mohammad Fareed MCA.

This command line contents four arguments. These are assigned to the array “args” as follow.

Shaik args[0]
Mohammad args[1]
Fareed args[2]
MCA args[3]

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. Index or subscript is start with „0‟.

Example Program for Command Line Argument: -

class CommandLine
{
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("Java is " + args[i]);
}
}

Save: - CommandLine.java
Compile: - Javac CommandLine.java
Run: - java CommandLine Shaik Mohammad Fareed MCA

Output: -

D:\ Fareed Javaprog> Java CommandLine Shaik Mohammad Fareed MCA.

Java is Shaik args [0] : Shaik


Java is Mohammad args [1] : Mohammad
Java is Fareed args [2] : Fareed
Java is MCA. args [3] : MCA.

NOTE: - The above Command executes the Java program „CommandLine‟ by passing the argument “Shaik
Mohammad Fareed MCA”. These arguments are then copied into String array args. We can access the
elements of the above array by using index values. The “length” property gives actual length of the array.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 34 II.B.Sc., III Sem Java
Chapter – 3
Constants, Variables and Data types of Java Language

Introduction: -

A programming language is defined to process certain kinds of data consisting of numbers,


characters and strings and to provide useful output known as information.

(Q) What is Constants? Explain different types of Constants supports in Java?

“Constant is a fixed value that will not be changed ever during the execution of the program”. Once
the programmer defines a value to a constant, it remains same through the entire program. Java supports
several types of constants.
Java Constants

Number Constants Character / String Constants

Integer Constants Real Constants Character Constant String Constant Backslash Constant

Decimal Integer. Decimal Notation.

Octal Integer. Exponential Notation.

Hexadecimal Integer.

(I). Integer Constants: - An Integer Constants refers to a sequence of digits. There are three types.

 Decimal Integer.
 Octal Integer.
 Hexadecimal Integer.

1. Decimal Integer: -

Decimal Integer consists of a set of digits, „0‟ through „9‟. Preceded by an optional minus ( - ) sign.

Valid Example of Decimal Integer: - 94912 02987 0 - 98857 12847.

Embedded spaces, commons and non-digits characters are not permitted between digits.

Invalid Example of Decimal Integer: - 507 047 20,143 $1000.

2. Octal Integer: - An Octal Integer consists of any combination of digits from the set 0 through 7, with
leading 0. Octal value have no sign.

Valid Example for Octal Integer: - 090120 012345 0987.

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


Integer. It consists of 0 to 9 and alphabets A to F to represent the numbers 10 to 15.

Valid Example for Hexadecimal Integer: - 0x20A40 0x2 0xBCD 0X 0xABF6.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 35 II.B.Sc., III Sem Java
(II). Real Constants: - The number containing „fractional parts‟ are called as “Real Constant”. To Real
constants represent fixed floating point value, we use Real Constant. There are two type of constants.

 Decimal Notation.
 Exponential Notation.

1. Decimal Notation: - To Real Constant represent fixed floating point values, we use real constants.
These numbers are represented with a Decimal Notation or values containing a Decimal Point. A real
constant may be either positive or negative sign.

Example: - 0.9885712847 - 143.582 0.0000458795

2. Exponential Notation: - A real number may also be expressed in “Exponential Notation” the
Exponential write as “e2” means multiply the number by 102. The Exponential is an integer with an optional
plus or minus sign. Exponent can write in either lowercase or uppercase.

Example: - 2.156e2. The above value becomes 215.65.


0.6e4 12.e2 1.5e+5 3.18E3 -1.2E-1

NOTE: - Embedded white space is not allowed, in any numeric constants.

(III). Character Constant: - A Single Character constant (or simply Character constant) contains a single
number or character enclosed within a pair of single quote marks.

Example: - „7‟ „X‟ „#‟.

(IV). String Constant: - A String Constant is a sequence of characters enclosed between double quotes.
The characters may be alphabets, digits, special characters and blank spaces.

Example: - “Well Done” “Mr. Shaik Mohammad Fareed” “25-01-2012” 04:30:22 PM”.

(V). Backslash Character Constant: - Java supports Backslash character constants that are used to
format the output presented or method to the user. These characters are also called as “Escape Sequence”
Characters. A list of such Backslash characters constants is given in below.

Constant Meaning
„ \b ‟ Back space
„ \f ‟ Form feed
„ \n ‟ New Line
„ \r ‟ Carriage Return
„ \t ‟ Horizontal Tab
„ \‟ ‟ Single quote
„ \” ‟ Double quote
„\\‟ Backslash

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 36 II.B.Sc., III Sem Java
(Q). What is Variable? Discus briefly about Variables in Java?

A Variable is an identifier that is associated with a particular memory location in the computer‟s
memory. A Variable is one whose value does change in during of the program execution time. A Variable is
capable of storing data values of type to which it is declared. The value of a variable will be changed
frequently during its life in the program. A variable has a name, type, a particular size and a value
associated with it.

Rules for selecting Variable Names: -

1. Variable Name must begin with a alphabet letters.


2. Variable Name should not exceed 256 characters.
3. Uppercase and Lowercase are distinct. This means variable „Total‟ is not same as „total‟ or „TOTAL”.
4. Variable Name must be unique with the same scope.
5. Reserved words or keywords are not allowed as variables names.
6. It should not contain any special characters like +, -, *, /, <, >, =, &, %, @, ||, (), [], {}, Etc.,

Declaration of Variables: - The declaration of a variable tells the compiler what the variable name is,
data type of the variable and scope of the variable. After designing suitable variable names, we must
declare them to the compiler. Each variable must be declared before to use it. Declaration does three
things.

1. It tells the Compiler what the variable name is.


2. It specifies what type of data the variable will hold.
3. The place of declaration decided the scope of the variables.

Syntax to Declaration of variable: - <Data type> <Variable Name>;

Example: - int age; float height; char gender;

NOTE: - Variables are separated by commas. A declaration statement must end with a semicolon ( ; ).

Initialization of Variables: - Initialization Variables nothing but assigning a value to the variable. This
can be done in two ways.
 By using the assignment statements.
 By using read statements.

1. By using the assignment statement: - Initialization a variable at the time of variable declaration.

Syntax: - <Data type> <Variable Name> = <Initial Value>.

Example: - int age = 25;


Float height = 5.7;
Char gender = M;

NOTE: - We can also assign value to multiple variables at a time.

Syntax: - VariableName = VariableName = Value.

Example: - a = b = c = d = 20.

2. By using Read Statement: - We can also initialize the variables interactively keyboard using through
using the “readLine () or scanner ()” methods.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 37 II.B.Sc., III Sem Java
// Write a Java Prpgram to determine the Sum of the following Harmonic Series for a given
value of „n‟? Harmonic Series: 1+1/2+1/3+1/4……….+1/n.

import java.util.Scanner;
class HormonicSeries
{
public static void main(String args[])
{
int i,n;
double sum=0,r;
Scanner in=new Scanner(System.in);
System.out.println("enter range");

n=in.nextInt();
for(i=1;i<=n;i++)
{
r=(float)1/i;
sum=sum+r;
}
System.out.print("sum of Harmonic series up to "+n+" is ="+sum);
}
}

Save: - HormonicSeries.java
Compile: - javac HormonicSeries.java
Run: - java HormonicSeries

Output: - D:\Fareed Javaprog> java HormonicSeries

Enter Range: 10

Sum of HormonicSeries up to 10 is = 2.9289682805538177.

Scope of a Variable: -The area of the program where the variable is accessible is called “Scope of the
Variable”. The Scope of a Variable defines the life span of that variable. A variable may have any one of the
scope like Block Scope, Method Scope (Local Scope) and Class Scope (Global Scope).

Java Variables are classified into the following types:

1. Instance Variables.
2. Class Variables (or) Global Variables.
3. Method Variables (or) Local Variables.

1. Instance Variables: - “Instance Variables are the variables that are declared inside the class”.
These variables are created when the objects are instantiated and associated with the objects. They
take different values for each object.

2. Class Variables (or) Global Variables: - Class Variables that are declared inside the class as
„Static‟ variables. These variables are Global to entire class thus they are common to entire set of
objects created for that class.

3. Local Variables (or) Method Variables: - Local Variables are the variables that are declared and
used inside the Methods of a Class. These variables are not accessible outside the class in which
they are declared. Local variables can be declared inside the block will be accessible only that block

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 38 II.B.Sc., III Sem Java
Example: -

public class MotorCycle


{
static String Mfr_Name; // Class (or) Global Variable.
int weight;
float mileage; // Instance Variables.
int no_of_gears;
public static void main(String args[])
{
MotorCycle Herohonda=new MotorCycle();
{
MotorCycle.Mfr_Name= "Splendor";
Herohonda.weight=120;
Herohonda.mileage=70.5f;
Herohonda.no_of_gears=4;
Herohonda.displayValues();
}
public void displayValues()
int ccvalue=120; // Local Variable
System.out.println(Mfr_Name);
System.out.println(ccvalue);
System.out.println(weight);
System.out.println(mileage);
System.out.println(no_of_gears);
}
}

(Q). Define Data Type? What are the data types supported by Java Language?

Data type specifies the size and type of values that can be stored. Java Language is rich in its data
types. The variety of data types available allows the programmer to select the type appropriate to the
needs of the application. Conceptually, there are two types of data in Java: Primitive and Reference Type.

1. Primitive Data Type (or) Built-In Data Type.


2. Reference Data Type (or) User-defined Data Type (or) Non-Primitive Data Type.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 39 II.B.Sc., III Sem Java
 Primitive Data type: - These Primitive Data type directly operates on machines.
 Non-Primitive Data type: - These Non-Primitive data type not directly operates on machines.

(I). Number Data type: -


The Number Data Type can allow only numerical values either positive or negative values.
Numeric Data types fall under two categories namely: Integer Type and Floating Point Type.

 Integer Data type.


 Floating Point Data type.

1. Integer Type: - Integer Data Type is used to declared variables to hold whole numbers. These
numbers should be either positive or negative values. Java can support four types of Integer declaration
such as Byte, Short, Int, Long. The following table shows the memory size, range and default value of all
the Integer Data Types.

Data Type Size Range Value


Byte 1 Byte (or) 8 Bits - 128 to +128 0
Short 2 Byte (or) 16 Bits - 32,768 to + 32,767 (or) - 215 to + 215 - 1 0
Int 4 Byte (or) 32 Bits - 2,147,483,648 to + 2,147,483,647 (or) – 231 to + 231 - 1 0
Long 8 Byte (or) 64 Bits - 9,223,372,036,854,775,808 to + 9,223,372,036,854,775,807 0L
(or) – 263 to + 263 - 1

The Byte Data Type is used to store values up to 1 Byte. The Short Data Type can store values up
to 2 Bytes. While the Integer Data Type can store values up to 4 Bytes. The Long Data Type is used for
assigning values to variables, which are beyond the range of Integer Data Type.

2. Floating-Point Type: - Floating-Point type are used to declared variable to constitute numbers which
have a with decimal parts or real numbers that is numbers containing Fractional Part. Java can support two
types of Floating-Point type declaration such as Float and Double. The following table shows the memory
size, range and default value of all the Floating-Point Types.

Data Type Size Range Value


Float 4 Byte (or)32 Bits 3.4E-038 to 3.4E+038 0.0f
Double 8 Byte (or) 64 Bits 1.7E-308 to 1.7E+308 0.0d

(II). Non-Numeric Type: - The Second Type of Primitive Data Type is the Non-Numeric type. These are
classified into two groups.

 Char Data Type.


 Boolean Data Type.

1. Char Type: - Character Type is used to represent single character values. The data type „char‟ declares
a variable of type char, it can hold a character constant. It occupies 2 Bytes of memory. Java uses Unicode
to represent characters instead of ASCII.

Data Type Size Range Value


Char 2 Byte (or)16 Bits 0 to 65535 Characters „ \u0000‟

2. Boolean Type: - Boolean Type is used to represent „True or False‟ values. The data type Boolean
declares a variable of type Boolean, it can hold either „True or False‟. In Java, every conditional expression
returns a Boolean Value.

Data Type Size Range Value


Boolean 1 Byte (or)8 Bits True or False False

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 40 II.B.Sc., III Sem Java
Reference Data Type (or) User-defined Data Type (or) Non-Primitive Data Type: -

The user as created these data types and when demanded by the programming situation creates
these data types. These may be Arrays or Interfaces or Classes. The rules for declaring these data type are
similar to those in C++ language.

(Q). Explain about Type Casting?

The Process of Converting One data type to another is called as Typecasting”. During programming
we may have to convert values of one data type to another. For example, we may need to convert int or
float values to char type. Such conversion is necessary when these are a need to store the values of a
variable of one type into a variable of another type.

The general form of the statement for typecasting a variable is as follows.

Syntax: - Type Variable 1 = (Type) Variable 2

Typecasting is done by putting the data type to which conversion is to be made in parentheses and
placing it before the value to be converted and stored.

Example: - For Example, to typecasting the value of Int data type into Byte data type, the following
statements are written:
1. Int i= 786;
2. byte j= (byte) i;

Typecasting can be divided into two groups: -

1. Narrowing Casting.
2. Widening (or) Promotion Casting.

1. Narrowing Casting: - The Process of assigning a large type to a smaller one is known as Narrowing.

2. Widening Casting: - The process of assigning a smaller type to a lager one is known as Widening.

NOTE: - That Narrowing Casting may results is loss of information.

In the above example the size of Int data type is 4 bytes whereas that of byte data type is 1 byte.
In Line 2 above, a variable whose data type is large bytes has been accommodated into another variable
whose data type is of smaller bytes.

Therefore, Narrowing is not always safe as it may result in the loss of data. Moreover, the compiler
would not notify the loss of data to the users by means of any error message at all. The solution of the
problem lies with a phenomenon referred to as Widening. In sharp contract with Narrowing, Widening
refers to the Typecasting of a variable of data type of smaller size into another type of larger size.

Typecasting as Possible for Narrowing to Widening: -

Narrowing Possible Into Widening


Byte (8-Bits) Short (16-Bits), Char (16-Bits), Int (32-Bits), Float (32-Bits), Long (64-Bits) and
Double (64-Bits)
Short (16-Bits) Int (32-Bits), Float (32-Bits), Long (64-Bits) and Double (64-Bits)
Char (16-Bits) Int (32-Bits), Float (32-Bits), Long (64-Bits) and Double (64-Bits)
Int (32-Bits) Float (32-Bits), Long (64-Bits) and Double (64-Bits)
Long (64-Bits) Float (32-Bits) and Double (64-Bits)
Float Double (64-Bits)

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 41 II.B.Sc., III Sem Java
/* Example Program for Typecasting */

class Tcs
{
public static void main(String args[])
{
double d1,d2,d=23456;
short s1,s2,s=56;
long l1,l2,l=198765;
d1=(double)s;
d2=(double)l;
s1=(short)d;
s2=(short)l;
l1=(long)d;
l2=(long)s;
System.out.println("The Value of d1 = " +d1);
System.out.println("The Value of d2 = " +d2+"\n");
System.out.println("The Value of s1 = " +s1);
System.out.println("The Value of s2 = " +s2+"\n");
System.out.println("The Value of l1 = " +l1);
System.out.println("The Value of l2 = " +l2+"\n");
}
}

Save: - Tcs.java
Compile: - D:\Fareed Javaprog> Javac Tcs.java
Run: - D:\Fareed Javaprog> java Tcs

Output: -
The Value of d1 = 56.0
The Value of d2 = 198765.0

The Value of s1 = 23456


The Value of s2 = 2157

The Value of l1 = 23456


The Value of l2 = 56

(Q). Difference Between “Print () Method and Println () Method”? (or) Get Values of Variables?

Java supports two types of output methods that can used to send the results to the screen.

 Print () Method. // Print and Wait.


 Println () Method. // Print a Line and move for the Next Line.

1. Print () Method: - The Print () Method sends information into a buffer. This buffer is not flushed until a
new line character is sent. As a result, the Print () Method Print output on one line until a new line
character is encountered.

Example: - System.out.print(“Hello !!”);


System.out.print(Shaik Mohammad Fareed”);

Will display the words like Hello !! Shaik Mohammad Fareed On one line and waits for displaying
further information on the same line.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 42 II.B.Sc., III Sem Java
For Example, the statements are like to separate the words into a two line as following.

System.out.print(“Hello !!”);
System.out.print(“\n”); // Generate New Line
System.out.print(“Shaik Mohammad Fareed”);

Will display the Output in two lines as follows: -

Hello !!
Shaik Mohammad Fareed

(2). Println () Method: - The Println() Method, by contrast, takes the information provided and displays it
on a line followed by a line feed. This means that the statements.

System.out.println(“Hello !!”);
System.out.println(“Shaik Mohammad Fareed”);

Output: - Hello !!
Shaik Mohammad Fareed

NOTE: - The Statement System.out.println(); will print a blank line.

// Example Program: -

class View
{
public static void main(String args[])
{
System.out.println("The Following Result is");
for(int i=1;i<=9;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(" ");
System.out.print(i);
}
System.out.print("\n");
}
System.out.println("Results is Done");
}
}
Save: - View.java
Compile: - D:\Fareed Javaprog> javac View.java
Run: - D:\ Fareed Javaprog> java View

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 43 II.B.Sc., III Sem Java
Chapter – 4
Operators and Expressions.

(Q). what is Operators? Explain various types of Operators available in Java?

“An Operator is a symbol that tells the computer to perform certain mathematical or logical
manipulation or action”. Operators operate on Operand. Operand may be either variable or data. Operators
are used to manipulate the program‟s data. Java operators can be classified into several numbers of
categories as below:

1. Arithmetic Operator ( +, -, *, /)
2. Relational (or) Comparison Operator (==, !=, <, >, <=, >=).
3. Logical Operator (or) Compound (Logical And &&, Logical OR ||, Logical NOT !).
4. Assignment Operator ( = ).
5. Incremental / Detrimental Operator ( ++, -- ).
6. Bitwise Operator (Bitwise And &, Bitwise OR |, Bitwise XOR ^, Left shift <<, Right shift >> etc.)
7. Special Operator. (Dot .)
8. Conditional Operator ( ? ).

(I). Arithmetic Operator: -

Arithmetic Operator are use to construct mathematical expressions as in algebra. Using these
Operators, the programmer can build the statements to be performed arithmetic operations like Addition,
Subtraction, Multiplication, Division and Modulo Division.

Operator Meaning Example


+ Addition (or) Unary Plus 3+4
- Subtraction (or) Unary Minus 5–3
* Multiplication 5*5
/ Division 10 / 2
% Modulo Division 20 % 7

Arithmetic operators are used as shown below:

a+b a–b a*b a/b a % b.

Here „a‟ and „b‟ may be variables or constants and are known as operands. Depending on the data types of
the operands these operators perform either Integer (or) Floating (or) Mixed Mode arithmetic operations.

1. Integer Arithmetic Operations.


2. Floating (or) Real Arithmetic Operations.
3. Mixed Mode Arithmetic Operations.

1. Integer Arithmetic Operations: - When both the operands is integers, the expression is called as
Integer Expression. The Integer arithmetic always yields an “Integer Values”.

Rule: - Here two operands „a‟ and „b‟ are defined as integers, result is in integer.

Example: - int a =15 and b=6

Operator Notation Value Result


Addition a+b 15 + 6 21
Subtraction a-b 15 – 6 9
Multiplication a*b 15 * 6 90
Division a/b 15 / 6 2 (Decimal part truncated)
Modulo Division a%b 15 % 6 3 (Remainder of Integer division)

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 44 II.B.Sc., III Sem Java
2. Floating (or) Real Arithmetic Operations: - An Arithmetic involving only real operands is called as
Real Arithmetic. A real operand may assume values either in a Decimal or Exponential notations.

Rule: - Here two operands „a‟ and „b‟ are defined as real, result is in float values.

Example: - Float a =15.2 and b=6.4

Operator Notation Value Result


Addition a+b 15.2 + 6.4 21.6
Subtraction a-b 15.2 – 6.4 8.8
Multiplication a*b 15.2 * 6.4 97.28
Division a/b 15.2 / 6.4 2.375
Modulo Division a%b 15.2 % 6.4 3.4568

3. Mixed Mode Arithmetic Operations: - Here when one of the operands is real and the other is integer
that expression called as “Mixed Mode Arithmetic”.

Rule: - Here one of the Operand is real and other operand is integer. Result is in float value.

Example: - Float a =15.2 and int b=6

Operator Notation Value Result


Addition a+b 15.2 + 6 21.2
Subtraction a-b 15.2 – 6 9.2
Multiplication a*b 15.2 * 6 91.2
Division a/b 15.2 / 6 2.5333
Modulo Division a%b 15.2 % 6 3.2356

NOTE: - In Integer Division for Modulo Division, the sign of the result is always the sign of the first
operand (the dividend).

Example: - -14 % 3 = - 2
-14 % -3 = -2
14 % -3 = 2

// Example Program for Arithmetic Operators?

class ArithmeticTest
{
public static void main(String args[])
{
short x=6;
int y=4;
float a = 12.5f;
float b=7f;
System.out.println("X is: " + x + ",Y is: " +y);
System.out.println(" X + Y = " + (x+y));
System.out.println(" X - Y = " + (x-y));
System.out.println(" X * Y = " + (x*y));
System.out.println(" X / Y = " + (x/y));
System.out.println(" X % Y = " + (x%y));
System.out.println("a is :" + a + ",b is :" + b);
System.out.println(" a / b = " +(a/b));
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 45 II.B.Sc., III Sem Java
Save: - ArithmeticTest.java
Compile: - D:\Fareed Javaprog> javac ArithmeticTest.java
Run: - D:\Fareed Javaprog> java ArithmeticTest

Output: - X is: 6, Y is: 4


X + Y = 10
X–Y=2
X * Y = 24
X/Y= 1
X%Y=2
a is: 12.5, b is: 7.0
a / b = 1.7857143

(II). Relational Operators (or) Comparison Operators: -

Relational Operators are used for comparison, when we need to compare two quantities with one
another. Java has several expressions for testing equality and magnitude. All of these expressions return a
Boolean value (That is True or False). All these relational operators compare the left operand with the right
operand and return the result. Java supports six relational operators in all. These operators and their
meanings are shown in below table.

Operator Meaning
< Is less than
<= Is Less than or equal
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal

A simple relational expression contains only one relational operator and is of the following form.

Arithmetic Expression 1 Relational Operator Arithmetic Expression 2

Arithmetic Expression 1 and Arithmetic Expression 2, which may be simple constants, variables or
combination of them. Below table shows some examples of simple relational expressions and their values.

Operator Meanings
4.5 < = 10 True
4.5 < - 10 False
-35 > = 0 False
10 < 7 + 5 True
When Arithmetic Expression is used on either side of a relational operator, the Arithmetic Expression
will be evaluated first and then the results compared. That is arithmetic operators have a higher priority
over relational operators.

// Implementation of Relational Operators?

class RelationalOperators
{
public static void main(String args[])
{
float a=16.0f, b=12.75f,c=15.0f;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("a < b is: " + (a<b));
Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 46 II.B.Sc., III Sem Java
System.out.println("a > b is: " + (a>b));
System.out.println("a == c is: " + (a==c));
System.out.println("a <= c is: " + (a<=c));
System.out.println("a >= b is: " + (a>=b));
System.out.println("b ! = c is: " + (b!=c));
System.out.println("b == a + c is: " + (b==a+c));
}
}

Save: - RelationalOperators.java
Compile: - D:\Fareed Javaprog> javac RelationalOperators.java
Run: - D:\Fareed Javaprog> java RelationalOperators

Output: -
a = 16.0
b = 12.75
c=15.0
a < b is : False
a > b is : True
a == c is: False
a < = c is: False
a > = b is : True
b ! = c is: True
b == a + c is: False

(III). Logical Operators: -

Logical Operators are used to form compound conditions by combining two or more relations. The
expression which is formed as combining of two or more relational expressions is called as Logical
Expression or Compound Relational Expression. In Java all Logical Operators returns Boolean Values that is
either True or False as results. Java has three logical operators, which are given in below table.

 Logical AND (&&) Operator Meanings


 Logical OR (||) && Logical AND
 Logical NOT (!) || Logical OR
! Logical OR

1. Logical AND (&&): - This operator return “True”, if both the operands are evaluated to “True”,
otherwise it returns “False”. Observe following Logical AND (&&) Truth Table.

Expression 1 Expression 2 Exp 1 && Exp 2


True True True
True False False
False True False
False False False

2. Logical OR (||): - This operator return “False”, if both the operands are evaluated to “False”, otherwise
it returns “True”. Observe following Logical OR (||) Truth Table.

Expression 1 Expression 2 Exp 1 || Exp 2


True True True
True False True
False True True
False False False

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 47 II.B.Sc., III Sem Java
3. Logical NOT (!): - This operator is used to negate a value of type Boolean. If converts a True value into
False and False value into True. Observe following Logical NOT (!) Truth table.

Expression Result
True False
False True
(IV) Assignment Operators: -

Assignment Operators are used to assign the value of an expression to a variable or constant. The
Operator „=” is used as Assignment Operator in Java. The right side of an assignment expression is always
evaluated before the assignment takes place. This means that expressions such as x = x+2 do the right
thing; 2 is added to the value of x, and then that new value is reassignment to x.

The usual assignment operator „=‟. In additional Java has a set of „Shorthand‟ assignment operators
which are used in the form.
V op = exp;

Where „V‟ is a Variable, „exp‟ is an expression and „op‟ is a Java binary operator. The operator „op=‟ is
known as the Shorthand assignment operator.

The assignment statement “ V op = exp” is equal to “ V = V op (exp);

Example: - x + = y + 1 this is same as the statement as x = x + (y+1).

Some of the Shorthand Assignment Operators: -

Expression Meaning
x+=y x= x + y
x-=y x=x–y
x*=y x=x*y
x/=y x=x/y
x*=y+1 x = x * (y + 1)
x/=y+1 x = x / (y + 1)
x%=y x=x%y

The use of Shorthand Assignment operators has three advantages.

1. What appears on the left-hand side need not be repeated and therefore it becomes „easier to write‟.
2. The Statement is more concise and „easier to read‟.
3. Use of Shorthand operator results in a more efficient code.

(V). Incremental and Detrimental Operators: -

Java supports two operators Increment and Decrement Operators. Which are used to increase or
decrease the values of variables by one. The Operator ++ adds 1 to the operand, while – subtracts 1. Both
these two operators take only one operand, so they are called as Unary Operators.

Operator Meaning
++ Increment Operator
-- Decrement Operator

(1). Increment Operator: - The Increment Operator ++ symbol or notation is used for Incrementing by
one. ++i or i++ is equal to i=i+1 or i+=1. There are two types of Increments

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 48 II.B.Sc., III Sem Java
 Prefix Increment (++i)
 Postfix Increment (i++)

Prefix Increment (++i ): - In the Prefix Increment first it is increment and then the result is assigned.
Example of Prefix increment: - x = 5, y = ++(x-2)
y = ++(x-2)  y = ++5 – 2  y = 6 -2  y = 4. Result of Pre Increment = 4.
Here Prefix operator first adds 1 to the operand and then the result is assigned to the variable on the left.
Postfix Increment (i++): -In Postfix first assigns the value to the variable on left and then increments.
Example of Prefix increment: - x = 5, y = (x-2)++
y = (x-2)++  y = 5 – 2 ++  y = 3 ++  y = 4. Result of Post Increment: = 4.
Here Postfix operator first assigns the value to the variable on left and then increments the operand.
NOTE: - However the result of the increment value will be the same in Prefix and Postfix cases.

(2). Decrement Operator: - The Decrement Operator - - symbol or notation is used for Decrementing by
one. - -i or i- - is equal to i=i-1 or i-=1. There are two types of Decrements

 Prefix Decrement (- - i)
 Postfix Decrement (i- -)

Prefix Decrement (- -i ): - In the Prefix Decrement first it is Decrement and then the result is assigned.
Example of Prefix Decrement: - x = 5, y = - -(x-2)
y = - -(x-2)  y = - - 5 – 2  y = 4 -2  y = 2. Result of Pre Decrement: = 2.
Prefix operator first decrees 1 to the operand and then the result is assigned to the variable on the left.
Postfix Decrement (i--): -In Postfix first assigns the value to the variable on left and then Decrement.
Example of Prefix Decrement: - x = 5, y = (x-2) - -
y = (x-2) - -  y = 5 – 2 - -  y = 3 - -  y = 2. Result of Post Decrement: = 2.
Here Postfix operator first assigns the value to the variable on left and then Decrement the operand.
NOTE: - However the result of the Decrement value will be the same in Prefix and Postfix cases.

// Illustrate Incremental and Detrimental Operators?

lass IncDec
{
public static void main(String args[])
{
int i=10;
int j=10;
System.out.println("Before Postfix i = "+i);
System.out.println("Before Postfix j = "+j);
i++;
j++;
System.out.println("After Postfix Increment i = "+i);
System.out.println("After Postfix Increment j = "+j);
int k=i++;
int l=++j;
System.out.println("K is = "+k);
System.out.println("L is = "+l);
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 49 II.B.Sc., III Sem Java
Save: - IncDec.java
Compile: - D:\Fareed Javaprog> javac IncDec.java
Run: - D:\Fareed Javaprog> java IncDec

Output: -

Before Postfix I = 10
Before Postfix j = 10
After Postfix Increment i = 11
After Postfix Increment j = 11
K is = 11
L is = 12

(VI). Bitwise Operator: -


Bitwise operators are used for manipulation of data values at bit level. These operators act
upon individual bits of a number. These operates are used for testing the bits, or shifting them to the right
to left. Bitwise operators compare two variables bit by bit and return a variable whose bits have been
modified. Bitwise operators may not be applied to Float or Double. Below table listed the Bitwise operator.

Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR (or) XOR
~ One‟s Complement
<< Left Shift
>> Right Shift
>>> Zero Fill Right Shift

Operator 1 Operator 2 Op 1 & Op2 Op 1 | Op 2 Op 1 ^ Op 2 ~ Operator 1 ~ Operator 2


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

(1). Bitwise AND (&): - The Bitwise AND operator is represented by a single ampersand (&) and is
surrounded on both sides by integer expressions. “The resulting of AND (&) operator is „1‟ if both the bits
have a value of „1‟, otherwise it is „0‟.”

Example: - Let‟s consider two variables „A‟ and „B‟ whose values are „13‟ and „25‟. The Binary
representation of these two variables we find “C = A & B”.

A 0000 0000 0000 1101  Binary Value of 13.


B 0000 0000 0001 1001  Binary Value of 25.

C = A & B  0000 0000 0000 1001  Binary Value of 09.

(2). Bitwise OR (|): - The Bitwise OR operator is represented by the symbol of vertical bar (|) and is
surrounded by two integer operands. “The resulting of OR (|) operator is „1‟ if at least one of the bits has a
value of „1‟, otherwise it is „0‟.”

Example: - Let‟s consider two variables „A‟ and „B‟ whose values are „13‟ and „25‟. The Binary
representation of these two variables we find “C = A | B”.

A 0000 0000 0000 1101  Binary Value of 13.


B 0000 0000 0001 1001  Binary Value of 25.

C=A|B 0000 0000 0001 1101  Binary Value of 29.


Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 50 II.B.Sc., III Sem Java
(3). Bitwise Exclusive OR (^): - The Bitwise Exclusive OR operator is represented by the symbol of (^)
and is surrounded by two integer operands. “The resulting of Exclusive OR (^) operator is „1‟ if Only one of
the bits has a value of „1‟, otherwise it is „0‟.”

Example: - Let‟s consider two variables „A‟ and „B‟ whose values are „13‟ and „25‟. The Binary
representation of these two variables we find “C = A ^ B”.

A 0000 0000 0000 1101  Binary Value of 13.


B 0000 0000 0001 1001  Binary Value of 25.

C = A ^ B  0000 0000 0001 0100  Binary Value of 20.

// Implement the Bitwise AND (&), OR (|), Exclusive OR (^) Operators?


class BitWises
{
public static void main(String args[])
{
int a =13, b =25;
System.out.println("A = " + a);
System.out.println("B = " + b);
System.out.println("A & B = " + (a&b));
System.out.println("A | B = " + (a|b));
System.out.println("A ^ B = " + (a^b));
}
}
Save: - BitWises.java
Compile: - D:\Fareed Javaprog> javac BitWises.java
Run : - D:\Fareed Javaprog> java BitWises
Output: - A = 13
B = 25
A & B = 09
A | B = 29
A ^ B = 20.

(4). Bitwise Complement: - The compliment operator causes the Bit of its open and to be invented.
Therefore one (1) becomes zero (0) and zero (0) becomes one (1).

Example: - A = 0000 0000 0011 1100


Bit Complement ~A = 1111 1111 1100 0011.

The Bit Complement is unary operator because it operators only in one operand.

(5). Bitwise Left Shift: - Shift one bit in the Left side and add zero‟s in the Right side.

Example: - Suppose A = 0000 0000 0000 1101


A<<0 = 0000 0000 0000 1101
A<<1 = 000 0000 0000 11010
A<<2 = 00 0000 0000 110100
A<<3 = 0 0000 0000 1101000

(6). Bitwise Right Shift: - Shift one bit in the Right side and add zero‟s in the Left side.

Example: - Suppose A = 0000 0000 0000 1101


A>>0 = 0000 0000 0000 1101
A>>1 = 00000 0000 0000 110
A>>2 = 000000 0000 0000 11
A>>3 = 0000000 0000 0000 1

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 51 II.B.Sc., III Sem Java
(7). Shift Right With Zero Fill (>>>): - Operator >>> provide by Java insert zero at the top end.

// Illustrate Implement the All Bitwise Operators?

class BitWises
{
public static void main(String args[])
{
int a =13, b =25;
System.out.println ("A = " + a);
System.out.println("B = " + b);
System.out.println("Bitwise AND (&) Operators");
System.out.println("--------------------------------------------");
System.out.println("A & B = " + (a&b));
System.out.println("Bitwise OR (|) Operators");
System.out.println("--------------------------------------------");
System.out.println("A | B = " + (a|b));
System.out.println("Bitwise Exclusive OR (^) Operators");
System.out.println("--------------------------------------------");
System.out.println("A ^ B = " + (a^b));
System.out.println("Bitwise Complement (~) Operators");
System.out.println("--------------------------------------------");
System.out.println(" ~ A = " + (~a));
System.out.println(" ~ B = " + (~b));
System.out.println("Bitwise Left Shift (<<) Operators");
System.out.println("--------------------------------------------");
System.out.println(" A << (LeftShif by 0) = " + (a<<0));
System.out.println(" A << (LeftShif by 1) = " + (a<<1));
System.out.println(" A << (LeftShif by 2) = " + (a<<2));
System.out.println(" A << (LeftShif by 3) = " + (a<<3));
System.out.println(" B << (LeftShif by 0) = " + (b<<0));
System.out.println(" B << (LeftShif by 1) = " + (b<<1));
System.out.println(" B << (LeftShif by 2) = " + (b<<2));
System.out.println(" B << (LeftShif by 3) = " + (b<<3));
System.out.println("Bitwise Right Shift (>>) Operators");
System.out.println("--------------------------------------------");
System.out.println(" A >> (RightShif by 0) = " + (a>>0));
System.out.println(" A >> (RightShif by 1) = " + (a>>1));
System.out.println(" A >> (RightShif by 2) = " + (a>>2));
System.out.println(" A >> (RightShif by 3) = " + (a>>3));
System.out.println(" B >> (RightShif by 0) = " + (b>>0));
System.out.println(" B >> (RightShif by 1) = " + (b>>1));
System.out.println(" B >> (RightShif by 2) = " + (b>>2));
System.out.println(" B >> (RightShif by 3) = " + (b>>3));

}
}

Save: - BitWises.java
Compile: - D:\Fareed Javaprog> javac BitWises.java
Run: - D:\Fareed Javaprog> java BitWises

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 52 II.B.Sc., III Sem Java
Output: -
A = 13
B = 25
Bitwise AND (&) Operators
--------------------------------------
A & B= 9
Bitwise OR (|) Operators
-------------------------------------
A | B = 29
Bitwise Exclusive OR (^) Operators
--------------------------------------
A ^ B = 20
Bitwise Complement (~) Operators
--------------------------------------
~ A = -14
~ B = -26
Bitwise Left Shift (<<) Operators
--------------------------------------
A << (LeftShif by 0) = 13
A << (LeftShif by 1) = 26
A << (LeftShif by 2) = 52
A << (LeftShif by 3) = 104
B << (LeftShif by 0) = 25
B << (LeftShif by 1) = 50
B << (LeftShif by 2) = 100
B << (LeftShif by 3) = 200
Bitwise Right Shift (>>) Operators
--------------------------------------------
A >> (RightShif by 0) = 13
A >> (RightShif by 1) = 6
A >> (RightShif by 2) = 3
A >> (RightShif by 3) = 1
B >> (RightShif by 0) = 25
B >> (RightShif by 1) = 12
B >> (RightShif by 2) = 6
B >> (RightShif by 3) = 3

(VII). Special Operator: - Java supports some special operators of interest such as “Instanceof” and
“Member Selection (or) Dot (.) Operators.

1. Instanceof Operator.
2. Member Selection (or) Dot (.) Operator.

1. Instanceof Operator: - The Instancof is an object reference operator and returns True, if the object on
the left hand side is an instance of the class given on the right hand side. This operator helps the
programmer to determine whether the object belongs to a particular class or not.

Syntax: - <Object Reference> Instanceof <Class Name>

Example: - Person Instanceof Student

Is True if the object Person belongs to the class Student; otherwise it is false.

2. Member Selection (or) Dot (.) Operator: - The Dot (.) Operator is used to access the instance
Variables and Methods of the Class.

Example: - Person.age // Reference to the Variable age.


Person.Salary() // Reference to the Method Salary().

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 53 II.B.Sc., III Sem Java
(VIII). Conditional Operator: - Conditional operator is one of the special operators supported by Java
which can be used as an alternative to “If…Else ladder”. Since it acts upon three operands, it is called as
Ternary operator. This operator is used to construct conditional expressions of the form.

Syntax: - Exp 1 ? Exp 2 : Exp 3

Here Exp 1, Exp 2 and Exp 3 is Expressions. And ? : is Operators.

 Exp 1 is evaluated First, If is True (nonzero), then the Expression Exp 2 is evaluated returned.
 If Exp 1 is False, Exp 3 is evaluated returned.

// Illustrate The Conditional Operator Program?

class Exps
{
public static void main(String args[])
{
int a =13, b =25;
int big = a>b?a:b;
System.out.println("Biggest Value is : " +big);
}
}
Save: - Exps.java
Compile: - D:\Fareed Javaprog>javac Exps.java
Run: - D:\Fareed Javaprog>java Exps

Output: - Biggest Value is : 25.

(Q). What is Arithmetic Expression? How the Arithmetic Expressions are evaluated with the help
of Arithmetic Operators Precedence?

An Arithmetic Expression is a combination of variables, constants and operators as per syntax. Each
arithmetic expression contains two or more variables or constants where each pair is connected with an
arithmetic operator.

Java can handle any complex mathematical expressions. Remember that Java does not have an
operator for exponentiation.

Java Expressions: -
Algebraic Expression Java Expression
ab – c (a * b) – c
(m+n) (x+y) (m+n)*(x+y)
ab / c (a*b) / c
3x2+2x+1 3*x*x+2*x+1
x/y + c (x / Y) + c

Evaluation of Expressions: - Expressions are evaluated using an assignment statement of the form.

Variable = Expression;

Variable is any valid Java variable name. When the statement is encountered, the expression is
evaluated first and the result is assigned to the variable or constant which is placed as left-hand side
operand to the assignment statement.

Example: - int a = 5, b = 10;


Int sum = a+b
Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 54 II.B.Sc., III Sem Java
Here the arithmetic expression „a+b‟ is evaluated first and then the value of „Sum‟ is assigned to the
sum of the values of two variables „a‟ and „b‟.

Precedence of Arithmetic Operator: - Each arithmetic operator has its own priority in evaluation the
expression. 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.

Levels Priority Operators Meaning


1 () Parentheses
High 2 / Division
Level 3 * Multiplication
4 % Modulo Division
Low 5 + Plus
Level 6 - Minus

The basic evaluation procedure includes to left-to-right passes through the expressions. While
evaluation the expression, the operators which has High Priority (if any) will be evaluated First. Then the
operators which have Low Priority (if any) will be evaluated.

Example: - Consider the following evaluation statement.

Expression x=a–b/3+c*2–1

Where a = 9, b = 12 and c = 3 the statement becomes

X = 9 – 12 / 3 + 3 * 2 – 1 and is evaluated as following

Evaluation Process of Arithmetic Expressions: - Each arithmetic expression is evaluated in two passes
that works from left-to –right.

1. During the First pass, the terms which have High Priority Operators will be evaluated.
2. During the Second pass, the terms which have Low Priority Operators will be evaluated.

Consider the following evaluation statement.

Expression x=a–b/3+c*2–1

Where a = 9, b = 12 and c = 3 the statement becomes

x = 9 – 12 / 3 + 3 * 2 – 1 and is evaluated as following

First Pass: -
Step 1: x = 9 – 4 + 3 * 2 – 1 (12 / 3 Evaluated)
Step 2: x = 9 – 4 + 6 – 1 (3 * 2 Evaluated)
Second Pass: -
Step 3: x = 5 + 6 – 1 (9 – 4 Evaluated)
Step 4: x = 11 – 1 (5 + 6 Evaluated)
Step 5: x = 10 (11 – 1 Evaluated)

Then the result 10 will be assigned to the variable „x‟ such as “ x = 10”.

However, introducing parentheses into an expression can change the order of evaluation.
Consider the same expression with parentheses as shown below.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 55 II.B.Sc., III Sem Java
Expression x = a – b / (3 + c) *( 2 – 1)

Where a = 9, b = 12 and c = 3 the statement becomes

x = 9 – 12 / (3 + 3) * (2 – 1) and is evaluated as following

 Whenever the parentheses are used, the expressions within parentheses assume Highest Priority.
 If two or more sets of parentheses appear one after another as shown above, the expression
contained in the left-most set is evaluated first and the right-most in the last.

Expression x = a – b / (3 + c) *( 2 – 1)

Where a = 9, b = 12 and c = 3 the statement becomes

x = 9 – 12 / (3 + 3) * (2 – 1) and is evaluated as following


First Pass: -
Step 1: x = 9 – 12 / 6 * (2 – 1) (3 + 3 Evaluated)
Step 2: x = 9 – 12 / 6 * 1 (2 - 1 Evaluated)
Step 3: x = 9 – 2 * 1 (12 / 6 Evaluated)
Step 4: x = 9 – 2 (2 * 1 Evaluated)
Second Pass: -
Step 5: x = 7 (9 – 2 Evaluated)

Parentheses may be nested, and in such cases, evaluation of the expression will proceed outward
from the innermost set of parentheses. Just make sure that every opening parenthesis has a matching
closing one.

For Example the Expression like x = 9 – (12 / (3 + 3 ) * 2 ) – 1  Result is : 4.


Similarly x = 9 - ( ( 12 / 3 ) + 3 * 2 ) – 1  Result is: -2.

(Q). Explain about Type Conversion in Expression?

Type Conversion referees to changing a value from one data type to another data type. Type
conversion is also called as Typecasting. Java supports two kinds of type casting in expressions.

1. Implicit Casting.
2. Explicit Casting.

1. Implicit Casting: - Automatic casting done by “Java Compiler Internally” is called Implicit Casting,
it is done to convert a „Lowe data type into a Higher data type‟.

2. Explicit Casting: - The Casting is “done by Programmer” is called as Explicit Casting. It is


compulsory while converting from a “Higher data type to lower data type”.

Syntax: - (Data Type) Variable / Expression;

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 56 II.B.Sc., III Sem Java
RHO Char Byte Short Int Long Float Double
LHO
Char Int Int Int Int Long Float Double
Byte Int Int Int Int Long Float Double
Short Int Int Int Int Long Float Double
Int Int Int Int Int Long Float Double
Long Long Long Long Long Long Float Double
Float Float Float Float Float Float Float Double
Double Double Double Double Double Double Double Double

NOTE: - RHO: - Right hand operand. LHO: - Left hand operand.

// Illustration of Use of with Casting Operation?

class WithCasting
{
public static void main(String args[])
{
float sum;
int i;
sum=0.0f;
System.out.println("With Casting Expression");
for(i=1;i<=10;i++)
{
sum=sum+1/(float)i; // Casting (Float) I
System.out.println("i = "+i);
System.out.println("Sum = "+sum);
}
}
}
Save: - WithCasting.java
Compile: - D:\Fareed Javaprog>javac WithCasting.java
Run: - D:\Fareed Javaprog>java WithCasting

Output: - With Casting Expression.

I = 1 Sum = 1
I = 2 Sum = 1.5
I = 3 Sum = 1.8333334
I = 4 Sum = 2.0833335
I = 5 Sum = 2.2833335
I = 6 Sum = 2.4500003
I = 7 Sum = 2.5928574
I = 8 Sum = 2.7178574
I = 9 Sum = 2.8289685
I = 10 Sum = 2.9289684

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 57 II.B.Sc., III Sem Java
// Illustration of Use of without Casting Operation?

class WithoutCastings
{
public static void main(String args[])
{
int sum;
int i;
sum=0;

System.out.println("Without Casting Expression");


for(i=1;i<=10;i++)
{
sum=sum+1/i; // Without Casting
System.out.println("i = "+i);
System.out.println("Sum = "+sum);
}
}
}
Save: - WithoutCastings.java
Compile: - D:\Fareed Javaprog>javac WithoutCastings.java
Run: - D:\Fareed Javaprog>java WithCastings

Output: - Without Casting Expression.

I = 1 Sum = 1
I = 2 Sum = 1
I = 3 Sum = 1
I = 4 Sum = 1
I = 5 Sum = 1
I = 6 Sum = 1
I = 7 Sum = 1
I = 8 Sum = 1
I = 9 Sum = 1
I = 10 Sum = 1

NOTE: - Casting can be used to round-off a given value to an Integer.

Variables Expression Action


X= (int) 7.5 7.5 is converted to Integer by Truncated.
X= (double) Sum/n Division is done in Floating point mode.
Y= (int) (a+b) The result of a+b is converted to Integer.
Z= (int) a+b „a‟ is converted to Integer and then add to „b‟
A= Cost((double)x) Converts „x‟ to double before using it as parameter.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 58 II.B.Sc., III Sem Java
(Q). Explain Operators Precedence and Associatively?

Each Operator in Java has a Precedence Associated with it. This Precedence is used to
determine how an expression involving more than one operator is evaluated. There are distinct levels of
precedence and an operator may belong to one of the levels. The operators at the Higher level of
Precedence are evaluated First.
The operators of the same Precedence are evaluated either from Left-to-Right or from Right-
to-Left, depending on the level. This is known as Associatively Property of operators. The following table
provides a complete listed in the order of decreasing Precedence.

Precedence Operators Descriptions Associatively


Ranks
1 . Member Selection Left-to-Right
2 () Function Call Non-Associative
3 [] Array Element Reference Non-Associative
4 -+!~ Unary Minus, Plus, Negation, Ones Complement Right-to-Left
5 ++, -- Incremental and Detrimental Non-Associative
6 */% Multiplication, Division, Modulo Division Left-to-Right
7 +- Addition and Subtraction Left-to-Right
8 << ,>>, >>> Left Shift, Right Shift and Right Shift with Zero Fill Left-to-Right
9 <, >, < =, > = Less than, Greater Than, Less than or equal to, Left-to-Right
Instanceof greater than or equal, Instanceof Type Comparison
10 == , != Equality and Inequality Left-to-Right
11 & Bitwise AND Left-to-Right
12 ^ Bitwise Exclusive OR (or) XOR Left-to-Right
13 | Bitwise OR Left-to-Right
14 && Logical AND Left-to-Right
15 || Logical OR Left-to-Right
16 ?: Conditional Operator Right-to-Left
17 = Assignment Operator Right-to-Left

Mathematical Functions: - Mathematical Functions such as: “Cos, Sqrt, Log, ..etc”. are frequently used
in analysis of real-life problems. Java supports these basic „Math Functions‟ through „Math Class‟ defined in
the “Java.lang.Package”. The Following table listed the „Math Functions‟ defined in the „Math Class‟.
Syntax: - Math.Function_Name();
Example: - Double Y = math.sqrt(x);
Functions Actions
Sin(x) Returns the Sine of the angle „x‟ in radians.
Cos(x) Returns the Cosine of the angle „x‟ in radians.
Tan(x) Returns the Tangent of the angle „x‟ in radians.
aSin (y) Returns the angle whose Sine is „Y‟.
aCos (y) Returns the angle whose Cosine is „Y‟.
aTan (y) Returns the angle whose Tangent is „Y‟.
aTan2(x,y) Returns the angle whose Tangent is „x/Y‟.
Pow(x,y) Returns the „x‟ raised to y (xy).
Exp(x) Returns the „e‟ raised to y (ey).
Log(x) Returns the natural Logarithm if „x‟.
Sqrt(x) Returns the square root of „x‟.
Ceil(x) Returns the smallest whole number greater than or equal to „x‟ (Rounded up).
Floor(x) Returns the largest whole number less than or equal to „x‟ (Rounded down).
rint(x) Returns the Truncated values of „x‟.
Abs(a) Returns the Absolute value of „a‟.
Max(a,b) and Min(a,b) Returns the Maximum and Minimum of „a‟ and „b‟.
NOTE: - „x‟ and „y‟ are double type parameters. And „a‟ and „b‟ mat be Ints, longs, Floats and doubles.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 59 II.B.Sc., III Sem Java
UNIT -II
Chapter 5: Decision Making & Branching.

(Q) Explain the Control Structures (or) Control Structures Statement (or) Decision Constructs
(Or) Decision Making and Branching Statement available in Java?

Introduction: -

Sequentially Execution: - “A Java Program is a set of statements, which are normally executed
sequentially” this type of execution is called as “Sequentially Execution”. The sequentially may be either
Top to Bottom or Bottom to Up.

Branching: - When a Program breaks the sequentially flow and jumping another part of the code, it is
called as “Branching”.

Conditional Branching: - When we are use the branching is based on a particular condition, it is known
as Conditional Branching.

Unconditional Branching: - If Branching take place without any decision, it is known as Unconditional
Branching.

Control / Decision Statements: - Java support several structures for constructing the statements to
control the flow of execution. These are called as Decision / Selection Statement. Java language possesses
such decision making capabilities and supports the following statements known as Control / Decision
Statements.

There are the following kinds of Decision Making or Control Structures available in Java.

(I). Decision / Selection Statements.


(II). Iteration / Looping Statements.
(III). Transfer / Jumping Statements.

1. Selection Statement: - Selection Statement also called as “Branching or Decision Statements”.


With the help of decision structures, we can select the statements to be executed depending upon
the specified condition.

2. Looping Statement: - Looping Statement also called as “Iteration Statements”. With the help of
iterative statements we can repeated the specific task as long as the specified condition.

3. Jumping Statement: - Jumping Statement also called as “Transfer Statement”. With the help of
transfer control one block or part of the program to another block or part of the program.

(I). Decision / Selection Statements: - Selection Statement also called as “Branching or Decision
Statements”. With the help of decision structures, we can select the statements to be executed depending
upon the specified condition. The following comes under these Statements like:

(A). If Statements.
(1). Simple If Statement.
(2). If…Else Statement.
(3). Nested If…Else Statement.
(4). If…Else…If Ladder.
(B). Switch Statement.
(C). Conditional Operator Statement.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 60 II.B.Sc., III Sem Java
(II). Looping Statement: - Looping Statement also called as “Iteration Statements”. With the help of
iterative statements we can repeated the specific task as long as the specified condition. The following
comes under these Statements like:

(A). While Looping.


(B). Do…While Looping.
(C). For Looping.

(III). Jumping Statement: - Jumping Statement also called as “Transfer Statement”. With the help of
transfer control one block or part of the program to another block or part of the program. The following
comes under these Statements like:

(A). Break Statement.


(B). Continue Statement.
(C). Return Statement.
Control Structure

Selection / Decision Statements Looping Statements Jumping Statements

If Statements. While Looping. Break Statement.


Simple If Statement.
Do…While Looping. Continue Statement.
If…Else Statement.
For Looping. Return Statement.
Nested If…Else Statement.

If…Else…If Ladder Statement.

Switch Statement.

Conditional Operator Statement.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 61 II.B.Sc., III Sem Java
(Q). Explain the various Decision Making Statements (or) Selection Statements available in Java?

Decision / Selection Statements: - Selection Statement also called as “Branching or Decision


Statements”. With the help of decision structures, we can select the statements to be executed depending
upon the specified condition. The following comes under these Statements like:

(A). If Statements.
(1). Simple If Statement.
(2). If…Else Statement.
(3). Nested If…Else Statement.
(4). If…Else…If Ladder.
(B). Switch Statement.
(C). Conditional Operator Statement.

(A). Decision Making With IF Statement: -

The If Statement is a powerful decision making statement and is used to control the flow of
execution of statement. It takes the following form:

Syntax: - If ( Expression / Condition)

In Java, If Statement can be used in different forms depending on the complexity of the conditions
to be tested. The following forms are

(1). Simple If Statement.


(2). If…Else Statement.
(3). Nested If…Else Statement.
(4). If…Else…If Ladder.
(1). Simple If Statement: - Simple If Statement is used to execute one set of statements based on the
results of a given test condition. If Condition is “True” then executed Only within If-Block statements only.
Otherwise skipped and the execution other statements.

Syntax of IF: - If (Expression / Condition) Statement;


(or)
If (Expression / Condition)
{
Statement (s);
} Entry

Flow Chart for Simple IF: -


Test True
Expression

Statement -Block
False

Statement -Block

Stop

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 62 II.B.Sc., III Sem Java
// Illustrate the If Statement, then Condition is True to Print the Result on Screen?

import java.lang.*;
class Ifeven
{
public static void main(String args[])
{
int n=15;
float s;
if(n>0)
{
s=n/10;
System.out.println("Condition is True: "+s);
}
}
}

Save: - Ifeven.java
Compile: - D:\Fareed Javaprog>javac Ifeven.java
Run: - D:\Fareed Javaprog>java Ifeven

Output: - Condition is True : 1.0

// Illustrate the If Statement, then Condition is False then Skip the Block of statement?

import java.lang.*;
class IfskipBlock
{
public static void main(String args[])
{
int n=-15;
float s;
if(n>0)
{
s=n/10;
System.out.println("Condition is True: "+s);
}
System.out.println("Hello Mohammad Fareed");
}
}

Save: - IfskipBlock.java
Compile: - D:\Fareed Javaprog> javac IfskipBlock.java
Run: - D:\Fareed Javaprog> java IfskipBlock

Output: - Hello Mohammad Fareed

NOTE: - Here Skip the If Condition block, because the If condition is False, so skip the If-Block Statement
result and executed other statement.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 63 II.B.Sc., III Sem Java
(2). If…Else Statement: - The If…Else Statement is an extension of the Simple If Statement.

 IF the Test Expression / Condition are “True”, then executed the True Block of Statement(s).That
means „If-Block Statement‟ is executed only.
 If the Test Expression / Condition are “False”, then executed the False Block of Statement(s). That
means „Else-Block Statement‟ is executed only.
 But they have not executed both blocks.
 In the both cases, the control is transferred subsequently to the next statements.

Syntax of If…Else Statement: -

If (Expression / Condition)
{
True – Block Statement(s);
}
Else
{
False – Block Statement(s);
}

Flow Chart for If…Else Statement: - Entry

Test
False True
Expression

False Block Statement True Block Statement


-Block -Block

Statement -Block

// Illustrate the program by using If…Else Statement?

import java.lang.*;
class IfelseBlock
{
public static void main(String args[])
{
int n=-5;
if(n>0)
{
System.out.println("The Given Number is Positive Number: "+n);
}
else
{
System.out.println("The Given Number is Negative Number: "+n);
} }
}
Save: - IfelseBlock.java
Compile: - D:\Fareed Javaprog> javac IfelseBlock.java
Run: - D:\Fareed Javaprog> java IfelseBlock
Output: - The Given Number is Negative Number: - 5.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 64 II.B.Sc., III Sem Java
(3). Nested If…Else Statement: - When a series of decision are involved for the execution of a
statement block we may have use more than one If…Else Statement in Nested form.

Syntax for Nested If…Else Statement: -

If (Expression 1 / Condition 1)
{
If (Expression 2 / Condition 2)
{
Statement Block - 1;
}
Else
{
Statements Block - 2;
}
}
Else
{
Statements Block - 3;
}
Statements – n;

 IF Test Condition 1 and Condition 2 are evaluated to “True”, then Statement Block–1 will executed.
 IF Test Condition 1 evaluates to “True” and Test Condition 2 evaluates to “False”, then Statement
Block - 2 will be executed.
 IF Test Condition 1 evaluates to “False”, then the Statement Block – 3 will be executed.

Flow Chart for Nested If…Else: -


Entry

Condition True
1?

False

Statement Block 3 False True


-Block Condition
2?

Statement Block 2 Statement Block 1


-Block

Statement Block - n

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 65 II.B.Sc., III Sem Java
// Illustrate the biggest of three number program by using Nested If…Else Condition?

import java.lang.*;
class NestedIf
{
public static void main(String args[])
{
int a=98857, b=12847, c=94912;
System.out.println("Largest Value in among three is : ");
if(a>b)
{
if(a>c)
{
System.out.println(a);
}
else
{
System.out.println(c);
}
}
else
{
if(c>b)
{
System.out.println(c);
}
else
{
System.out.println(b);
}
}
}
}

Save: - NestedIf.java
Compile: - D:\Fareed Javaprog> javac NestedIf.java
Run: -D:\Fareed Javaprog> java NestedIf
Output: - Largest Value in among three is : 98857

(4). If…Else…If Ladder: -

If…Else…If Ladder is used when we compare more than one condition to execute one set of
statements among several mutually exclusive statements. The conditions are evaluated from the top to
downwards.

 The statement which is associated with the condition that is evaluated to “True” will be executed
and all the remaining statements will be skipped.

 Whenever it finds a “True” condition then the execution will be stopped there and control comes out
from the ladder.

 When all the „n‟ conditions becomes False, then the final „Else‟ containing the „default-statement‟ will
be executed.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 66 II.B.Sc., III Sem Java
Syntax for If…Else…If Ladder Statement: -

If (Test Condition – 1)
Statement – 1;
Else if (Test Condition – 2)
Statement – 2;
Else if (Test Condition – 3)
Statement – 3;
----------
----------
----------
Else if (Test Condition – n)
Statement – n;
Else
Default Statement;
Next Statements;

Flow Chart for If…Else…If Ladder Statement: -

Entry

True
Conditi False
on 1

Statement - 1 True False


-Block Conditi
on 2

Statement - 2
-Block True False
Conditi
on 3

Statement - 3
-Block True False
Conditi
on - n

Statement - n Default Statement


-Block -Block

Next Statements
-Block

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 67 II.B.Sc., III Sem Java
// Illustrate the java program by using If…Else…If Ladder Statement?

import java.lang.*;
class ElseifLadder
{
public static void main(String args[])
{
int a=6;
{
if (a>0)
System.out.println("It is Positive Value : " + a);
else if (a<0)
System.out.println("It is Negative Value : " + a);
else
System.out.println("It is Zero Value : " + a);
}
}
}

Save: - ElseifLadder.java
Compile: - D:\Fareed Javaprog> javac ElseifLadder.java
Run: -D:\Fareed Javaprog> java ElseifLadder

Output: - It is Positive Value : 6

// Illustrate the java program by using If…Else…If Ladder Statement?

import java.lang.*;
class IfelseifLadder
{
public static void main(String args[])
{
int rollnumber[]={111,222,333,444};
int marks[]={81,75,43,58};
for(int i=0; i<rollnumber.length;i++)
{
if (marks[i]>79)
System.out.println(rollnumber[i] + " : Distinction Grade");
else if (marks[i]>59)
System.out.println(rollnumber[i] + " : I - Grade");
else if (marks[i]>49)
System.out.println(rollnumber[i] + " : II - Grade");
else
System.out.println(rollnumber[i] + " : Fail");
}
}
}

Save: - IfelseifLadder.java
Compile: - D:\Fareed Javaprog> javac IfelseifLadder.java
Run: -D:\Fareed Javaprog> java IfelseifLadder

Output: - 111 : Distinction Grade.


222 : I – Grade.
333 : Fail
444 : II – Grade.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 68 II.B.Sc., III Sem Java
(B). Switch Statement: -

Java has a built-in a multi-way decision making statements known as „Switch Statement”. The
Switch Statement tests the value of a given variable against a list of each case values and whenever a
match is found, a block of statements associated with that case is executed.

Syntax for Switch Statement: -

Switch (Variable / Expression)


{
Case Value 1:
Statement Block – 1;
Break;
Case Value 2:
Statement Block – 2;
Break;
Case Value 3:
Statement Block – 3;
Break;
-----------------
-----------------
-----------------
Case Value n:
Statement Block – n;
Break;
Default:
Default – Block;
}
Next Statements;

 The Expression is an Integer Expression or Characters, Value 1, Value 2 ….. Value n is unique
constants or constant expressions and is known as “Case Label”.
 A Switch Statement Block – 1, Block – 2 …… Block – n are statements lists any may contain one or
more statements in it.
 There is no need to put braces ( { } ) around these Blocks, but it is important to that case labels
end with a Colon ( : ).
 When the Switch is executed, the value of the expression is successively compared against the
values Value 1, Value 2, …… Value n. if a case is found whose Value of the expression, then the
Block of statements case are executed.
 The „Break‟ statement at the end of each block signal the end of a particular case and causes an exit
from the Switch statement, transferring the control to the next statement.
 When Switch fails to match the expression with all of the case values, then it goes for Default Block

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 69 II.B.Sc., III Sem Java
The Control Flow in the Switch statement is shown below.

Switch (F)
{
Case F1: If (F==1)

Statement Block – 1;
Break;
Case F2: If (F==2)
Statement Block – 2;
Break;
Case F3: If (F==3)
Statement Block – 3;
Break;
-----------------
-----------------
-----------------
Case F n:
Statement Block – n;
Break;
Default: If Switch is Fail in above all Cases
Default – Block;
}
Next Statements;

// Illustrate the Switch Statement?

import java.lang.*;
class Switchdays
{
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("Tueday");
break;

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 70 II.B.Sc., III Sem Java
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Firday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Invalid Day Number");
}
}
}

Save: - Switchdays.java
Compile: - D:\Fareed Javaprog> javac Switchdays.java
Run: - D:\Fareed Javaprog> java Switchdays

Output: - Friday.

// Illustrate the Switch Statement by using Exceptions?

class SwitchName
{
public static void main(String args[])
{
char choice;
System.out.println("Select Below your City");
System.out.println(" S --> Shaik. ");
System.out.println(" M --> Mohammad. ");
System.out.println(" F --> Fareed. ");
System.out.println(" R --> Rompicherla. ");
System.out.println(" Choice any Character ------- . ");

try
{
switch(choice=(char) System.in.read())
{
case 'S':
case „s‟:
System.out.println("Shaik.");
break;

case 'M':
case „m‟:
System.out.println("Mohammad.");
break;

case 'F':
case „f‟:
System.out.println("Fareed.");
break;

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 71 II.B.Sc., III Sem Java
case „R':
case „r‟:
System.out.println("Rompicherla.");
break;
default:
System.out.println("Invalid Choice Name");
}
}
catch(Exception e)
{
System.out.println("I/O Error");
}
}
}

Save: - SwitchName.java
Compile: - D:\Fareed Javaprog> javac SwitchName.java
Run: - D:\Fareed Javaprog> java SwitchName

Output: - Select Below your City.

S  Shaik.
M  Mohammad.
F  Fareed.
R  Rompicherla.

Choice any Character ------- F


Fareed.

(C). Conditional Operator Statement: - Conditional operator is one of the special operators supported
by Java which can be for making multi-way decision statements. The operator is a combination of “ ? ”
And “ : ”. Since it acts upon three operands, it is called as Ternary operator. This operator is used to
construct conditional expressions of the form.

Syntax: - Exp 1 ? Exp 2 : Exp 3

Here Exp 1, Exp 2 and Exp 3 is Expressions. And ? : is Operators.

 Exp 1 is evaluated First, If is True (nonzero), then the Expression Exp 2 is evaluated returned.
 If Exp 1 is False, Exp 3 is evaluated returned.

// Illustrate The Conditional Operator Program?

class Exps
{
public static void main(String args[])
{
int a =13, b =25;
int big = a>b?a:b;
System.out.println("Biggest Value is : " +big);
}
}
Save: - Exps.java
Compile: - D:\Fareed Javaprog>javac Exps.java
Run: - D:\Fareed Javaprog>java Exps

Output: - Biggest Value is : 25.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 72 II.B.Sc., III Sem Java
Chapter – 6
Decision Making and Looping.
Introduction: -

Looping: - “The Process of repeatedly executing a block of statements is known as Looping”. The
Statements in the block may be executed any number of times, from one to infinite number.

A Loop in a program essentially consists of two parts, one is called the Body of the Loop and
another is known as Conditional Statement. The Body part of the Loop will be executed repeatedly as long
as the given condition evaluates to True.

Java supports such Looping features which enable us to develop programs containing repetitive
processes without using unconditional branching statements like „Go to Statement‟.

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

(1). Entry-Controlled Looping: - 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 Loop will not be
executed.

(2). Exit-Controlled Looping: - In case of an 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.

Flow Chart of Entry and Exit-Controlled Looping: -

Therefore, for an efficient Looping mechanism, the following steps are included.

Step 1: Initialization: - To set the initial value for the Loop counter. The Loop Counter may be either
Increment counter or a decrement counter.

Step 2: Decision: - An appropriate test condition to determine whether the Loop is executed or not.

Step 3: Updation: - Incrementing or Decrementing the counter value.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 73 II.B.Sc., III Sem Java
(Q). Explain the various Looping control Statements (or) Iteration Statements available in Java?

Looping Statement: - Looping Statement also called as “Iteration Statements”. With the help of iterative
statements we can repeated the specific task as long as the specified condition. The following comes under
these Statements like:

(A). While Looping.


(B). Do…While Looping.
(C). For Looping.

(A). While Loop Statement: -

“When the given condition is True, the statements are executed repeatedly. If it is False, the
loop will be terminated”.

 While Loop is an Entry-Controlled Loop statement as it tests the given condition from the first
iteration onwards.

 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 tests condition is once again evaluated and if it is „True‟, the body is
executed once again.

 This process of repeated execution of the body continues until the test condition finally becomes
“False” and the control is transferred out of the loop on exit.

Syntax for While Statement: -

Initialization;
While (Test Condition)
{
Body of the Loop;
}

Flow Chart for while Statement: -

Entry

Test False
Condition

True

Body of the Loop

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 74 II.B.Sc., III Sem Java
// Illustrate the given Sum of the Natural Numbers by using While Statement?

import java.lang.*;
class Doloop
{
public static void main(String args[])
{
int n=10, i, sum=0;
i=1;
while(i<=n)
{
sum =sum +i ;
i=i+1;
}
System.out.println("Sum of 1st 10 Natural Numbers is : " + sum);
}
}

Save: - Doloop.java
Compile: - D:\Fareed Javaprog> javac Doloop.java
Run: - D:\Fareed Javaprog> java Doloop

Output: - Sum of 1st 10 Natural Numbers is : 55

(B). Do…While Loop Statement: -

The Do…While Loop Statement, executed the body of statement at first then evaluates the
condition. If condition is True to allow the body of the loop repeatedly. If it is False, the loop will be
terminated.

 Do…While Loop is an Exit-Condition loop statement as it allows the loop body to be executed for the
first time without any condition.

 The Body of statement executed at first time without any test condition, then evaluate the
condition, If condition is “True” to evaluate the loop body will be allowed to execute.

 This loop is used to execute a set of statements repeatedly for a finite number of times.

 This process will be continued until the given test condition becomes False, The Loop will be
terminated and control goes to the statement that appears immediately after the while statement.

Syntax for Do…While Loop Statement: -

Do
{
Body of the Loop;
}
While ( Test Condition );
Next Statements;

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 75 II.B.Sc., III Sem Java
Flow Chart for Do…While Statement: -

Body of the Loop

Test
Condition

False True

// Illustrate the given Sum of the Natural Numbers by using Do…While Statement?

import java.lang.*;
class DowhileLoop
{
public static void main(String args[])
{
int n=25;
int i=1;
int sum=0;
do
{
sum=sum+i;
i=i+1;
}
while(i<=n);
System.out.println("Sum of 1st 10 Natural Numbers is : " + sum);
}
}

Save: - DowhileLoop.java
Compile: - D:\Fareed Javaprog> javac DowhileLoop.java
Run: - D:\Fareed Javaprog> java DowhileLoop

Output: - Sum of 1st 10 Natural Numbers is : 325

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 76 II.B.Sc., III Sem Java
// Illustrate the Multiplication of table by using Nested Do…While Statement?

import java.lang.*;
class NestedDowhile
{
public static void main(String args[])
{
int row,column,y;
System.out.println("Multiplication of Table \n");
row=1;
do
{
column=1;

do
{
y=row*column;
System.out.println(" "+y);
column=column+1;
}
while (column <=10);
System.out.println("\n");
row=row+1;
}
while(row<=10);
}
}

Save: - NestedDowhile.java
Compile: - D:\Fareed Javaprog> javac NestedDowhile.java
Run: - D:\Fareed Javaprog> java NestedDowhile
Output: -

Multiplication of Table.

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

Differences between While and Do…While Statement: -

While Statement Do…While Statement


While statement, first check the condition, Do…While statement, first statement are
then executed the statements. executed then check the condition.
By default it executed statements „0‟ times. By default it executed statements „1‟ times.
Entry-Controlled. Exit-Controlled.
The While Statement should not terminate The Do…While Statement should terminate
with semicolon ( ; ) with semicolon ( ; )

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 77 II.B.Sc., III Sem Java
(C) For Loop Statement: -

The For Loop is another Entry-Controlled Loop that provided a more convenient construct looping
control structure. A For Statement performs an initialization step then evaluates a expression. If the
expression evaluate to “True”, a given statement is executed and an increment or decrement expression is
evaluated repeatedly as long as the expression continues to evaluate to „True‟. If Expression is evaluated
“False” the loop will be terminate and jump into another statements.

Syntax of For Loop Statement: -

For ( Initialization ; Expression / Test Condition ; Increment / Decrement )


{
Body of the Loop ;
}

The For Loop Statement consists of three parts. That is:

1. Initialization Part.
2. Test Condition Part.
3. Increment / Decrement Part.

1. Initialization Part: - “Initialization part is used to initialize all the sentinel variables which are to
be used in the loop”. Using the assignment statement such as I = 1 or k = 0 or count = 0. the
variables I, K, Count are known as „Loop-Control Variables‟.

2. Test Condition Part: - “The Condition / Expression part contains the actual conditional expression
which controls the execution of the Loop”. The Test Condition is a relational expression, such as
I < 20, or I < n, that determines when loop will exit. If the condition is “True”, the body of the loop
is executed; otherwise the loop is terminated.

3. Increment / Decrement Part: - “Increment / Decrement part is used to place increment or


decrement expressions of the variables”. When the body of the loop is executed, the control is
transferred back to the For Statement after evaluating the last statement in the loop. Now the
control variable is Incremented / Decremented by i+ + (Increment I by 1) / i- - (Decrement I by 1),
and the new value of the control variable is again tested to see whether it satisfies the loop
condition. If the condition is satisfied, the body of the loop is again executed. This process continued
until the given condition becomes control variable fails.

The Control Flow of For Statement: -

Entry 1st Iteration 2nd Time onwards

For ( Initialization ; Expression / Test Condition ; Increment / Decrement )


{ True
Body of the Loop ;
} False
Next Statements;

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 78 II.B.Sc., III Sem Java
Flow Chart of For Statement: -

Initialization;

Test Condition;
False
Increment / Decrement;
Next Statements;
True

Body of the Loop

// Illustrate the Sum of all Odd Numbers Program by using For Statement in Java?

import java.lang.*;
class Forstate
{
public static void main(String args[])
{
int n=50;
int i;
int sum =0;
for(i=1;i<=50;i=i+2)
{
sum=sum+i;
}
System.out.println("Sum of all Odd Numbers of less than 50 is : "+sum);
}
}
Save: - Forstate.java
Compile: - D:\Fareed Javaprog> javac Forstate.java
Run: - D:\Fareed Javaprog> java Forstate

Output: - Sum of all Odd Numbers of less than 50 is: 625.

Nesting of For Statement: - Nesting of loops, that is “One For Statement within another For Statement is
allowed is a known as Nesting For Statement”. In Java we have used this concept similarly For Loop.
Nesting of For Loop is as follows below:
----------------
----------------
For (i=1; i<10; i++)
{
----------------
----------------
For (j=1; j> 20; ++j)
{
- - - - - - - - - - - - - - - - Inner Loop Outer
---------------- Loop
}
----------------
----------------

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 79 II.B.Sc., III Sem Java
// Illustrate Print the Pyramid Program in Incremental order by using Nesting For Statement?

import java.lang.*;
class Pyramid
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
for(int j=0; j<i; j++)
{
System.out.print("*");
}
System.out.println(" "); // Generate a New line.
}
}
}

Save: - Pyramid.java
Compile: - D:\Fareed Javaprog> javac Pyramid.java
Run: - D:\Fareed Javaprog> java Pyramid
Output: -
*
* *
* * *
* * * *
* * * * *

// Illustrate Print the Pyramid Program in Detrimental order by using Nesting For Statement?

import java.lang.*;
class PyramidDec
{
public static void main(String args[])
{
for(int i=5;i>0;i--)
{
for(int j=0; j<i; j++)
{
System.out.print("*");
}
System.out.println(" "); // Generate a New line.
}
}
}
Save: - PyramidDec.java
Compile: - D:\Fareed Javaprog> javac PyramidDec.java
Run: - D:\Fareed Javaprog> java PyramidDec
Output: -

* * * * *
* * * *
* * *
* *
*

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 80 II.B.Sc., III Sem Java
// Illustrate Print the Pyramid of Numbers by using Nesting For Statement?

import java.lang.*;
class PyramidNumber
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
for(int j=0; j<i; j++)
{
System.out.print(j+1);
}
System.out.println(" ");
}
}
}

Save: - PyramidNumber.java
Compile: - D:\Fareed Javaprog> javac PyramidNumber.java
Run: - D:\Fareed Javaprog> java PyramidNumber
Output: -
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

NOTE: -
The For Statement and its equivalent of While and Do…While Statement. There are shown in below:

While Statement Do…While Statement For Statement


n=1 n=1 For(n=1; n<=10; n++)
while(n<10) Do {
{ { ------
----- ---- ------
----- ---- }
n=n+1; n=n+1;
} }
while(n<=10)

Additional Features of For Loop Statement: -

1. The For loop has several capabilities that are not found in the other loop constructs.

Example: - For Example, more than one variable can be initialized at a time in the For Statement.

P = 1;
For (n = 0; n < 15; ++n)

Can be Rewritten as
For (p = 1, n = 0; n < 15; ++n)

Notice that the Initialization section has two parts like „P = 1‟ and „n = 1‟ separated by a comma (,)

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 81 II.B.Sc., III Sem Java
// Illustrate the program more than one variable can be initialized at a time in the For Statement?

import java.lang.*;
class MoreVar
{
public static void main(String args[])
{
int sum =0;
for(int n=50, i=1;i<=50;i=i+2) // More then One Variable can be Initialized at a Time.
{
sum=sum+i;
}
System.out.println("Sum of all Odd Numbers is less than 50 is : "+sum);
}
}

Save: - MoreVar.java
Compile: - D:\Fareed Javaprog> javac MoreVar.java
Run: - D:\Fareed Javaprog> java MoreVar

Output: - Sum of all Odd Numbers of less than 50 is: 625.

2. The Second Feature is The Increment section may also have more than one part.

Example: - For Example, the loop is perfectly valid. The multiple arguments in the Increment section are
separated by commas (,).

For ( n=1, m=10; n<=m; n=n+1, m=m-1)


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

// Illustrate the program more than one Increment section can be at a time in the For Statement?

import java.lang.*;
class MoreInc
{
public static void main(String args[])
{
int n=50;
int i;
int sum =0;
for(i=1;i<=50;i=i+2,sum=sum+1) // More than one Incremental Operation.
{
// sum=sum+i;
}
System.out.println("Sum of all Odd Numbers is lessthan 50 is : "+sum);
}
}

Save: - MoreInc.java
Compile: - D:\Fareed Javaprog> javac MoreInc.java
Run: - D:\Fareed Javaprog> java MoreInc

Output: - Sum of all Odd Numbers of less than 50 is: 25.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 82 II.B.Sc., III Sem Java
3. The Third Feature is that the Test Condition may have any compound relation and the testing need not
be limited only to the loop control variable.

Example: - Consider the Following Example

Sum = 0;
For (i=1; i<20 && sum<100; ++i)
{
-----------------------
-----------------------
-----------------------
}
The Loop uses a compound Test Condition with the control variable „ I ‟ and external variable „sum‟.
The loop is executed as long as both the conditions „i<20 and sum<100‟ are True. The „sum‟ is evaluated
the inside of the loop.

// Illustrate the program more than one Conditional section can be at a time in the For Statement?

import java.lang.*;
class MoreCond
{
public static void main(String args[])
{
int i;
int sum =0;
for(i=1;i<20 && sum<100; ++i) // More than One Condition.
{
}
System.out.println("Sum : "+sum);
}
}
Save: - MoreCond.java
Compile: - D:\Fareed Javaprog> javac MoreCond.java
Run: - D:\Fareed Javaprog> java MoreCond

Output: - Sum: 0.

4. Another unique aspect of For loop is that one or more sections can be omitted, if necessary.

Example: - Consider the Following Statements.

-------------------
-------------------
m = 5;
For ( ; m !=100; )
{
System.out.println (m);
m = m + 5;
}
-------------------
-------------------
Both the Initialization and Increment Section are omitted in the For Statement. The Initialization has
been done before the For Statement and the control variable is Incremented inside the loop. In such cases,
the sections are left blank. However, the semicolons separating the sections must remain.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 83 II.B.Sc., III Sem Java
// Illustrate the program Omitted more than one section can be at a time in the For Statement?

import java.lang.*;
class Forex
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
{
int j=0;
for(; j<i; j++) // Here Omitted for Initialization Variable and Incremental Value inside the For Loop
{
System.out.print("*");
}
System.out.println(" ");
}
}
}

Save: - Forex.java
Compile: - D:\Fareed Javaprog> javac Forex.java
Run: - D:\Fareed Javaprog> java Forex
Output: -
*
* *
* * *
* * * *
* * * * *

(Q). Explain the various Transfer Statements (or) Jumping. Statements available in Java?

Jumping Statement also called as “Transfer Statement”. With the help of transfer control one
block or part of the program to another block or part of the program.

Example: - For example, consider the case of searching for a particular name in a list containing, say 100
names. A program loop written for reading and testing the names a 100 times must be terminated as soon
as the desired name is found.

Java permits a Jump from one statement to the end or beginning of a loop as well as a Jump out
of a loop. Java provides three ways of Transferring Control in a Program, which embodied in the following.

1. Break Statement. (or) Jumping Out of a Loop.


2. Continue Statement. (or) Skipping a part of a Loop.
3. Return Statement.

1. Break Statement (or) Jumping Out of a Loop: - A Break Statement allows to exit from any point
with in its body, bypassing its normal termination expression. When a Break Statement is encountered
inside a loop, the loop is immediately stopped, and program control resumes at the next statement
following the loop.

The innermost While, Do…While and For Statement that enclosed the Break Statement must be in
the immediately enclosing method or initialize block.

Syntax of Break Statement: - Break;

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 84 II.B.Sc., III Sem Java
Exiting a Loop With Break Statement: -

Break with While Statement: - Break with Do…While Statement: -

While ( Condition) Do
{ {
----------- --- --------------
----------- --- --------------
If (Condition) If (Condition)
Break; Break;
----------- --- --------------
----------- --- -------------- Exit From
} Exit From } Loop.
Next Statements; Loop. While (Condition);
----------- --- Next Statements;
----------- --- --------------
--------------

Break with For Statement: - Break with Nested For Statement: -

For ( Init Value; Condition; Incre/Decre) For ( Init Value; Condition; Incre/Decre)
{ {
-------------- --------------
-------------- --------------
If (Condition) For ( Init Value; Condition; Incre/Decre)
Break; {
-------------- --------------
-------------- --------------
} Exit From If (Condition)
Next Statements; Loop. Break;
-------------- --------------
-------------- --------------
} Exit From
Next Statements; Inner Loop.
--------------
--------------
}

// Illustrate the program by using Break Statement?

import java.lang.*;
class WhileBreak
{
public static void main(String args[])
{
int i=1;
while(i<=5)
{
int j=1;
while(true)
{
System.out.println ( j );

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 85 II.B.Sc., III Sem Java
j++;
if (j>i)
break;
}
System.out.println ("\t");
i++;
}
}}
Save: - WhileBreak.java
Compile: - D:\Fareed Javaprog> javac WhileBreak.java
Run: - D:\Fareed Javaprog> java WhileBreak
Output: -
1 1 1 1 1
2 2 2 2
3 3 3
4 4
5
(2). Continue Statement. (Or) Skipping a part of a Loop: -

The Continue Statement forces the next iteration of the loop to take place, in Java, continue
statement is used to skipping the execution some (or) any code in between itself and the test condition of
the loop. Whenever the Continue statement encountered inside a loop it skips the execution of the
statements, and the control passes to the condition, which is evaluated, and if True, the loop is entered
again.

The Continue Statement tells the Compiler “Skip the Following Statements and Continue with the
Next Iteration”.

Syntax of Continue Statement: - Continue;

Bypassing and Continuing in Loop: -

Continue with While Statement: - Continue with Do…While Statement: -

While ( Condition) Do
{ {
----------- --- --------------
----------- --- --------------
If (Condition) If (Condition)
Continue ; Continue ;
----------- --- --------------
----------- --- --------------
} }
Next Statements; While (Condition);
----------- --- Next Statements;
----------- --- --------------
--------------
Continue with For Statement: -

For ( Init Value; Condition; Incre/Decre)


{
--------------
If (Condition)
Continue;
--------------
}
Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 86 II.B.Sc., III Sem Java
// Illustrate the program by using Continue Statement?

import java.lang.*;
class WhileContinue
{
public static void main(String args[])
{
int i=10;
while(i<10)
{
i++;
if(i>5 && i<8)
continue;
System.out.println(i);
System.out.println(":"+i);
}
}
}

(3). Return Statement: - A Return Statement returns the control of the current method or constructor to
the caller.

Syntax of Return Statement: - Return / Return <Expression>

 If a „return‟ statement does not contain an expression, the statement must be in a method declared
with the „void return type‟ or in a constructor. Otherwise, the compiler issues an error message.
 If a „return‟ statement contains an expression, it must be in a method that returns a value or the
compiler issue an error message. The type of the expression is the return value of the current
method.

(Q). Explain the Labeled Statements (or) Labeled Loops Statements available in Java?

Java does not include a „Goto‟ statement. Instead of goto, Java allows you to combine Break and
Continue with label. This has an effect similar to a „Goto‟ in that it allows a program to reposition control.

A block of statements can be Labeled as shown below:

Block 1:
{
----------- ---------
----------- ---------
Block 2:
{
-- ------------------
-- ------------------
}
----------- ---------
}

 Here to give a label to a loop, place it before the loop with a colon (:) at the end.
 “A Simple Break Statement causes the Control to Jump outside the nearest loop”.
 “A Simple Continue Statement restarts the current loop”.
 If we want to jump outside nested loops or to continue a loop that is outside the current one, then
we may have to use the labeled break and continue statements.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 87 II.B.Sc., III Sem Java
Example: -
Fareed:
For (int m=1; m=11; m++)
{
For (int n =1; n<11; n++)
{
System.out.println(“ ” + m*n);
If (n = = m)
Continue Fareed;
}
}

Here, the Continue Statement terminates the inner loop when „ n = m ‟ and continue with the next
iteration of the outer loop (counting m).

(a). Label Break: - In Java you can give a label to a block of statements. The labeled statements are
useful when you are exiting from a deeply nested set of loops. You can break out of one or more blocks of
code using labeled break.

Syntax for Labeled Break: - Break label;

Example: -
Fareed:
{
--------------------
--------------------
Break Fareed;
}

Here, label is the name of a label that identifies a block of code. When this form of break executes,
control is transferred out of the named block of code. This means that you can use a labeled break
statement to exit from a set of nested blocks.

// Illustrate the program by using labeled Break statement?


import java.lang.*;
class LabelBreakFareed
{
public static void main(String args[])
{
boolean flag=true;
Shaik:
{
Mohammad:
{
Fareed:
{
System.out.println("Before the Break");
if(flag)
break Mohammad;
System.out.println("Doesn't Execute");
}
System.out.println("Doesn't Execute");
}
System.out.println("After Second Block");
}
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 88 II.B.Sc., III Sem Java
Save: - LabelBreakFareed.java
Compile: - D:\Fareed Javaprog> javac LabelBreakFareed.java
Run: - D:\Fareed Javaprog> java LabelBreakFareed

Output: - Before the Break


After Second Block.

(b). Label Continue: - As Label Break, Continue may specify a label to describe which loop to continue.

Syntax for Labeled Continue: - Continue label;

Example: -
Fareed:
{
--------------------
--------------------
Continue Fareed;
}
// Illustrate the program by using labeled Continue statement?

import java.lang.*;
class LabelContinueFareed
{
public static void main(String args[])
{
Fareed:
for(int i=1;i<=5;i++)
{
System.out.println("\r");
System.out.println("*");
Shaik:
for(int j=1;j<=5;j++)
{
System.out.print("$");
if(j>=i)
continue Fareed;
}
}
}
}
Save: - LabelContinueFareed.java
Compile: - D:\Fareed Javaprog> javac LabelContinueFareed.java
Run: - D:\Fareed Javaprog> java LabelContinueFareed

Output: -
*
$
*
$ $
*
$ $ $
*
$ $ $ $
*
$ $ $ $ $

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 89 II.B.Sc., III Sem Java
// Illustrate the program by using labeled Break and Continue statement?

import java.lang.*;
class BreakContinueFareed
{
public static void main(String args[])
{
Fareed:
for(int i=1;i<=100;i++)
{
System.out.println(" ");
if(i>=5)
break;
for(int j=1;j<100;j++)
{
System.out.println("Fareed");
if(j==i)
continue Fareed;
}
}
System.out.println("Termination by BREAK");
}
}

Save: - BreakContinueFareed.java
Compile: - D:\Fareed Javaprog> javac BreakContinueFareed.java
Run: - D:\Fareed Javaprog> java BreaklContinueFareed

Output: - Fareed

Fareed
Fareed

Fareed
Fareed
Fareed

Fareed
Fareed
Fareed
Fareed

Termination by BREAK.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 90 II.B.Sc., III Sem Java
Chapter – 7
Class, Objects and Methods.
Introduction: -

Objects: - Objects are the basic runtime entities in an Object Oriented System (OOS). An Object is any of
the following: External entities, Things, Events / Occurrences, Roles, Organizational Units, Places, etc

Definition(1) of Objects: - “Any thing can be Objects”, in other words an Object be a Person, Place, or
Things which the computer must be understand or recognized.

Definition(2) of Objects: - An Object is a “Software bundle of Variable and related Methods”.

Definition(3) of Objects: - An Object is a set of Data its associated Methods. Object = Data + Methods.

Definition(4) of Objects: - An Object has defined as an identifiable entity with some Characteristics
and Behavior”.

Definition (5) of Objects: - Objects are run times entity. An object is distinguishable entity with some
Characteristics & Behavior. Every object has a defined as
 State.
 Behavior.
 Identity.

State: - The State of an Object encompasses all of the (Static) Properties of the Object plus the current
(Dynamic) values of each of these properties.

Behavior: - Behavior is how an Object acts and reacts, in terms of its state changes and message
passing.

Identity: - Identity is that property of an Object which Distinguishes or Unique it from all other Objects.

Examples of Objects in real world entity: - Vehicle, Furniture, etc.,

Example (1): - We need some information about Cars (Car is Object). Car can have the following
features.
State: - Color, Size, Weight, Engine capacity etc.,
Behavior: - Start, Stop, Forward, Backward, Accelerate, etc.,
Identity: - Registration number, classic model shape, etc.,
Example (2): -
Person Object
Name Shaik Mohammad Fareed
Basic Pay 35000 Data (or) Characteristics
Salary ()
Methods (or) Behavior
Income Tax() (or) Functions.

Note: -
(1). Objects share two characteristics: they all have state and they all have behavior.
(2). Object maintains its state in variables and implements its behavior with methods.
(3). Everything that the software object knows (state) and can do (behavior) is expressed by the
variables and methods within that objects.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 91 II.B.Sc., III Sem Java
Variables

Methods

Classes: - The most important feature of OOP‟s is the Class. A class is the way to bind the “Data & its
associated Functions” or some time called also “Variables & Methods”. The keyword “class” specifies the
class name.

Definition (1) of Class: - “A Class is a collection of objects of similar type”.

Definition (2) of Class: - “A group of Objects that share common properties and relationships”.

Definition (3) of Class: - “A Class is a set of Objects that share a common structure and common
behavior.

Definition (4) of Class: - “The Objects with the same data structure (attributes) and behavior
(operations) are grouped into a class.

Definition (5) of Class: - A Class is a “blueprints” or “prototype” that defines the variables and methods
common to all objects of a certain kind. Software “blueprints” for objects are called classes.

In Java, a Class is a new data type that contains member variables and member functions
that operate on the variables. A class is defined with key word “Class”.

Example(1): - Motor bicycle object is an instance of the class of objects known as Motor bicycle. Motor
bicycles have some state (current gear, etc) and behavior (change gears, brake, etc) in common. However
each motor bicycle‟s state is independent of and can be different from other motor bicycles.

Speed and
Change Gear
Gears

Methods
Brake

Example(2): - For example in the case of Student Class, all objects have similar attributes like s_number,
s_name, marks in three subjects and similar operations like total(), average(). Related objects exhibiting
the same behavior are grouped and represented by a class in the following style.

class Student
{
int s_number;
string s_name;
int m1,m2,m3;
int total()

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 92 II.B.Sc., III Sem Java
{
int tot;
tot=m1+m2+m3;
return(tot)
}
float average()
{
float avg;
avg=(float)(m1+m2+m3)/3;
return (avg);
}
}

Methods: - The term Method comes from the Object-Oriented language small task. The function that
operates on an object is known as Methods. Methods are used to change the objects attitude values or to
return the values of selected Object attributes. Methods represented a real-world action.

Example: -
int total()
{
int tot;
tot=m1+m2+m3;
return(tot)
}

(Q). What is a Class? Explain how to define a class in Java? (OR)


Explain the Concepts of classes at the root of Java‟s design?

Introduction: -
Java is a true Object-Oriented language and therefore he 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. That is all about
Object-Oriented Programming”.

A Class is a collection of related objects that share common properties and actions. Once a class is
defined, we can create any number of objects belonging to those classes. Objects of a class are also called
as “Instances” of that class.

Example: - Person, Vehicle, Furniture, etc.

A Class is a user defined data type, which may contain three types of items: Variables, Methods and
Constructors.

 Variables represent its State.


 Methods Provides the logic that constitutes the Behavior defined by a Class.
 Constructors initialize the state of a new instance of a class.

Classes are used to pack a group of logically related data items and functions that works on them.
The data items are called “Fields” and functions are called “Methods”. The concept of classes is at root of
Java‟s design.

1. Defining a Class.
2. Field Declaration / Adding Variables.
3. Methods Definition / Adding Methods.
4. Creating Objects.
5. Accessing Class Members.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 93 II.B.Sc., III Sem Java
(1). Defining a Class: -

A Class is a User-defined data type. It‟s defined the nature of objects or defines its properties. Once
the class type has been defined, we can create “Variables” of those type declarations that are similar to the
basic type declarations.
Once a class is defined, we can create a many objects as we want to create. The objects of a
class are also called as instances of that class.

Basic Syntax of Class Definition: -

Class ClassName <extends> [Super Class Name] <Implements > [ Interface Name]
{
Variables / Fields Declarations;
Methods Declarations;
}

 The “Class” is the Keyword and followed by the Class Name (Its User-Define) is the actual class
which we want to define.

 The Keyword “extends” is used to extend the features of existing class to the current class. We can
create or use only one Superclass to extend at a time.

 The Keyword “Implements” is used to implement the interfaces if any. We can use more than one
interface to implements in the current class.

NOTE: -

1. Every ClassName is started with “First Capital Letter” then followed by small letters (Single Word).
Example: - Class Fareed. Here Class name is „Fareed‟. And „F‟ is Capital letter and followed small.

2. If ClassName contain two or more words we started with first capital letter and next word also first
letter is capital and following small letters. (Two or more).
Example: - Class MohammadFareed. Here First Word „M‟ and Next word „F‟ is capital letter.

3. There is no any space between two or more words as a Class Name.

(2). Field Declaration / Adding Variables: -

In Object-Oriented Programming (OOP‟s) data are encapsulated in a class by placing data


variables inside the class definition. The data variables are called as „Fields‟ or „Instance variables‟ because
they are created whenever an object of the class is instantiated. We can declare the instance variables
exactly the same way as we declare local variables.

Example: - Class Student


{
Int age;
String name;
Char gender;
}
 The Field of data variables declares inside the body of the class definition.

 Here Class Name is “Student” contain three fields each if type as Int, String, Char. These variables
are only declared but not created. These variables are created when we create an object to that
class.

 Instance variables are also called as “Member Variables”.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 94 II.B.Sc., III Sem Java
(3). Methods Definition / Adding Methods: -

A Class with only data filed (and without methods that operate on that data) has no life. The
objects created by such a class can‟t respond to any message.

A Class needs some methods as 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.

Basic Syntax for Method Definition: -

<Return Type> <Name of the Method> (Parameter List)


{
Method Body;
}

Parts of Method Declaration: - The basic four parts have Method Declaration.

1. The Type of the value the Method Returns (Return Type).


2. The name of the Method (Method Name).
3. A List of parameters (Parameter List).
4. The Body of the Method (Method Body).

1. Return Type: - The Return type of the Method specifies the type of value that the Method returns. A
Method can return a maximum of only one value of any type including basic data types and user-defined
data type.

2. Method Name: - The Name of the Method tells the actual Name of the Method. It is a valid indenter.

3. Parameter List: - The Parameters list is always enclosed in parentheses. This list contains variables
Names and types of all the variables we want to given 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.

Example: - public void setData (int a, float b, char c, string s, int x) // Five Parameters in a list.
public void setData ( ) // Empty List.

4. Method Body: - The Method Body contains actual executable statements that are designed to process
the data items.
Parameter List.
Example: -
Public void getData (Int a, String n, char g)
{
age = a;
name = n; Method Body.
gender = g;
}

NOTE: - The Method has a return type of “Void” because it does not return any value. We pass three
values to the Method which are then assigned to the instance variables age, name and gender. The
“getdata ()” method is basically added to provide values to the instances variables.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 95 II.B.Sc., III Sem Java
Example: - Let us consider the “Rectangle” class

Class Rectangle
{
Int length;
Int width;
Public void getData(Int x, Int y)
{
length = x;
width = y;
}
}
That we are able to use directly “length” and “width” inside the methods. Add some more properties to the
class, this can be done as follows:

Class Rectangle
{
Int length, width; // Combined Decorations.
Public void getData(Int x, Int y)
{
length = x;
width = y;
}
Int rectArea() // Declaration of another method.
{
int area = length * width;
return (area);
}
}
The new method “rectArea()” computes area of the rectangle and returns the result since the result would
be an integer, the return type of the method has been specifies as Int.

NOTE: - The Parameter list used in the method header should always be declared independently separated
by commas. That us

Void getData (int x, y) // Incorrect or Illegal Declaration.

(4). Creating Objects: -

An Object in Java is essentially a block of memory that contains space to store all the instances
variables. Creating an object is also referred to as “Instantiating” an objects.

Objects in Java are created using the “new” operator. The new operator allocates memory for all the
instances variables of the objects. The „new‟ operator creates an object of the specified class and returns a
reference to that objects.

Example of Creating an object: -

Rectangle rect1; // Declare an Object


rect1 = new Rectangle(); // Instantiates the Object

 The first statement „declared a reference variable‟ of the class „Rectangle‟.

 The second statement „actual assigns the object reference to the variable. The „rect1‟ is now an object
of the „Rectangle‟.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 96 II.B.Sc., III Sem Java
Action Statements Results

Declare Rectangle rect1; Null rect1

rect1
Instantiate rect1 = new Rectangle; Rectangle Object

Fig: - Creating Object References

NOTE: - Here „rect1‟ is a reference to Rectangle object.

In above two statements can also be combined into in one single line as follows.

Rectangle rect1 = new Rectangle ();

In above expression Rectangle () invokes the default constructor of „Rectangle‟ class and returns the
reference of the object.

We can create many objects based on a single class. Here each object has its own copy of
instance variables of its class.

Example: - Rectangle rect1 = new Rectangle ();


Rectangle rect2 = new Rectangle ();
Rectangle rect3 = new Rectangle ();
----------------------
----------------------
Rectangle rect n = new Rectangle ();

It is important to understand that each object has its own copy of the instance variables of its class.
This means that any changes to the variables of one object have no effect on the variable of another.

It is also possible to create two or more reference to the same objects.

Example: -
Rectangle rect1 = new Rectangle ();
Rectangle rect2 = rect1;
Rectangle rect3 = new Rectangle ();

rect1

Rectangle rect1 = new Rectangle (); Rectangle Object

Rectangle rect2 = rect1; rect2


Rectangle Object

rect3
Rectangle rect3 = new Rectangle ();
Rectangle Object

NOTE: - Here above example both „rect1 and rect2‟ refer to the same object.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 97 II.B.Sc., III Sem Java
Difference between “Value Type (Structure)” and “Reference Type (Classes)”: -

Value Type Reference Type


It directly contains the value. It is values is stored another place is called Instance.
It‟s hold the values. Objects can references the values.

10 A A 10
Object Reference
Faster in Access. Reusable Memory.
No Dynamic Memory Allocation (DMA). Dynamic Memory Allocation (DMA) allowed.
Possible for passing values only. Possible for passing References.
Here when size is small but usage of longer Here size is longer but usage is less period to better
period to use values. use classes (References) type.
It can‟t be possible to Inherited properties. It can possible Inherited Properties.
No Procted Access Modifiers. Can be used Procted Access Modifiers

(5). Accessing Class Members: -

The members of the class can be accessed directly inside that class only. Both member
variables and member functions of a class can be accessed without any references by the member
functions of that class.

From outside the class, we can not access the instance variables and the methods directly. to
access the members of a class from outside the class, we must use the proper object with relevant access
specifier. We can use the “Dot (.)” operator along with the object to refer the members of the class.

Syntax: - ObjectName . VariableName = Value;


(or)
ObjectName . MethodName (Parameter_List);

 Here „ObjectName‟ is the „Name of the Object which we want to use‟.


 „VariableName‟ is the „Name of the Instance Variable inside the object that we wish to accesses‟.
 „MethodName‟ is the „Name of the Method that we wish to call or invoke‟.
 „Parameter_List‟ is a list of values that to „Actual Values‟ of variables.
 „Parameter_List‟ is a comma separated list to „actual values‟ that must match in type.

Example: - The Instance variable of the „Rectangle‟ class may be accessed and assigned values as follow:

rect1 . length = 15;


rect1 . width = 10;
rect2 . length = 20;
rect2 . width = 12;

Value.
ObjectName. VariableName.

The two objects „rect1 and rect2‟ store different values as:

rect1 rect2

rect1.length 15 rect2.length 20

rect1.width 10 rect2.width 12

This is one of the ways of assigning values to the variables in the objects.
Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 98 II.B.Sc., III Sem Java
Another way and more convenient way of assigning values to the Instances variables is to used a
method that is declared inside the class.

The Method “getData ()” can be used to do this work, we can call the “getData ()” method on
the any class name (Rectangle) object to set the values of both „Length‟ and „Width‟. Here is the code
segment to achieve this following:

Rectangle rect1 = new Rectangle (); // Creating an Object.


Rect1.getData (15,10); // calling the Method using the Object.
Example: -
Void getData (int x, int y)
{
length = x;
width = y;
}
The Code creates „rect1‟ object and then passes in the values „15‟ and „10‟ for the „x‟ and „y‟
parameters of the method “getData()”. This method then assigns these values to „length‟ and „width‟
variables respectively. This again can be done in two ways:

1. The first approach is to access the Instance variables using the “Dot (.)” operator and compute the area

Int area1 = rect1.length * rect1.width

2. The Second approach is to call the method „rectArea ()‟ declared inside the class.

Int area1 = rect1.rectArea (); // Calling the Method

class Rectangle
{
int length,width; // Declaration of Variables.
void getData(int x, int y) // Definition of Method.
{
length = x;
width = y;
}
int rectArea() // Definition of another Method
{
int area=length * width;
return(area);
}
}
class RectArea // Class with Main Method.
{
public static void main(String args[])
{
int area1, area2;
Rectangle rect1 = new Rectangle(); // Creating Objects.
Rectangle rect2 = new Rectangle();
rect1.length = 15; // Accessing Variables of one style.
rect1.width = 10;
area1=rect1.length * rect1.width;
rect2.getData(20,12); // Accessing Variables of another style.
area2=rect2.rectArea();
System.out.println("Area 1 = " + area1);
System.out.println("Area 2 = " + area2);
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 99 II.B.Sc., III Sem Java
Save: - RectArea.java
Compile: - D:\Fareed Javaprog> javac RectArea.java
Run: - D:\Fareed Javaprog> java RectArea

Output: - Area 1 = 150


Area 2 = 240

(Q). Explain Types of Constructors with an example in Java?

Java supports a special type of method, called a Constructor. Constructors are used to initialize the
Instance Variables of an object when it is created.

 Constructors have the same name as the class name itself.


 They do not specify a return type, not even void.

Constructors are the block of statement used for the purpose of initializations. A Constructors is
never called directly, instead it is invoked via the keyword new operator. When we create an object of a
class, all the instances variables must be initialized. For this purpose we use constructors which are
associated with the class objects. Whenever we create an object, immediately a constructor of that class
will be executed.

Rules of defining Constructors: -

1. Constructors have the same name as the class name itself.


2. They do not specify a return type, not even void.
3. Constructors can accept parameters.
4. Constructors can not be invoked explicitly.
5. A class can have more than one constructor.
6. Constructors takes arguments same as normal methods.
7. An Abstract class can have constructors.
8. An Interface should not have any constructors.
9. Constructors can use any access modifies, including private.

Types of Constructors: -

A Constructors of a class either 3 types.

1. Default Constructors.
2. Parameterized Constructors.
3. Copy Constructors.

1. Default Constructors: - The Default Constructors is the Constructors which accept “Zero Arguments”
or “With out any parameters list”, and then we say „Default Constructors‟.

Example: - Class MyClass


{
Int x, y, z;
MyClass() // Default Constructor.
{
X = 0;
Y = 0;
Z = 0;
}
}

Here above example it‟s satisfied the characteristics of Constructor. Here „Class Name‟ is “MyClass”
and „Constructor Name‟ is “MyClass” have the same name as Class Name and Constructor Name.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 100 II.B.Sc., III Sem Java
Once the Constructor is defines, the Constructor is automatically called immediately after the object
is created, before the „new‟ operator completes.

MyClass obj1 = new MyClass (); // Default Constructor

2. Parameterized Constructors: - The Parameterized Constructor is the Constructor which accept “At
least one arguments” ten we say Parameterized Constructor.

Example: - Class MyClass


{
Int x, y, z;
MyClass (int a, int b) // Parameterized Constructor.
{
X = a;
Y = b;
}
}
Once the Constructor is defines, the Constructor is automatically called immediately after the object
is created, before the „new‟ operator completes.

MyClass obj2 = new MyClass (5, 10); // Parameterized Constructor.

// Program for Class and Objects using Parameterized Constructors?

class Circle
{
double x, y, radius;
Circle(double ax, double ay, double aradius)
{
x = ax;
y = ay;
radius = aradius;
}
}
class CircleConstructor
{
public static void main(String args[])
{
Circle C = new Circle(17.5, 18.4, 6); // Parameterized Constructor.
System.out.println("C.x = " + C.x);
System.out.println("C.y = " + C.y);
System.out.println("C.radius = " + C.radius);
}
}
Save: - CircleConstructor.java
Compile: - D:\Fareed Javaprog> javac CircleConstructor.java
Run: - D:\Fareed Javaprog> java CircleConstructor

Output: - C.x = 17.5


C.y = 18.4
C.radius = 6.0

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 101 II.B.Sc., III Sem Java
3. Copy Constructors: -

The simplest kind of Constructors that a class has as „one that has no parameters and another has
parameters‟. The formed is called as „Default Constructor and later is called Parameterized Constructor‟.

Another type of Constructor whose only parameters is reference to objects of the same class to
which the Constructor belongs. The form is usually used to „Duplicate an Existing object‟ of the class. So it
is called the “Copy Constructor”.

// Program for Class and Objects using Copy Constructors?

class Copy
{
double x, y;
Copy(double a, double b)
{
x = a;
y = b;
}
Copy (Copy a)
{
x = a.x;
y = a.y;
}
void show()
{
System.out.println(" X = " + x + " Y = " + y);
}
}
public class CopyConstructor
{
public static void main(String args[])
{
Copy a = new Copy(10, 20);
a.show();
Copy b = new Copy(a);
b.show();
}
}
Save: - CopyConstructor.java
Compile: - D:\Fareed Javaprog> javac CopyConstructor.java
Run: - D:\Fareed Javaprog> java CopyConstructor

Output: - X = 10.0 Y = 20.0


X = 10.0 Y = 20.0

NOTE: - It is meaningful to use the access modifiers „public‟ default, but not „private‟. If we use the access
modifiers private to constructor, we can not create any objects for that class outside of the class.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 102 II.B.Sc., III Sem Java
(Q). Explain Constructors Overloading with an example in Java?

Providing multiple definitions of the Constructor is called Constructor Overloading.


Overloading a constructor is used when we want to provide alternate ways for clients to create objects of
the class. To Overloading a constructor, we need to follow the following rules.

 The number of arguments must be differed with each other.


 If the number of the arguments is same, the datatypes of arguments must be differed.
 If the number and types of arguments are same, the order of the arguments must be differed.

// Example Program for Constructor Overloading?

import java.util.*;
class Students
{
String name;
int age;
Students() {} // Default Constructor.
Students(String n) // Paramertized Constructor 1
{
this.name = n;
}
Students(int a) // Paramertized Constructor 2
{
this.age = a;
}
Students(int a, String n) // Paramertized Constructor 3
{
this.name = n;
this.age = a;
}
void StudentsShow()
{
System.out.println("Student Name : " + name);
System.out.println("Student Age : " + age);
}
Students a1 = new Students(); // Call Default Constructor
Students a2 = new Students("Mohammad"); // Call Parameterized Constructor 1
Students a3 = new Students(25); // Call Parameterized Constructor 2
Students a4 = new Students(25,"Fareed"); // Call Parameterized Constructor 3
}

Save: - Students.java
Compile: - D:\Fareed Javaprog> javac Students.java
Run: - D:\Fareed Javaprog> java Students

Output: - Student Name: Mohammad


Student age: 25
Student age: 25 Fareed

NOTE: - The above Class „Students‟ have four different versions of constructors. Then the programmer can
create objects of the class „Students‟.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 103 II.B.Sc., III Sem Java
(Q). Explain “this” Keyword with an example program?

The “ this ” keyword refers to the “object that is currently executed”.

Syntax: - this. VariableName = value;

Here Variable Name is the name of an instance variable. There is also another form use of the this
keyword, it allows one constructor to explicitly invoke another one constructor in the same class.

The this keyword is done with another following syntax.

Syntax: - this (args);


Here, „args‟ is an optional set of arguments that may be passed to constructors.

// Example program with „this‟ keyword?

import java.util.*;
class Myclass
{
int x, y, z;
Myclass(int x, int y, int z)
{
this.x = x;
this.y = y;
this.z = z;
}
void show()
{
System.out.println("X, Y and Z are : " + x + y + z);
}
}
public class MyThis
{
public static void main (String args[])
{
Myclass fareed = new Myclass(10,20,30);
fareed.show();
}
}
Save: - MyThis.java
Compile: - D:\Fareed Javaprog> javac MyThis.java
Run: - D:\Fareed Javaprog> java MyThis

Output: - X, Y and Z are : 10 20 30

Second Form of this keyword: - Illustrates “this keyword can be used by one constructor to explicitly
invoke another constructor in its same class”

import java.util.*;
class circle
{
double x, y, radius;
circle(double x)
{
this(x, 0, 1); // this keyword with arguments list
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 104 II.B.Sc., III Sem Java
circle(double x, double y)
{
this( x, y, 1); // this keyword with arguments list
}
circle(double x, double y, double radius)
{
this.x = x;
this.y = y;
this.radius = radius;
}
}
class MyThisArgslist
{
public static void main (String args[])
{
circle c = new circle(1.1, 3.4, 10);
System.out.println("C.X = " + c.x);
System.out.println("C.Y = " + c.y);
System.out.println("C.Radius = " + c.radius);
}
}

Save: - MyThisArgslist.java
Compile: - D:\Fareed Javaprog> javac MyThisArgslist.java
Run: - D:\Fareed Javaprog> java MyThisArgslist

Output: - C.X = 1.1


C.Y = 3.4
C.Radius = 10.0

There is also another form use of the this keyword, it allows one constructor to explicitly invoke another
one constructor in the same class. The this keyword is done with another following syntax.

Syntax: - this (args);

Here, „args‟ is an optional set of arguments that may be passed to constructors. The sequence of
type on this argument list determines which form of the constructor is invoked.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 105 II.B.Sc., III Sem Java
(Q). Explain Method Overloading with an example program in Java?

In Java, it is possible to use a method name more than one time for definitions. A method can be
defined with same name but with different parameters list and different definitions.

The process of implementing one method with different number of parameters and different
definitions in a program is called “Method Overloading”. This process is a kind of „Polymorphism‟.

Method Overloading is used when objects are required to work on different parameter lists
similarly or differently. When we call the Overloaded method, Java compiler tries to match the appropriate
method definition which matches the parameter list given in the method call.

To create an overloaded method, we need to provide several different method definitions


with the same name but with different parameter lists. The return type of the method is not considered in
overloading a method. In Java, we can overload instance methods as well as constructor methods of a
class.

The programmer should consider the following three rules to overload a method.

1. All the definition of an overloaded method must be differed either in the number of arguments or
type of arguments.
2. If the number of arguments is same for any two methods definitions, the type of arguments must
be different from each other.
3. If the number and types of arguments are same, the order of the arguments must be differed.

// Example Program of Method Overloading?

import java.util.*;
class Room
{
float length;
float breadth;
float roomArea(float l, float b) // Method accepts two parameters of type 'float'.
{
length = l;
breadth = b;
return length * breadth;
}
int roomArea(int l, int b) // Method accepts two parameters of type 'int'.
{
length = l;
breadth = b;
return (int)length * (int)breadth;
}
float roomArea(float l) // Method accepts one parameters of type 'float'.
{
length = breadth = l;
return length * breadth;
}
Room r1 = new Room();
float a = r1.roomArea(2.5f, 5.5f);
int b = r1.roomArea(2, 5);
float c = r1.roomArea(7.5f);
}
Save: - Room.java
Compile: - D:\Fareed Javaprog> javac Room.java
Run: -D:\Fareed Javaprog> java Room

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 106 II.B.Sc., III Sem Java
Output: - 13.75
10
56.25

The above class „Room‟ has one overloaded method „roomArea()‟ with three different definitions.
The signature of the three methods is as follows.

 float roomArea(float l, float b) // Method accepts two parameters of type 'float'.


 int roomArea(int l, int b) // Method accepts two parameters of type 'int'.
 float roomArea(float l) // Method accepts one parameters of type 'float'

All the above signatures are differed either in number of parameters or type of parameters they accepts.
To use those three methods we have to create one object of the class „Room‟. Now we can call those
methods with different parameter lists as shown below.

Statement 1: - Room r1 = new Room();


Statement 2: - float a = r1.roomArea(2.5f, 5.5f);
Statement 3: - int b = r1.roomArea(2, 5);
Statement 4: - float c = r1.roomArea(7.5f);

The first statement creates an object „r1‟ of class type “Room”.


The second statement invokes the method definition which has two float type parameters in its signature.
The third statement invokes the method definition which has two integer type parameters in its signature.
The fourth statement invokes the method definition which has one float type parameters in its signature.

(Q). Explain Static Variables and Static Methods with an example program in Java?

A Class basically constrains two sections. One declared variables and the other declares methods.
These variables and methods are called instance variables and instance methods. This is because every
time the class is instantiated, a new copy of each of them is created. They are accessed using the objects
(with dot operator).

Static Variables: -

The Variables that are declared inside a class with the keyword “static” are called as “Static
Variables”. These variables are declared with the class scope. Static Variables are used when we want a
variable that is common to all instances of a class. Java creates only one copy for a static variable for the
entire class to which it belongs. Static Variables can also be used without creating an object.

Syntax for Static Variable: - static <data type> <variable name>;

We can also assign a value to a variable for its declaration.

Syntax: - static type varName = expression;

// Illustrate an example program by using the Static Variable in Java?

import java.util.*;
class StaticVar
{
static int count; // Static Variable.
string name; // Non-Static Variable
StaticVar(string n) //Parameterized Constructor.
{
name = n;
++ count ;
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 107 II.B.Sc., III Sem Java
class StaticVarTest
{
public static void main(String args[])
{
StaticVar s1 = new StaticVar("First Number :");
System.out.println(s1.name + " " + s1.count);
StaticVar s2 = new StaticVar("Second Number :");
System.out.println(s2.name + " " + s2.count);
}
}

Save: - StaticVarTest.java
Compile: - D:\Fareed Javaprog>javac StaticVarTest.java
Run: - D:\Fareed Javaprog>java StaticVarTest

Output: - First Number : 1


Second Number : 2

NOTE: - A Static variable can also be accessed without creating any object by using the class name
directly.

Syntax: - <Class Name>.<static variable name>;

Example: - Staticvar.count = 5;

Static Methods: -

The Methods that are declared inside a class with the keyword “static” are called as
“Static Methods”. A Static method can access only static variables and methods; it can not access non-
static members of the class.

Syntax: - static <return type> <method name> (Parameter list)


{
Method body
}
Example: -

import java.util.*;
class StaticMembers
{
static int count; // Static Variable.
int non_st; // Non-Static Variable
StaticMembers() //default Constructor.
{
count++;
}
static void showCount() // Static Method.
{
System.out.println("Count = " + count);
non_st = 100; // Error: Non-Static Variable non_st cannot be referenced from static.
}
}

A Static Method can access another static method for the execution.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 108 II.B.Sc., III Sem Java
Example: -

import java.util.*;
class StaticMember
{
static int count; // Static Variable.
StaticMember() //default Constructor.
{
count++;
}
static void show()
{
showCount();
}
static void showCount() // Static Method.
{
System.out.println("Count = " + count);
}
}

Static methods can also be called even without using the object. They are available to other classes
by their class name.

Example: -

import java.util.*;
class StaticMember
{
static int count; // Static Variable.
StaticMember() //default Constructor.
{
count++;
}
static void showCount() // Static Method.
{
System.out.println("Count = " + count);
}
}

The following statement is used to call the static method “showCount()” without creating any object
to that class.

staticMember.showCount();

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 109 II.B.Sc., III Sem Java
UNIT – III
Chapter 8: Inheritance.

(Q) What is Inheritance explain in types of Inheritances with an example in Java?

Inheritance: - Inheritance is a mechanism to derive a New Class from the Existing Class. Here Existing
Class is a Base class; New class is known as derived class.
(OR)
Inheritance is the property that allows “The reuse of an Existing Class to build a New Class”.
(OR)
Inheritance is the process of acquiring the qualities of one class to another class is called Inheritances.
These qualities include both properties and action of the class. Using inheritances, we extend the features
of a class into another class.

The mechanism of deriving a New Class from an Existing Class can be called as Inheritances. The
Existing Class which is used for creating a New Class is Called Base Class / Parent Class / Super Class and
the newly created class is called Derived Class / Child Class / Sub Class.

Inheritances can represent the “Is-a” Relationship: -

Consider the below figure, Bird is a Base Class and Robin, Swallow, Penguin & Kiwi is a
Derived Class. A Flying & Non-Flying is a inherits from the Bird Class it access a common properties /
attributes like Feathers & Lay Eggs. So Inheritances is a “Is-a” Relationship.

Bird
Attributes
1. Feathers.
2. Lay Eggs.

Flying Bird Non-Flying Bird

Attributes Attributes
…………….. ……………..
……………… ………………

Robin Swallow Penguin Kiwi

Attributes Attributes Attributes Attributes


…………….. …………….. …………….. ……………..
……………… ……………… ……………… ………………

In Java, a class can be subclasses into several classes in the inheritance hierarchy.
Inheritance allows the subclasses to inherit all the variables and methods of their super class.

Types of Inheritance: - Inheritance are mainly divided into 5 types there are

1. Single Inheritance. (Derived from only one Super Class)


2. Multiple Inheritances. (Derived from more than one Super Class)
3. Hierarchical Inheritance. (Derived from Derived Class)
4. Multilevel Inheritance. (One Super class, many sub classes)

NOTE: - Java does not directly implement Multiple Inheritance.


Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 110 II.B.Sc., III Sem Java
1. Single Inheritance: - A Derived a New Class based on the One Exiting Class. But not the constructor
or destructor from its Base Class. It is called as Single Inheritance. Here only one Base Class and its having
only one Derived Class.

A Parent / Super Class Base Class

(OR) Derived from


Only one super class
B Child / Sub Class Derived Class

2. Multiple Inheritances: - Derivation of a class from several Base Classes is called as Multiple
Inheritances. A class can inherit the attributes of two or more classes. This is also known as Multiple
Inheritance. Multiple Inheritances allows us to combine the features of several existing classes.

Derived from more than one


Super class.

(OR)

Base Class 1 Base Class 2 Base Class 3 ……….. Base Class N

Derived Class 1

NOTE: - In Java, it is not possible to derived a new class based on more than one class directly; rather we
use Interfaces to achieved this technique.

3. Multilevel Inheritances: - A Class is Derived from another Derived Class it is called as Multilevel
Inheritances.

Example: -
A Base Class 1 Grand Father Parent Class

(OR)
B Derived Class 1 Father
Intermediate
Class.

C Derived Class 2 Child Child


Class.

Derived from Derived Class.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 111 II.B.Sc., III Sem Java
4. Hierarchical Inheritances: - Deriving multiple classes based on the one Existing Class is called
Hierarchical Inheritances.

Base Class 1
A
(OR)

B C D Derived 1 Derived 2 Derived 3

One Super class, many sub classes.

In Java, a class can be subclasses into several classes in the inheritance hierarchy.
Inheritance allows the subclasses to inherit all the variables and methods of their super class.

Defining Subclasses: -

In Java, the Subclasses can be defined using the keyword “extends” to specify the „super class‟. The
keyword “extends” signifies that the properties of the super class are extended to the subclass. Then the
subclass contains the variables and methods of the super class. In addition to super class members, the
sub class can also have its own variables and methods.

Syntax of Subclass: -
Class <subclasses name> extends <superclass name>
{
Variables Declaration; (or) Data Members;
Methods Declaration;
}

// Illustate the Simple Inheritance program?

import java.util.*;
class Room
{
int length;
int breadth;
Room(int l, int b) // Parameterized Constructor
{
length = l;
breadth = b;
}
int area()
{
return length * breadth;
}
}
class GuestRoom extends Room // GuestRoom Inherits properties from Room Class.
{
int height;
GuestRoom(int l, int b, int h)
{
super(l,b); // Pass Values to Superclasses.
height = h;
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 112 II.B.Sc., III Sem Java
int volume() // Sub Class
{
return length * breadth * height; // Accessing Super Class Members.
}
}
public class SimpleInheritance
{
public static void main (String args[])
{
GuestRoom myRoom = new GuestRoom(10,20,30); // Derived Class Object.
int area = myRoom.area(); // Accessing Super Class Method.
int volume = myRoom.volume(); // Accessing Sub Class Method.
System.out.println("Area = " + area);
System.out.println("Volume = " + volume);
}
}
Save: - SimpleInheritance.java
Compile: - D:\Fareed Javaprog>javac SimpleInheritance.java
Run: - D:\Fareed Javaprog>java SimpleInheritance

Output: - Area = 200


Volume = 6000.

The program defines a class „Room‟ ad extends it to another class „GuestRoom‟. Note that the class
„GuestRoom‟ defines its own data members and methods. The sub class „GuestRoom‟ now includes three
instance variables namely length, breadth and height and two methods are „area‟ and „volume‟.

The Constructor in the derived class uses the „super‟ keyword to pass values that are required by
the base constructor. The statement like:

GuestRoom myRoom = new GuestRoom (10, 20, 30);

Call first the „GuestRoom‟ constructor method, which in turn calls the „Room‟ constructor method by
using the „super‟ keyword.

Finally, the object „myRoom‟ of the subclass „GuestRoom‟ calls the methods „area‟ defined in the
super class was well as the method „volume‟ defined in the subclass itself.

NOTE: - Members access and Inheritances: -

Although a subclass includes all of the members of its superclass, it cannot access private
member variables of a superclass. It is only accessible by other members of its own class. Sub classes have
no access to it.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 113 II.B.Sc., III Sem Java
(Q). Explain the Super keyword with an example in Java?

A class inherits the state and behavior defines by all of its superclass. State it determined by
variables; behavior is determined by methods. Therefore, an object has one copy of every instance variable
defined not only by its class but also by every superclass of its class.

A Static or Instance variable in a subclass may have the same name as a superclass variable. The
variable hides the superclass variable. These two variables may have the same type or different types.

It is possible to access a hidden variable by using the „super‟ keyword. Super has two general forms.

1. First calls the super class constructor.


2. Second is used to access a member of the superclass that has been hidden by member of subclass.

(1). Using Super to call super class constructor : -

A subclass can call a constructor method defined by its superclass by use of the following form of super.

Syntax: - super (parameter list);

 super must be used within a subclass constructor method.


 Super() must always be the first statement executed inside a subclass constructor.

Example: -

import java.util.*;
class Room
{
int l,b;
Room(int x, int y)
{
l = x;
b = y;
}
int area()
{
return (l * b);
}
}
class GuestRoom extends Room // GuestRoom Inherits properties from Room Class.
{
int h;
GuestRoom(int x, int y, int z)
{
super(x,y); // Pass Values to Superclasses.
h = z;
}
int volume() // Sub Class
{
return (l * b * h); // Accessing Super Class Members.
}
}
public class Inheritances
{
public static void main (String args[])
{
GuestRoom myRoom = new GuestRoom(5, 10, 20); // Derived Class Object.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 114 II.B.Sc., III Sem Java
int area = myRoom.area(); // Accessing Super Class Method.
int volume = myRoom.volume(); // Accessing Sub Class Method.
System.out.println("Area = " + area);
System.out.println("Volume = " + volume);
}
}
Save: - Inheritances.java
Compile: - D:\Fareed Javaprog>javac Inheritances.java
Run : - D:\Fareed Javaprog>java Inheritances

Output: - Area = 50
Volume = 100

(2). Second use of Super: -

The Second form of super acts some what like this clause, except it always referees to the
superclass of the subclass on which it is used.

Syntax: - super.member

Here, member can be either a method of instance variable. This is used in most situations in which
member names of a subclass hide members by the same name in the superclass.

Example: -

import java.util.*;
class first
{
int k;
}
class second extends first
{
int k;
second(int a, int b)
{
super.k = a;
k = b;
}
void display()
{
System.out.println("Super Class of K is : " + super.k);
System.out.println("Sub Class of K is : " + k);
}
}
class SuperTest
{
public static void main(String args[])
{
second fareed = new second(1,2);
fareed.display();
}
}
Save: - SuperTest.java
Compile: - D:\Fareed Javaprog>javac SuperTest.java
Run: - D:\Fareed Javaprog>java SuperTest

Output: - Super Class of K is : 1


Sub Class of K is : 2

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 115 II.B.Sc., III Sem Java
NOTE: - In a class hierarchy constructors are called in order of derivation, from super class to sub class.
Since super() must be the first statement executed in a sub class constructor, this order is same whether
or not super() used.

(Q). Explain Method Overriding with an example in Java?

By defining a method in the subclass which is already defined in its superclass is called as
“Overriding Method”.
(OR)
A Method in the subclass that has the same name, same argument and same return type as
a method in the superclass. This is known as “Overriding Method”. The method defined in the subclass is
invoked and executed instated of the one in the superclass. This is known as “overriding”.

In such case, when a call to that method is made using an object of the subclass, then the
method as defined in the subclass in called. Thus, a subclass can override a method defined inside the
super class.

Rules for Overriding a Method: -

1. The name of the Overriding method is same as the method in superclass.


2. The return type of the Overriding method is same as of the method in superclass.
3. The number of argument of the Overriding method is same as the superclass.
4. The method declares „static‟ cannot be overridden but can be re-declared.
5. We cannot Override a method which is declared as „final‟ in the superclass.
6. The invisible methods are can not be Overridden.
7. Constructors cannot be overridden.

NOTE: - When invoking a superclass an Overridden method the „super‟ keyword is used.

// Write a program by using super key in Overridden?

import java.util.*;
class Vehicals
{
public void move()
{
System.out.println("Vehicals can Move");
}
}
class car extends Vehicals
{
public void move()
{
super.move(); // invokes the Super class method.
System.out.println("Car is travailing Vehicle");
}
}
public class OverrideVehicals
{
public static void main(String srgs[])
{
Vehicals a = new Vehicals(); //Vehicals references and Object.
Vehicals b = new car(); // Vehicals references but car object.
a.move(); // Run the method in Vehicals class
b.move(); // Run the method in Car class.
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 116 II.B.Sc., III Sem Java
Save: - OverrideVehicals.java
Compile: - D:\Fareed Javaprog> javac OverrideVehicals.java
Run: - D:\Fareed Javaprog> java OverrideVehicals

Output: - Vehicals can Move


Car is travailing Vehicle.

Compare between Method Overloading and Method Overriding: -

Method Overloading: - It is possible to create methods that have „the same name, but different
parameter list and different definition‟ that is called Method Overloading and it is also called as
“Polymorphism”.

Method Overriding: - A method in „the sub classes that has the same name, same arguments and same
return type as a method in the super classes‟ is known as Method Overriding.

Method Overloading Method Overriding


1. Write two or more methods with the same 1. Write two or more methods with the same
name but with different parameters lists is called name and same parameters lists is called as
as Method Overloading. Method Overloading.
2. Method Overloading is done in the same class. 2. Method Overriding is done in Super and Sub
Classes.
3. In Method Overloading, method return type 3. In Method Overriding, method return type
can be same or different. should be same.
4. Java Virtual Machine (JVM) decided which 4. Java Virtual Machine (JVM) decided which
method is called depending on the different in method is called depending on the data type
the methods. (class) of the object used to call the methods.
5. Method Overloading is one of the ways that 5. Method Overriding is concept is used in
Java implements Polymorphism. Inheritances.

(Q). Define the concepts of Final Classes, Final Variables and Final Methods in Java?

Final Classes: - “A class that cannot be sub classes is called a Final Class”. A class can be declared as
Final Class with the keyword “final”. Declaring a class as final prevent any un-wanted extension to the
class. If any attempt to inherit a final class will cause an error and the compiler will not allowed it.

Syntax for Final Class: - final class <Class Name>


{
Statements;
}

Final Variables: - The Variables that are declares as Final are treated as “Constants” in Java. Once we
defined a value for a final variables, it return same thought-out the program.

Syntax of Final Variable: - final data type <Variable Name> = <Value>;

Example: - final float pi = 3.142;

Final Method: - The methods that are declared as final cannot be Overridden in any of the sub classes
that are derived from a super classes.

Example: - final void showData()


{
Statements;
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 117 II.B.Sc., III Sem Java
Finalizer Method: - A constructor method is used to initialize an object when it‟s declared. This process is
known as “Initialization”. Similarly, Java supports a concept called “Finalization”, which is just opposite to
initialization. This concept also called as the “Destructors” in C++.

The Finalizer method is simply “finalizer()” and can be added to any class. Java calls that method
whenever it is about to reclaim the space for that object.

(Q). Explain Abstract Methods and Abstract Classes with a suitable example in Java?

Abstract Methods: - The method which is declared with the modifier „abstract‟ is called as Abstract
Method. By using abstract method mechanism we makes a method of a class must always be redefined in
its subclasses. It makes Method Overriding compulsory by all the sub classes of a class. An abstract
method contains no functional code (method code).

Syntax of Abstract Method: - abstract <return type> <method name> (Arguments list);

NOTE: - An Abstract method can also be a member of the class but it does not have body.

Example: - abstract class MyAbstract


{
abstract void myAbsMethod(); // Abstract Method
}

Abstract Classes: - A Class that is declared as abstract is called Abstract Class. The class which is having
at least one abstract method must be declared as abstract. The abstract class can not be instantiated; that
is we can not create any objects based on an abstract class. But we can create references to an abstract
class.

An abstract method can have both abstract methods and concrete methods. Any class that extends
an abstract class must implementation all the abstract methods of the abstract super classes.

Syntax of Abstract Classes: - abstract class <Class Name>

// illustrate Example of Abstract Methods and Classes in Java?

import java.lang.*;
abstract class MyClass
{
abstract void Calculate(double x);
}
class Fareed1 extends MyClass
{
void Calculate(double x)
{
System.out.println("Square of X is = " + (x*x));
}
}
class Fareed2 extends MyClass
{
void Calculate(double x)
{
System.out.println("Square Roots of X is = " + Math.sqrt(x));
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 118 II.B.Sc., III Sem Java
class Fareed3 extends MyClass
{
void Calculate(double x)
{
System.out.println("Cube of X is = " + (x*x*x));
}
}
class AbstractMethodsClasses
{
public static void main(String args[])
{
Fareed1 F1 = new Fareed1();
Fareed2 F2 = new Fareed2();
Fareed3 F3 = new Fareed3();
F1.Calculate(5); // Calculate of Square.
F2.Calculate(3); // Calculate of Square Roots.
F3.Calculate(7); // Calculate of Cube Value.
}
}
Save: - AbstractMethodsClasses.java
Compile: - D:\Fareed Javaprog>javac AbstractMethodsClasses.java
Run: - D:\Fareed Javaprog>java AbstractMethodsClasses

Output: -

Square of X is = 25.0
Square Roots of X is = 1.7324678
Cube of X is = 343.0

(Q). Explain different types of Visibility Modifiers available in Java?


(OR)
Explain different types of Access Protection available in Java?

As the name implies, the Access Specifier Controls access to the method. Whatever the
access specifier, other methods in the same class have access to all the methods.

An Access Specifier is a keyword that represents how to access the methods of classes. Java
provides a few access specifiers for controlling the accessibility of the members of a class. Access specifier
broadens or restricts the accessibility of the members to the other classes.

Java support four types of Visibility or Access Specifier are:

 Default.
 Public.
 Private.
 Protected.
A class can use only two access modifiers „Public‟ and „Default‟ whereas a member can use
any one of the four access modifiers. Both the classes and members can have access modifiers to restrict
the usage of the classes and methods.

Before proceeding to explain the different access specifier of Java, let us consider how classes are
organized in Java.

A we know, Java is a true Object-Oriented Programming (OOP) language. Each and every
line of code in Java is written inside a class. Classes are basic structures of any Java program. The Java
Standard Library (JSL) contains numerous built-in classes, providing a number of functionalities. Since
these classes are very large in number they are grouped in packages for the sake of the convenience. The
grouping is done on the basic of the functionality of the class.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 119 II.B.Sc., III Sem Java
(1). Default (friendly access): -

If we mention no access specified before a member of a class, the access specifies is said to be
“Default”. When we don‟t type any access specifier, Java considers a „friendly‟ type access specifier as
„Default‟. The default access specifies has no keyword, but it is commonly referred to as „friendly‟. The
members of a friendly class are accessible to the following classes:

 The Class in which they are defined.


 The Sub classes in the same package.
 Other Classes in the same package.

Syntax of Default: - class <Class Name>


{
Class Definition
}
(2). Public: -

A Class can be defined with the „Global Scope‟ by using the access specifier „public‟ receding the
keyword class in the class definition. The class which is declared as public can be used by any of the code
from anywhere. Members prefixed with the access specify “Public” have the maximum accessibility. The
public members of a class will be automatically inherited by all its sub classes in the same package or any
other packages. The members are accessible to the following classes.

 The Class in which they are defined.


 The Sub classes in the same package.
 Other Classes in the same package.
 The Sub Classes in another package.
 Other Classes in another package.

Syntax of Public: - public class <Class Name>


{
Class Definition
}
(3). Private: -

Private filed enjoy the highest degree of protection. The members that are declare “private‟ have
the minimum accessibility. They are accessible only in the class in which they are defined. No other classes
can access them, thus such members are accessible only to the following classes.

 The Class in which they are defined.

Syntax of Private: - private class <Class Name>


{
Class Definition
}
(4). Protected: -

The member that are declares with the access specifies “Protected” are visible to all the classes and
sub-classes in the same package and also to sub classes in the other packages. The non-sub classes in
other packages can not access the protected methods. The following are the classes which can access
protected members of the classes

 The Class in which they are defined.


 The Sub classes in the same package.
 Other Classes in the same package.
 The Sub Classes in another package.
 Other Classes in another package.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 120 II.B.Sc., III Sem Java
Access level of various Visibility Modifiers: -

Access Modifiers
Public Protected Default Private Private
Access Location (Friendly) Protected
Same Class. Yes Yes Yes Yes Yes
Sub Class in same package. Yes Yes Yes Yes No
Other Class in same package. Yes Yes Yes No No
Sub Class in other package. Yes Yes No Yes No
Non-Sub Class in other package Yes No No No No

NOTE: -
 Sub Class in other package is “with or with out super class reference” is allowed in Public access.
 Sub Class in other package is “we can not use reference variables” is allowed in protected access.

Rules of Thumb: -

 Use “public” if the field is to be visible every where.


 Use “protected” if the field is to be visible every where in the current package only. And also sub
classes in other packages.
 Use “Default” if the filed is to be visible every where in the current package only.
 Use “private protected” if the field is to be visible only in sub class, regardless of packages.
 Use “Private” if the field is not to be visible any where except in its own class.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 121 II.B.Sc., III Sem Java
Chapter – 9
Arrays, Strings and Vectors.

(Q). What is Array? Explain how to Creating an Arrays in Java?

Definition of Arrays: -

“An Array is a group of contiguous or related data items that share a common name”.
(OR)
“Array is defined as Collection of homogeneous elements that share a common name”.
(OR)
“Array is collections of all are Integer or all are Float or all are String / Characters that share
a common name”.

Example: - int 10, 20, 30;


Float 10.5, 20.8, 123.5;
Char F, A, R, I, E, D;

Introduction of Array: -

An Array is a collection of data elements of same type. All the elements in an Array share a
common name and allocated contiguous memory location in the computer‟s memory. Arrays are supported
sequential access and random access.

Creating an Array: -

In Java, All the Arrays are created dynamically; we have no Static Arrays in Java. Like any
other variable, we must declare and create the arrays, the computer memory before they are used.
Creating and using an array involves the following three steps.

1. Declaring of Array.
2. Creation of Array (or) Create Memory location of Array.
3. Initialization of Array (or) Put values into the memory location.

1. Declaration of Arrays: - Like any other variable, we must declare and create the arrays, the computer
memory before they are used it. Declare an array we following the two methods.

Syntax of Declaration of Array: - <Data type> <Array Variable Name> [];


(OR)
<Data type> [] <Array Variable Name>;

Data type
Example (1): - int number [];

Array Variable Name

Example (2): - Float [] marks;

NOTE: - The above statement declares an array „number‟ of type „integer‟. We do not need to specify the
size of the array at the time of declaration.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 122 II.B.Sc., III Sem Java
2. Creation of Array (or) Create Memory location of Array: - After Declaring an Array, we need to
allocate memory locations for an Array. Java allows us to create arrays using “new” operator only.

Syntax for Creation Array: - <Array Variable Name> = new <Data type> [size];

Keyword
Example: - number = new int [5]; Size of Array.
Array Variable Name Data Type

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


average = new float [10];

The above statement allocates memory for the array variables „number and average‟ with 5, 10
indexed variables of type are „int and float‟. This array occupies 30 bytes (10 + 20 = 30 bytes), because 2
bytes for each of the indexed variables.

In Java, the memory is allowed allocated for the arrays in continuous memory locations. It is also
possible to combine the two steps “Declaration and Creation” into one as show below:

Int number [] = new int [5];

Statement Results

Int number []; Point now where // Declaration of Array

number

number = new int [5];

Points to „int‟ object // Create Memory Location.

number [0]
number [1]
number [2]
number [3]
number [4]

After allocating the memory for the entire array, now it is ready to use like any other
ordinary variables. Each elements of the array can be accessed using an index values along with the array
variable name. The index value must be an integer value.

3. Initialization of Array (or) Put values into the memory location: - Assigning data values into
arrays is called Initialization of Array. The final step is to put values into the array created. This is done
using array subscripts as shown below.

Syntax of Initialization Array: - Array Name [Subscript] = value;

Example: - number [0] = 94;


number [1] = 95;
number [2] = 98;
number [3] = 99;
number [4] = 98;

We can also initialize arrays automatically in the same way as the ordinary variables when they are
declared, as shown below.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 123 II.B.Sc., III Sem Java
Syntax of Initialization Array: - <Data type> <Array Name>[]= {List of values};

Example: - int numbers [] = {94, 95, 98, 99, 98};

The array initialize is a list of values separated by commas and surround by curly braces.

NOTE: - Here we did not specify any size, the Java Compiler allocates enough memory to hold all the data
values given in the list.

Example: - int add [][] = {{20,10},{15,20}};

The above initialization statement initializes the array „add‟ with 4 values. Java Virtual Machine
(JVM) allocates memory for the array with 2 rows and 2 columns and placed the values at appropriate
positions.

(Q). What is Array? Explain different types of Arrays in Java?

Definition of Arrays: -

“An Array is a group of contiguous or related data items that share a common name”.
(OR)
“Array is defined as Collection of homogeneous elements that share a common name”.
(OR)
“Array is collections of all are Integer or all are Float or all are String / Characters that share
a common name”.

Example: - int 10, 20, 30;


Float 10.5, 20.8, 123.5;
Char F, A, R, I, E, D;

Introduction of Array: -

An Array is a collection of data elements of same type. All the elements in an Array share a
common name and allocated contiguous memory location in the computer‟s memory. Arrays are supported
sequential access and random access

For instance, we can define an Array name “Marks” to represent a set of salaries of a group of
employees.

Syntax: - Data type <Array Name> [Size of Array];

Array Name;
Example: - int Marks [5];

Data type Size of the Array

Here a particular value is indicated by writing a number called “Index” or “Subscript” in brackets
after Array name. The individual values are called as elements.

Each element in an array is called as an indexed variable, we can declare an array of the type, size
and dimension. “The number of indexed variables in an array is equivalent to the maximum size of the
array”. Each element in the array can be accessed using an index or subscript value. In Java, the index
value starts at 0‟s (Zero‟s) and ends at „n-1‟. Where „n‟ is the maximum size of the array.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 124 II.B.Sc., III Sem Java
Marks Array Name

Marks [0] 0
Marks [1] 1
Size of Array
Subscripted / Indexed Marks [2] 2
Marks [3] 3
Marks [4] 4

Defines an array by the name Marks that can hold a maximum of the five elements. The individual
elements of an array are accessed and manipulated using the array name followed by their index. The
Marks stored in the first subject is accessed as Marks [0] and the Marks scored in the 5 th
Subject as Marks [4]. In Java, the index value starts at 0‟s (Zero‟s) and ends at „n-1‟. Where „n‟ is the
maximum size of the array. In this case, a sequence of five integers representing the Marks stored one
after another in memory.

Based on the number of dimensions, we can categories an Array into the following types

1. Single / One Dimensional Array.


2. Multi / Two Dimensional Arrays.

1. Single / One Dimensional Array: -

One-Dimensional Arrays represented individual elements in only one dimensional either “Row Wise”
or either “Column Wise”.

“A list of items can be given one variable name using only one subscript and such a
variable is called a single subscripted variable or a one dimensional array”. In mathematics, we often deal
with variables that are single subscription. For instance, we use the equation.
n
∑ Xi
A= i - 1
n
To calculate the average of „n‟ variable of „X‟. The subscripted variable „Xi‟ refers to the „I th‟
element of „X‟. In Java, single subscripted variable „Xi‟ can be expressed as X[1], X[2], X[3],……. X[n].

In Java, Array is objects that store multiple variables of the same type. To declare an Array, we use
„new‟ operator for memory allocation.

Syntax: - Data type <Array Variable Name> [] = new Data type [Maximum Size];

Data type
Example: - int Marks [] = new int [5 ];
Maximum Size.
Data type Array Keyword
Variable

For example, if we want to represent a set of five subject marks, say {94, 95, 98, 99, 98} by an
array variable numbers, then we may create the variable number as follows.

Data type
Example: - int Marks [] = new int [5 ];
Maximum Size.
Data type Array Keyword
Variable

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 125 II.B.Sc., III Sem Java
The values to the array elements can be assigned as followed.

Marks [0] = 94;


Marks [1] = 95;
Marks [2] = 98;
Marks [3] = 99;
Marks [4] = 98;
Int Marks [] = new int[5];
The above declaration declares an array “Marks” of type „int‟ to hold 5 values of type integer. Each indexed
variable of the above array can be accessed using one subscript value ranges from 0 to 4.

This would cause the array number to store the value shown as follows:

Marks [0] = 94
Marks [1] = 95
Marks [2] = 98
Marks [3] = 99
Marks [4] = 98

// Illustrate the Sorting Program by using Arrays in Java?

import java.lang.*;
class NumberSorting
{
public static void main(String args[])
{
int number[] = {55,67,24,73,89};
int n = number.length;
System.out.println("Given List is : ");
for(int i=0; i<n; i++)
{
System.out.print(" " + number[i]);
}
System.out.println("\n");
for(int i=0; i<n; i++)
{
for(int j=i+1; j<n; j++)
{
if(number[i]<number[j])
{
int temp = number[i];
number[i] = number[j];
number[j] = temp;
}
}
}
System.out.print("Sorted List is : ");
for(int i=0; i<n; i++)
{
System.out.print(" " + number[i]);
}
System.out.println(" ");
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 126 II.B.Sc., III Sem Java
Save: - NumberSorting.java
Compile: - D:\Fareed Javaprog>javac NumberSorting.java
Run: - D:\Fareed Javaprog>java Number Sorting

Output: -

Given List is: 55 67 24 73 89


Sorted List is : 89 73 67 55 24

2. Multi / Two Dimensional Arrays: -

Multi-Dimensional Array is used to represented data values in the form of rows and columns. When
an array has more than one dimension it is called as “Multi-Dimensional” Array.

Since a Multi-Dimensional array has two dimensions, we use two subscript values one for column
and another row to access each individual indexed variables of the array.

Syntax of Multi-Dimensional Array: -

<Data type> <Array Variable Name> [][] = new <Data type> [Size1][Size2];

Here Size1 represented the number of rows and Size2 represented the number of Columns of the array.

In Mathematics, we represent a particular value in a matrix by using two subscripts as “V i,j”.


Here denotes the entire matrix “Vi,j” refers to the values in the ith row and jth column.

Keyword Data type

Example: - int matrix [] [] =new int [3] [3];

Data type Array Variable ith jth


Name row column.

The above declaration declares an Array “matrix” of type with two dimensions to have 3 rows and
3 columns. Each elements of the above Array can be accessed by using two subscripts values.

Column 0 Column 1 Column 2


Row 0 [0][0] [0][1] [0][2]
Row 1 [1][0] [1][1] [1][2]
Row 2 [2][0] [2][1] [2][2]

The memory for the above declares array is allocated in contiguous memory locations as shown below.

Column 0 Column 1 Column 2


Row 0 [0][0] [0][1] [0][2] Matrix[0][0] = 310
310 275 365 Matrix[0][1] = 275
Row 1 [1][0] [1][1] [1][2] Matrix[0][2] = 365
210 190 325 Matrix[1][0] = 210
Row 2 [2][0] [2][1] [2][2] Matrix[1][1] = 190
260 300 380 Matrix[1][2] = 325
Matrix[2][0] = 260
Matrix[2][1] = 300
Matrix[2][2] = 380

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 127 II.B.Sc., III Sem Java
Variable Size of Array: - Java treats multi-dimensional arrays as “Arrays of Arrays”. With this facility we
can have arrays with different lengths in the dimension of the arrays.

Example: - if it possible to declare a two dimensional array as follows:

int x[][] = new int [3][];


x [0] = new int [2];
x [1] = new int [4];
x [2] = new int [3];

These statements create a two dimensional array as having different lengths for each row as shown:

X [0] 0 1 x[0][1]

X [1] 0 1 2 3 x[1][3]

X [2] 0 1 2 x[2][2]

// Illustrate the Multiplication program by using Multi-Dimensional Arrays in Java?

import java.lang.*;
class MultiTables
{
final static int ROWS = 10;
final static int COLUMNS= 10;
public static void main(String args[])
{
int product[][] = new int [ROWS][COLUMNS];
int row,column;
System.out.println("Multiplication of Table :");
System.out.println(" ");
int i,j;
for(i=0; i<ROWS; i++)
{
for(j=1; j<COLUMNS; j++)
{
product[i][j] = i*j;
System.out.print(" " + product[i][j]);
}
System.out.println(" ");
}
}
}

Save: - MultiTables.java
Compile: - D:\Fareed Javaprog> javac MultiTables.java
Run: - D:\Fareed Javaprog> java MultiTables

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 128 II.B.Sc., III Sem Java
Output: -

Multiplication of Table.

1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100

(Q). What is String? Explain the details of Stings with an example in Java?

Definition of String: - “A Sting is a sequence of characters that is formed using a alphabets”. Each
character in a string is a 16-bit Unicode characters in Java. The sequence of characters can be represented
as a character array or an object of the class String. Each character can be accessed using an index value.
The index value of the string expression start at 0 (Zero).

Example: - char MyName[] = new char[6];


MyName[0] = „F‟;
MyName[1] = „A‟;
MyName[2] = „R‟;
MyName[3] = „E‟;
MyName[4] = „E‟;
MyName[5] = „D‟;

In Java, strings are object and implemented using two classes namely „String‟ Class and
„StringBuffer‟ Class.

1. String Class.
2. StringBuffer Class.

(1). Class String: - A Java string is an insatiate object of the „String Class‟. We can represent a series of
characters using an object of the class „String‟. A Java String Class is not a character array and is not NULL
terminated.
String stringName;
Declared a String Class: - stringName = new String (“string”);

Example: - String firstName;


firstName = new String (“Mohammad”);

These two statements may be combined as follows: string firstName = new String (“Mohammad”);

Creating String using String Class: - We can create strings using the class „String‟ in several ways.
„String‟ Class provides several constructors to build an object of the class „Sting‟.

 String s = “Mohammad Fareed”; String


Object
Mohammad Fareed
S

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 129 II.B.Sc., III Sem Java
We can directly assign the string expressions to the reference of the class String. Then Java Victual
Machine (JVM) creates objects of the type String with the given content and assigned the references to the
references variables.

 String s = new String (“Shaik Mohammad Fareed”);


String
Object
Shaik Mohammad Fareed
S

We can create an object of the class String and assign the reference to the reference of the class by
using the constructor which accepts parameters of type string.

 char name[] = {„M‟, „o‟, „h‟, „a‟, „m‟, „m‟, „a‟, „d‟, „F‟, „a‟, „r‟, „e‟, „e‟, „d‟};
String s = new String(name); String
Object
Mohammad Fareed
S

We can create an object of the class String and assign the reference to the reference of the class by
using the constructor which accepts a parameter of type „char‟ array.

String Concatenations: - String processing involves dealing with strings. String manipulation is the most
common part of many Java programs. The primary operation for combining Strings is called
Concatenations. We can append one string with another by using the operator „+‟.

Example: - String one = new String (“Shaik”);


String two = new String (“Mohammad Fareed”);
one = one + two;
System.out.println(one);
Mohammad Fareed
two

Shaik

one
Mohammad Fareed

In above example, the string objects „one‟ is concatenated with another string object „two‟.
Now, the content of the object „one‟ becomes the string values after appending the content of „two‟.

String Arrays: - Like any other array, we can also create String arrays to have multiple string objects. In
this case Java Virtual Machine (JVM) creates arrays of objects of the class String and holds individual
references in appropriate indexed variables.

Syntax: - Sting stringName [] = new String[size of sting];

Example: - String MyName[] = {“Shaik”, “Mohammad”, “Fareed”};


for(int i = 0; i < MyName.length; i++)
System.out.println(MyName[i]);

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 130 II.B.Sc., III Sem Java
Example: - String MyName[] = new String[3];
MyName[0] = “Shaik”;
MyName[1] = “Mohammad”;
MyName[2] = “Fareed”;
for (int i = 0; i < MyName.length; i++)
System.out.println(MyName[i]);

Shaik
MyName[0]

MyName[1] Mohammad

MyName[2] Fareed

Methods of String Class: - The String Class defines a number of methods that allow us to accomplish a
variety of string manipulation tasks. The below lists some of the most commonly used String methods.

String Method Call Task Perform


S2 = S1.toLowerCase; Convert the String S1 to all Lowe cases.
S2 = S1.toUpperCase; Convert the String S1 to all Upper cases.
S2 = S1.replace(„x‟ , „y‟); Replace all appearances of „X‟ with „Y‟.
S2 = S1.trim(); Remove with spaces at the beginning and end of the String S1.
S1.equal(S2) Return „True‟ if S1 is equal to S2.
S1.equalIgnoreCase(S2) Return „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 S1<S2, Positive id S1>S2, and Zero if S1 is equal S2.
S1.concate(S2) Concatenates S1 and S2.
S1.substring(n) Given Substring starting from nth character.
S1.substring(n, m) Given 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) Convert the parameter value to string representation.

// illustrate the Alphabetical ordering of strings by using String class in Java?

import java.lang.*;
class StringOrdering
{
static String name[] = {"Shaik", "Mohammad", "Fareed", "MCA"};
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++)
{

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 131 II.B.Sc., III Sem Java
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]);
}
}
}
Save: - StringOrdering.java
Compile: - D:\Fareed Javaprog>javac StringOrdering.java
Run: - D:\Fareed Javaprog>java StringOrdering

Output: -
Fareed
MCA
Mohammad
Shaik

// Program using length(), charAt() and indexOf().

import java.lang.*;
class Stringprog
{
public static void main(String args[])
{
String str ="MOHAMMAD FAREED";
System.out.println(str);
System.out.println("The String Contains " + str.length() + " Letters.");
System.out.println("The Character at Index of 7 : " + str.charAt(7));
System.out.println("The Index of the Character 'E' is : " + str.indexOf('E'));
}
}
Save: - Stringprog.java
Compile: - D:\Fareed Javaprog>javac Stringprog.java
Run: - D:\Fareed Javaprog>java Stringprog

Output: -

MOHAMMAD FAREED
The String Contains 15 Letters.
The Character at Index of 7 : D
The Index of the Character „E‟ is : 12

// Program of using Substring()

import java.lang.*;
class SubStrings
{
public static void main(String args[])
{
String str ="MOHAMMAD FAREED";

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 132 II.B.Sc., III Sem Java
System.out.println(str);
System.out.println("The Sub String from Index 0 to index 8 is : " + str.substring(0,8));
System.out.println("The Sub String from Index 8 to end is : " + str.substring(8));
}
}
Save: - SubStrings.java
Compile: - D:\Fareed Javaprog>javac SubStrings.java
Run: - D:\Fareed Javaprog>java SubStrings

Output: -
MOHAMMAD FAREED
The Sub String from Index 0 to index 8 is : MOHAMMAD
The Sub String from Index 8 to end is : FAREED

// Program changing the case using to lowercase() to uppercase() and “+” Concats?

import java.lang.*;
class StringLowertoUpper
{
public static void main(String args[])
{
String MyName ="Mohammad Fareed MCA.,IRPM.";
System.out.println(MyName);
String low = MyName.toLowerCase();
String up = MyName.toUpperCase();
System.out.println(low);
System.out.println(up);
String first = " Shaik ";
String last = "Muneer Pasha";
System.out.println(first + last);
String name = "Mr. ".concat(first + last);
System.out.println(name);
}
}
Save: - StringLowertoUpper.java
Compile: - D:\Fareed Javaprog>javac StringLowertoUpper.java
Run: - D:\Fareed Javaprog>java StringLowertoUpper

Output: -
Mohammad Fareed MCA.,IRPM.
mohammad fareed mca.,irpm.
MOHAMMAD FAREED MCA., IRPM.
Shaik Muneer Pasha.
Mr. Shaik Muneer Pasha.

// Program for locating a character using indexOf() and lastIndexOf()?

import java.lang.*;
class StringIndexOf
{
public static void main(String args[])
{
String MyName ="Mohammad Fareed MCA.,IRPM.";
System.out.println(MyName);
int x = MyName.indexOf("d");
System.out.println("The First Index of 'd' is : " + x);

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 133 II.B.Sc., III Sem Java
int y = MyName.lastIndexOf("d");
System.out.println("The Last Index of 'd' is : " + y);
}
}
Save: - StringIndexOf.java
Compile: - D:\Fareed Javaprog>javac StringIndexOf.java
Run: - D:\Fareed Javaprog>java StringIndexOf

Output: -
Mohammad Fareed MCA.,IRPM.
The First Index of 'd' is : 7
The Last Index of 'd' is : 14

// Program for replacing characters in a string using replace()?

import java.lang.*;
class StringReplace
{
public static void main(String args[])
{
String MyName ="Mohammad Fareed MCA.,IRPM.";
System.out.println(MyName);
System.out.println(MyName.replace('F', 'S'));
System.out.println(MyName);
}
}
Save: - StringReplace.java
Compile: - D:\Fareed Javaprog>javac StringReplace.java
Run: - D:\Fareed Javaprog>java StringReplace

Output: -
Mohammad Fareed MCA.,IRPM.
Mohammad Sareed MCA.,IRPM.
Mohammad Fareed MCA.,IRPM.

(2). StringBuffer Class: - StringBuffer is a peer class of String. We can also create String using the class
StringBuffer the use of object of type StringBuffer foe the „manipulation of strings‟. StringBuffer creates
string of “Flexible length that can be modified in terms of both length and content (data)”. We can insert
characters and substrings in the middle of a string, or append another string to the end.

 While String creates string of “Fixed length”.


 StringBuffer creates string of “Flexible length that can be modified in terms of both length and
content (data)”.

Creating Strings using StringBuffer: - We can create a string by using the constructor of the class
StringBuffer by passing one string type argument.

Syntax for StringBuffer: - StringBuffer stringName = new StringBuffer (“Passing Arguments”);

Example: - StringBuffer MyName = StringBuffer (“Mohammad Fareed”);

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 134 II.B.Sc., III Sem Java
Methods of StringBuffer: - StringBuffer class supports several methods to support string manipulation
operations.

StringBuffer Methods Task Performs


append(str) Appends the string to the object.
charAt(n) Return the character at index position in start from 0 (Zero).
delete(m,n) Deletes the characters from „m‟ to „n‟ position.
delectCharAt(n) Deletes the characters at given index positions „n‟.
indexof(str) Returns the starting index position of the given string.
length() Return the length of the string.
replace(m, n, str) Replace the positions from „m‟ to „n‟ with given string.
reverse() Reverse the content of the string.
setCharAt(i, c) Sets the given character „c‟ at index position „i‟
insert(n, str) Inserts given string at position „n‟.
setLength(n) Sets the length of the string to given „n‟.

// illustrate the Manipulation of String by using StringBuffer in Java?

import java.lang.*;
class StringManipulation
{
public static void main(String args[])
{
StringBuffer MyName = new StringBuffer("Mohammad Fareed");
System.out.println("Original String : " + MyName);
System.out.println("Length of String : " + MyName.length()); // Obtaining String Length.
for(int i=0; i<MyName.length(); i++) // Accessing characters in a String.
{
int p = i+1;
System.out.println(("Character at Position : " + p + " is : " + MyName.charAt(i)));
}
String aString = new String(MyName.toString()); // Inserting a string in the middle
int pos = aString.indexOf("Fareed" );
MyName.insert(pos, " Shaik ");
System.out.println("Inserting Middle of String is : " + MyName);
MyName.setCharAt(8, '-'); // Modifying a character.
System.out.println("Modified New String Now : " + MyName);
MyName.append(" MCA,IRPM."); // Appending a string at the end.
System.out.println("Appended String at End : " + MyName);
}
}

Save: - StringManipulation.java
Compile: - D:\Fareed Javaprog>javac StringManipulation.java
Run: - D:\Fareed Javaprog>java StringManipulation

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 135 II.B.Sc., III Sem Java
Output: -

Original String : Mohammad Fareed


Length of String: 15
Character at Position : 1 is : M
Character at Position : 2 is : 0
Character at Position : 3 is : h
Character at Position : 4 is : a
Character at Position : 5 is : m
Character at Position : 6 is : m
Character at Position : 7 is : a
Character at Position : 8 is : d
Character at Position : 9 is :
Character at Position : 10 is : F
Character at Position : 11 is : a
Character at Position : 12 is : r
Character at Position : 13 is : e
Character at Position : 14 is : e
Character at Position : 15 is : d
Inserting Middle of String is : Mohammad Shaik Fareed.
Modified New String Now : Mohammad – Shaik Fareed.
Appended String at End : Mohammad – Shaik Fareed MCA,IRPM.

Differences between String Class and StringBuffer Class: -

“A Sting is a sequence of characters that is formed using a alphabets”. Each character in a string is a 16-bit
Unicode characters in Java.

In Java, strings are object and implemented using two classes namely „String‟ Class and
„StringBuffer‟ Class.

String Class: -

 When we need to create “Fixed length String”, we use the class String to create an object of String.

 The Content (Data) of an object of type String can not be changed once it is defined. This property
makes the objects of String class as “Immutable”.

Example: - String MyName;


MyName = new String (“Mohammad Fareed”); // Creates a new String.
MyName.toLowerCase(); // No effect.
MyName.concate(“MCA”); // No Results.
MyName = MyName.UpperCase(); // New object will be created and MyName refers to
The New object.

Mohammad Fareed
MyName

MOHAMMAD FAREED
MyName

In the above example, we created an object „MyName‟ of type String with the content „Mohammad
Fareed‟. The statement „MyName.toLowerCase();‟ will not change the content of the object, rather it
creates a new object but no reference is there. Similarly in the statement „MyName.concat(“MCA”);‟ also
the same thing. The statement „MyName = MyName.UpperCase();‟ creates a new object with the content
“MOHAMMAD FAREED” and changes the „MyName‟ reference to the new object.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 136 II.B.Sc., III Sem Java
StringBuffer Class: -

 StringBuffer creates string of “Flexible length that can be modified in terms of both length and
content (data)”.

 StringBuffer is a peer class of String. We can also create String using the class StringBuffer the use
of object of type StringBuffer foe the „manipulation of strings‟. StringBuffer creates string of
“Flexible length that can be modified in terms of both length and content (data)”. We can insert
characters and substrings in the middle of a string, or append another string to the end.

 The Content (Data) of an object of type StringBuffer can be changed easily; this flexibility makes
the objects of StringBuffer class as “Mutable”.

Example: - StringBuffer MyName; // Create a references.


MyName = new StringBuffer (“Shaik”); // Creates an object.
MyName.append(“Mohammad Fareed”); // Changes the content of the object.
MyName.reverse(); // Changes the content of the object.

Shaik

MyName Mohammad Fareed

deeraF dammahoM

(Q). What is Vector? Explain concepts of Vectors with suitable examples in Java?

Introduction: -
Collection classes are used to process the objects creates in the program. While we process
the objects, we do the following things frequently.

1. Add Objects to all the Collections.


2. Search for an Object in the Collections.
3. Retrieve an Object from the Collections.
4. Iterate through the Collections, looking at each object on after another.
5. Remove the Objects from the Collections.

The Collections of Application Programming Interface (API) consists of a group of interfaces


and classes which are used as for processing objects. Each interface and class has its own unique
characteristics which help the programmer for the manipulation of objects.

Example: - Interfaces: Collection, Set, List, Maps etc.


Classes: Vector, HashSet, Hashtable, ArrayList, LinkedList.

Definition of Vector: -

“Vector class is used to create a generic and dynamic array which is known as Vector”. An
array of type vector can hold objects any type and any number. The Objects do not have to be
homogeneous. The objects that are placed inside a Vector array need not be of same type. “The Class
Vector implements the interfaces Collections and List. It provides various methods for object manipulation.
This Vector class is available in “java.util” package.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 137 II.B.Sc., III Sem Java
<<Interface>>
Collections

<<Interface>>
List

Vector

Creating Vector: -
We can create Vectors like arrays as follows. Here we create the objects Vector class by using
the constructors of the class.

Syntax: - Vector v = new Vector(); // Vector Declaration without any size.


Vector list = new Vector(5); // Vector Declaration with sizes of 5.

NOTE: - The Vector can be declared without specifying any size explicitly. A Vector can accommodate an
unknown number of items. Even, when a size is specified, this can be overlooked and a different number of
items may be put into the Vector. Remember, in contrast, an array must always have its size specified.

Advantages of Vectors: -

1. Vectors are convenient to store objects.


2. Vectors can be used to store variables sized objects.
3. We can add and deleted objects from the list as and when we required.

Disadvantages of Vectors: -

1. We can store data values of simple datatypes directly in a vector.


2. Each data value of any simple datatypes must be converted into a class type.
3. Creating objects to store simple data values take more memory and time.
4. Storing and retrieving of objects in a vector is more complex compared to arrays.

Vector Methods: - Vector class objects support various methods for the manipulation of the objects inside
it.

Vector Methods Task Perform


list.add(obj) Add the object to the Vector at the end of the list.
list.add(p, obj) Add the object to the vector at given position.
list.addElement(obj) Adds the object to the vector at the end of the list.
list.clear() Clear the list.
list.contains(obj) Checks whether te object is in the list or not.
list.copyInto(arr) Copies the list into an array.
list.firstElement() Returns the first elements from the list.
list.indexOf(obj) Returns the index position of the object.
list.insertElementAt(obj, p) Insert the object at a given position „p‟.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 138 II.B.Sc., III Sem Java
// Program working with Vectors and Arrays in Java?

import java.util.*;
class NamesofVectors
{
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("Shaik", 0);
list.insertElementAt("Fareed", 2);
int size = list.size();
String listArray[] = new String[size];
list.copyInto(listArray);
System.out.println("List of Names : ");
for(int i=0; i<size; i++)
{
System.out.println(listArray[i]);
}
}
}
Save: - NamesofVectors.java
Compile: - D:\Fareed Javaprog>javac NamesofVectors.java

Output: -
Test Data (1): -
Run: - D:\Fareed Javaprog>java NamesofVectors Mohammad MCA.
List of Names:

Shaik
Mohammad
Fareed
MCA.

Output: -
Test Data (2): -
Run: - D:\Fareed Javaprog>java NamesofVectors Mohammad MCA. Lecture Computers Department.
List of Names:

Shaik
Mohammad
Fareed
MCA.
Lecture
In
Computers
Department.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 139 II.B.Sc., III Sem Java
(Q). Explain difference between Arrays and Vectors in Java?

Arrays: - An Array is a collection of data elements of same type. All the elements in an Array share a
common name and allocated contiguous memory location in the computer‟s memory. Arrays are supported
sequential access and random access.

Vectors: - Vector class is used to create a generic and dynamic array which is known as Vector. An array
of type vector can hold objects any type and any number. The objects that are placed inside a Vector array
need not be of same type. “The Class Vector implements the interfaces Collections and List. It provides
various methods for object manipulation.

Arrays Vectors
1. Array is Homogenous Elements. 1. Vectors can handle Heterogeneous Elements.
2. Arrays are convenient to store Primary 2. Vectors are convenient to store objects (User
Datatypes Values. Defined Classes).
3. The size of Array is Fixed. 3. The size of Vectors is not fixed (Variable length).
4. Single Threads of Arrays are faster. 4. Single Threads of Vectors are slow.
5. Multiple Threads of Arrays are slow. 5. Multiple Threads of vectors are fast.
6. Adding the objects at the end of an Array 6. Adding the objects at the any position is very
is easy. But, inserting and deleting the easy. We have re-arranged all the elements of
elements in the middle of the array is the Vectors.
Difficult.
7. Retrieving the elements from an array is 7. Retrieving the elements from an Vectors is
easy. complex.

(Q) Explain the Concepts of Wrapper Classes with an example in Java?

In Object-Oriented Programming, every element is treated as objects. We can not process primitive
type values directly. So each primitive value must be converted into object. For this we use the feature of
Wrapper classes provided by Java.

Primitive values in Java are not objects. In order to manipulate these values as objects, the
Java language package provides a Wrapper class for each of the primitive data type. Wrapper classes are
part of the “java.lang package”. For each primitive there is a Wrapper classes in Java.

For Example the wrapper class „Integer‟ class is used to wrap a value of type primitive „int‟. The
following is the list of Wrapper class‟s associates with each primitive type.

Primitive Type Wrapper Class


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

Creating Wrapper Objects: -

We can use objects of the type wrapper classes to wrap primitive values. All the wrapper
classes represented of the type being constructor.

Example: - Integer intobj = new Integer(i) // Primitive integer to Integer Object.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 140 II.B.Sc., III Sem Java
 Converting Primitive Numbers to Object Numbers using Constructor Methods.

Constructor Calling Conversion Action


Integer intobj = new Integer(i) Primitive integer to Integer Object.
Float floatobj = new Float(f) Primitive float to Float Object.
Double doubleobj = new Double(d) Primitive double to Double Object.
Character charobj = new Character(„C‟) Primitive character to Character Object.
Boolean boolobj = new Boolean(flag) Primitive boolean to Boolean Object.

 Converting Object Numbers to Primitive Numbers using type Value() Methods: -

We use this method when we need to convert a value of a wrapped numeric to a primitive.
Each wrapper class provides a method type Value(), where „type‟ represented its data type. This method
converts an object type to its primitive‟s type.

Example: - int i = intobj.intValue() // Object to Primitive Integer.

Method Calling Conversion Action


char c = charobj.charValue() Object to Primitive Character.
boolean flag = boolobj.booleanValue() Object to Primitive Boolean.
int i = intobj.intValue() Object to Primitive Integer.
float f = floatobj.floatValue() Object to Primitive Float.
long l = longobj.longValue() Object to Primitive Long.
double d = doubleobj.doubleValue() Object to Primitive Double.

 Converting Numbers to String using toString() Methods: -

We use this method to convert Numeric Primitives into String objects. Each wrapper class
provides this method. The method is defined as static method in all the wrapper classes.

Example: - int i = 10;


float f = 3.143f;
String str = Integer.toString(i); // Converts Primitives „i‟ into String.
String str = Flaot.toString(f); // Converts Primitives „f‟ into String.

Method Calling Conversion Action


str = Integer.toString(i) Primitive Integer to String.
str = Float.toString(f) Primitive Float to String.
str = Double.toString(id) Primitive Double to String.
str = Long.toString(l) Primitive Long to String.
str = Character.toString(„c‟) Primitive Character to String.
str = Boolean.toString(flag) Primitive Boolean to String.

 Converting String Object to Numbers object using Static Method valueOf() : -

This method is used to build a wrapper object. It is defined as static in all the wrapper
classes. It accepts arguments of type String of the appropriate type.

Example: - Double d;
d = Double.valueOf(“9885712847.007”);
Float f;
f = Folat.valueOf(“94912.02987f”);

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 141 II.B.Sc., III Sem Java
Method Calling Conversion Action
Int obj = Integer.valueOf(str) Converts String to Integer object.
float obj = Float.valueOf(str) Converts String to Float object.
long obj = Long.valueOf(str) Converts String to Long object.
double obj = Double.valueOf(str) Converts String to Double object.
char obj = Character.valueOf(str) Converts String to Character object.

 Converting Number String Object to Primitive Numbers using parseType() method: -

Parsing methods are used to convert a value of type String into Primitive type values. This
method is defined as static in all the wrapper classes except Character class.

Example: - int i = Integer.parseInt(str);


float f = Folat.parseFlaot(“987.9491f”);

Method Calling Conversion Action


int i = Integer.parseInt(str) Converts String to Primitive Integer.
float f = Folat.parseFlaot(str) Converts String to Primitive Float.
long l = Long.parseLong(str) Converts String to Primitive Long.
double d = Double.parseDouble(str) Converts String to Primitive Double.

// Program on Wrapper Classes in Java?

import java.io.*;
class WrapperInterest
{
public static void main(String args[])
{
Float pamount = new Float(0); //Converting Number to Object.
Float irate = new Float(0);
int nyears =0;
try
{
DataInputStream in = new DataInputStream(System.in);
System.out.flush();
System.out.print("Enter the Principal Amount : ");
System.out.flush();
String principal = in.readLine();
pamount = Float.valueOf(principal); // String object to Number Object.
System.out.print("Enter the Interest Rate : ");
System.out.flush();
String interest = in.readLine();
irate = Float.valueOf(interest);
System.out.print("Enter the Number of Years : ");
System.out.flush();
String years = in.readLine();
nyears = Integer.parseInt(years); // Numeric String into Number Object.
}
catch (IOException e)
{
System.out.println("I/O Error");
System.exit(1);
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 142 II.B.Sc., III Sem Java
float Tvalue = loanamount(pamount.floatValue(),irate.floatValue(),nyears);
System.out.println(" Total Value = " + Tvalue);
}
static float loanamount(float p, float r, int n)
{
int y = 1;
float s = p;
while(y<=n)
{
s = s*(1+r);
y = y+1;
}
return s;
}
}

Save: - WrapperInterest.java
Compile: - D:\Fareed Javaprog>javac WrapperInterest.java
Run: - D:\Fareed Javaprog>java WrapperInterest

Enter the Principal Amount : 5000


Enter the Interest Rate : 0.34
Enter the Number of Years : 5
Total Value = 21602.004

(Q) Explain the Enumerated data type with an example?

Java supports a special feature called „Enumerated‟ types call „enum‟.

 Enumerated data type is used to restrict to take on variables that come from a specified set of
values.
 J2SE 5.0 allows using the enumerated type in Java using the „enum‟ keyword.
 This keyword can be used similar that „static final‟ constants in the earlier versions.

Example: - For example earlier versions can use this concept (static final) as like shown below:

public static final int Sunday =0;


public static final int Monday =1;
public static final int Tuesday =2;
public static final int Wednesday =3;
public static final int Thursday =4;
public static final int Friday =5;
public static final int Saturday =6;

Using the enumerated type feature provided by J2SE 5.0, the above code rewritten as:

public enum Day{Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};

Syntax of enum: - <Access Modifier> enum <Name of enum>{Set of values};

Example: - public enum MyNames{Shaik Mohammad Fareed MCA IRPM};

 Here the access modifier may be any of the access modifiers (public, private, protected) available in
Java.
 The „enum‟ is the keyword.
 The Name of the enumerated type may be any valid Java Identifier.
 The Set of values inside the braces are valid Java identifiers separated by commas.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 143 II.B.Sc., III Sem Java
Advantages of using Enumerated: -

 Compile-time type safety.


 We can use the keyword in switch statements.

// Illustrate the enumerator program in Java?

import java.util.*;
public class WorkingDays
{
enum Days{Sunday, 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("Today : " + d + " is Holiday");
else
System.out.println("Today : " + d + " is Workingday");
}
}
Save: - WorkingDays.java
Compile: - D:\Fareed Javaprog>javac WorkingDays.java
Run: - D:\Fareed Javaprog>java WorkingDays
Output: -
Today : Sunday is Holiday.
Today : Monday is Workingday.
Today : Tuesday is Workingday.
Today : Wednesday is Workingday.
Today : Thursday is Workingday.
Today : Friday is Workingday.
Today : Saturday is Workingday.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 144 II.B.Sc., III Sem Java
Chapter – 10
Interfaces: Multiple Inheritances.
(Q) What is Interface? Explain the process of defining and implementing an Interface with an example?

Introduction: -
Java does not support Multiple Inheritances. That is, classes in Java cannot have more than
one superclass. For instances, a definition like is not permitted in Java.

Class A extends B extends C


{
------------------
------------------
------------------
------------------
}
However, the designers of Java could not overlook the importance of Multiple Inheritances. A
large number of real-life applications require the use of Multiple Inheritances, whereby we inherit methods
and properties from several distinct classes.

Java provides an alternative approach known as “Interfaces” to support the concept of Multiple
Inheritances.

Definition of Interface: -

An Interface is a group of constants and method declarations that define the form of a class. An
Interface is collection of method declarations with no data and no bodies. Java provides an alternate
approach know as Interfaces to support concepts of Multiple Inheritance. Although a Java class can not be
sub classes of more than one super class, it can implement more than one Interface, thereby enabling us
to create classes that built upon other classes without the problem s created by multiple inheritances.

Defining Interface: -

An interface is basically a kind of class. Like classes, interfaces contain methods and variables,
but with a major difference.
The difference is that interface defines 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.
Therefore, it is the responsibility of the class that implements an interface to define the code for
implementation of these methods.

Important Rules: -
 All the methods of an interface are implicitly „public‟ and „abstract‟.
 All the variables of an interface are implicitly „public static and final‟.
 An interface can extend one or more other interface.
 An interface can not implement another interface or class.

The syntax for defining an interface is very similar to that for defining a class. The general from
of an interface definition is:

Syntax: - interface <Interface Name>


{
Variable / Field Declarations;
Methods Declarations;
}

 Here, interface is the keyword and interfaceName is any valid Java variable (Just like Class names).

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 145 II.B.Sc., III Sem Java
 All the fields declared inside the interface are implicitly public static and final. All the methods
declared inside the interface are abstract methods.

 Variables are declared as following Syntax.

static final <Data type> <Name of the Variable> = <Value>;

Note that all variables are declared as constants. Methods declaration will contain only a list of methods
without any body statements.

Syntax: - <Return type> <Name of the Method>(parameter list);

Example: - interface PersonDetails


{
static final int code = 98857;
static final string name = “Fareed”;
void display ();
}
Here is an example of an interface definition that contains two variables and one method.

Note that the code for the method is not including in the interface and the method declaration
simply ends with a semicolon. The class that implements this interface must define the code for the
method.

Another Example: - interface Area


{
static final float pi = 3.142F;
float compute (float x, float y);
void show ();
}
Extending Interface: -

Like classes, interface can also be extended. That is, 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 achieved using the keyword „extends‟ as shown below.

Syntax: - Interface <Name of the Interface> extends <Super Interface Class>


{
Variables / Fields Declarations;
Methods Declarations;
}
(OR)
Syntax: - interface name2 extends name1
{
Body of name2;
}

Here the keyword „extends‟ is used to extends the interfaces.

For example, we can put all the constants in one interface and the methods in the other. This
will enable us to use the constants in classes where the methods are not required, example:

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 146 II.B.Sc., III Sem Java
Example: - interface CandidateDetails
{
int code = 12847;
string name = “Mohammad”;
}
interface PersonDetails extends CandidateDetails
{
Void display();
}

The Interface „PersonDetails‟ would inherit both the constants „code and name‟ into it. Note that the
variables name and code are declared like simple variables. It is allowed because all the variables in an
interface are treated as constants although the keywords final and static are not present.

Implementing Interfaces: -

Interfaces are used as “super classes” whose properties are inherited by classes. It is therefore
necessary to create a class that inherits the given interface. To create an interface, it must be
implemented by a class. A class can implement an one or more interfaces. This is done as follows:

Syntax: - class <Class Name> implements <Name of the Interface>


{
Body of Class Name / Class Definition ;
}
Here the keyword “implements” is used to implements the interfaces through the class. A class
can implement one or more interfaces at a time separated by a comma.

//

import java.io.*;
interface Area // Interface Defined.
{
final static float pi = 3.14F;
float compute (float x, float y);
}
class Rectangle implements Area // Interface Implements.
{
public float compute (float x, float y)
{
return (x*y);
}
}
class Circle implements Area // Another implementation.
{
public float compute (float x, float y)
{
return (pi*x*y);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area area; //Interface Objects.
area = rect; // area refers to rect object

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 147 II.B.Sc., III Sem Java
System.out.println("Area of Rectangle = " + area.compute(10,20));
area = cir; // area refers to cir object.
System.out.println("Area of Circle = " + area.compute(10,20));
}
}

Save: - InterfaceTest.java
Compile: - D:\Fareed Javaprog>javac InterfaceTest.java
Run: - D:\Fareed Javaprog>java InterfaceTest
Output: -

Area of Rectangle = 200.0


Area of Circle = 628.0

NOTE: - Default variables on a interface is final.


Default methods in a interface is abstract.

Various forms of Interface implementations: -

Interface A Class A D Interface

Extension
Implementation Extension

B Class B E
Class Interface

Extension
Extension Implementation

C Class C
Class

(A) (B)

Interface Interface

Interface A A B
Extension

B C Class C
Class Implementation

(C)
D

Accessing Interface Variables: -

Interface can be used to declare a set of constants that can be used in different
classes. This is similar to creating header files in C++ to contain a large number of constants. Since such
interfaces do not contain methods, there is no need to worry about implementing any methods. The
constant values will be available to any class that implements the interface. The values can be used in any
methods, as part of any variable declaration, or anywhere where we can use a final value.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 148 II.B.Sc., III Sem Java
Example: - interface A
{
int m = 10;
int n = 50;
}
class B implements A
{
int x = m;
void method B (int size)
{
--------
--------
--------
If(size < n)
--------
--------
--------
}
}

(Q). Explain how to achieved Multiple Inheritance in Java? Explain with an example?

Definition of Multiple Inheritances: - “Deriving a new class based on more than one class is called as
Multiple Inheritance”.

Base 1 Base 2

Base 3

In Java it is not possible to derived a new class based on more than one class directly; rather we
can use Interfaces to achieved this technique.

If two super classes have same names for their members (Variables and Methods) then which
member is inherited into the sub class is the main confusion in multiple inheritances. This is the reason;
Java does not support the concept of multiple inheritances. This confusion is reduced by using multiple
interfaces to achieve multiple inheritances.

Example: - Let us take two interface as :

interface A
{
int x = 20;
void show();
}
interface B
{
int x = 30;
void show();
}
And there is an implementation class MyClass as:

class MyClass implements A, B

Now, there is no confusion to refer to any of the members of the interfaces from MyClass.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 149 II.B.Sc., III Sem Java
For example: -
 To refer to interface A‟s „x‟, we can write as: “ A.x”.
 And to refer to interface B‟s „x‟, we can write as: “B.x”

Similarly, there will not be any confusion regarding which methods is available to the
implementation class, since both the methods in the interface do not have body, and the body is provide in
the implementation class, therefore “MyClass”.

The way to achieve multiple inheritance by using interfaces is shown in the following program.

// Illustrate the Multiple inheritance in Java?

import java.io.*;
interface Maths // Interface Defined.
{
int m = 50;
void marks();
}
interface Physics // Another Interface Defined.
{
int m = 65;
void marks();
}
interface Computers // Another Interface Defined.
{
int m = 97;
void marks();
}
interface Chemistry // Another Interface Defined.
{
int m = 59;
void marks();
}
interface BioTech // Another Interface Defined.
{
int m = 78;
void marks();
}
class SubjectMark implements Maths, Physics, Computers, Chemistry, BioTech
{
public void marks()
{
float m = (Maths.m + Physics.m + Computers.m + Chemistry.m + BioTech.m)/5;
System.out.println("\n Average Marks in Five Subjects are = " + m);
}
public static void main(String args[])
{
SubjectMark sm = new SubjectMark ();
sm.marks();
}
}

Save: - SubjectMark.java
Compile: - D:\Fareed Javaprog>javac SubjectMark.java
Run: - D:\Fareed Javaprog>java SubjectMark
Output: -
Average Marks in Five Subjects are = 69.0.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 150 II.B.Sc., III Sem Java
UNIT –IV
Multithreading Programming

Chapter – 11
Multithreading Programming.

(Q) Defining what is Thread? Explain how to creating Threads in Java with an example?

Definition of Thread: -

In a Java, “Thread is a light weight process or execution of a group of statements”. A Thread


is similar to a program that has a single flow of control.

(or)
“A Thread is a sequence of execution within an own flow of process”.

Definition of Single-Thread: -

“The program that has only one or single flow of control is called Single-Threaded Program”.
In Java, every program will have at least one Thread.

A Thread is a similar to a program that has a single flow of control. It has beginning a body, and an
end, and executed command sequentially. In fact, all main programs in our earlier examples can be called
Single-Threaded Programs. Every program will have at least one Thread as shown below:

class ABC
Beginning
{
........ . . .
........ . . .
Single Thread Body of Execution.
........ . . .
........ . . .
........ . . .
}
End.

Definition of Multi-Thread: -

“The program that has Multiple or one or more flow of controls is called Multi-Threading”. In
a Java program may have several processes to complete the independent tasks. All processes of a program
will be executed simultaneously.

Modern Operating Systems such as Windows 95 to till may recognize that they can execute several
programming simultaneously. This ability is known as „Multi-Tasking‟. In system terminology, it is called as
„Multi-Threading‟.

There are two different types of Multi-Tasking:

1. Process based Multi-Tasking.


2. Thread based Multi-Tasking.

1. Process based Multi-Tasking: - A process is a program that is executing Process based Multi-
Tasking is the feature that allows your computer to run two or more programs concurrently.

2. Thread based Multi-Tasking: - In a Thread based Multi-Tasking environment, the Thread is the
smallest unit of dispactable code. This means that a single program can perform two or more tasks
simultaneously.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 151 II.B.Sc., III Sem Java
A Unique property of Java is its support for Multi-Threading. That is 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 is
known as Multi-Threaded Program.
Main Thread

Main Method Module.

Start
Start Start
Switching Switching

Thread „A‟ Thread „B‟ Thread „C‟

Figure: - Multi-Threaded Program

In above illustrate the Java Program with four Threads; one is main thread and three others. The
main thread is actually „main method module‟ which is designed to create and start the other three threads
namely A, B and C.

Once initiated by the main thread, the thread A, B and C run concurrently and share the resources
jointly. Since all the threads are running on a single processor, the flow of execution is shared between the
threads. The Java interpreter handles the switching of control between the threads in such a way that it
appears they are running concurrently.

Advantages of Multi-Threads: -

1. Multi-Threads is a powerful programming tool that makes Java distinctly different from its fellow
programming languages.

2. Multi-Threading is useful in a number of ways.

3. It enables programmers to do multiple things at one time.

4. They can divide a long program into threads and executed them in parallel.
For Example, we can send tasks such as printing into the background and continue to perform some
other task in the foreground. These approaches considerable improve the speed of programs.

5. Threads extensively used n Java-enabled browsers such as „HotJava‟.

Creating Threads: -

Creating a thread in Java is simple. Threads are implemented in the form of objects that
contain a method called „run()‟. The run() method is the heart and soul of ant thread. It makes up the
entire body of a thread and is the only method in which the thread‟s behavior can be implemented. A
typical run() would appear as follow:

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 152 II.B.Sc., III Sem Java
public void run()
{
………………………….
………………………….
…………………………. (Statements for Implementing Threads)
………………………….
}

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()‟. A new thread
can be created in to two ways:

I. By extending Thread Class. (or) Creating a Thread Class


II. By Implementing Runnable Interface.(or) By Converting a Class to a Thread.

I. By Extending a Thread Class: - Define a class that extends thread class and override its run()
method with the code required by the thread.

II. By Implementing Runnable Interface: - 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.

(I). By Extending a Thread Class: - Define a class that extends thread class and override its run()
method as a thread by extending the class „java.lang.Thread‟. This gives us access to all the thread
methods directly. It includes the following steps:

(a). Declare the class as extending the Thread class.


(b). Implement the run() that is responsible for executing the sequence of code that the Thread will
Executed.
(C). Create a thread object and call the start() to initiate the thread execution.

(a). Declaring the Class: - The Thread class can be extended as follows:

class MyThread extends Thread


{
…………………………………
…………………………………
…………………………………
}

Now we have a new type of Thread is „MyThread‟.

(b). Implementing the run() Method: - The run() method has been inherited by the class „MyThread‟.
We have to override this method in order to implement the code to be executed by our Thread. The basic
implementation of run() will look like this way:
public void run()
{
…………………………………
………………………………… // Thread Code here.
…………………………………
}
When we start the new thread, Java calls the thread‟s run() method, so it the run() where all the
action takes place.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 153 II.B.Sc., III Sem Java
(C) Starting New Thread: - To actually create the run an instance of our thread class, we must write the
following:

MyThread thread A = new MyThread();


threadA.start(); // Invokes run() method.

The first line instantiates a new object of class „MyThread‟. Note that this statement just creates the
object. The thread that will run this object is not yet running. The thread is in a new born state.

The second line calls the start() method creating the thread to move into the Runnable state. Then,
the Java runtime will schedule the thread to run by invoking its run() method. Now, the thread is said to be
in the running state.

// Illustrate Creating Threads by using Thread Class in Java?

import java.lang.*;
class A extends Thread // Declaring the Thread Class „A‟
{
public void run() // Implementing the run() method of Class „A‟.
{
for(int i=1; i<=5; i++)
{
System.out.println("\t From Thread A : i = " +i);
}
System.out.println("Exit From Thread A ");
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5; j++)
{
System.out.println("\t From Thread B : j = " +j);
}
System.out.println("Exit From Thread B ");
}
}
class C extends Thread
{
public void run()
{
for(int k=1; k<=5; k++)
{
System.out.println("\t From Thread C : k = " +k);
}
System.out.println("Exit From Thread C ");
}
}
class ThreadTest
{
public static void main(String args[])
{
new A().start(); // Start the Running of Thread.
new B().start();
new C().start();
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 154 II.B.Sc., III Sem Java
Save: - D:\Fareed Javaprog> ThreadTest.java

Compile: - D:\Fareed Javaprog>javac ThreadTest.java


Run: - D:\Fareed Javaprog>java ThreadTest

Test Data (1): - Test Data (2): - Test Data (3): -


Output: - Output: - Output: -

From Thread A : I = 1 From Thread A : I=1 From Thread A : I = 1


From Thread A : I = 2 From Thread B : J=1 From Thread A : I = 2
From Thread A : I = 3 From Thread B : J=2 From Thread A : I = 3
From Thread A : I = 4 From Thread B : J=3 From Thread B : J = 1
From Thread A : I = 5 From Thread A : I=2 From Thread B : J = 2
From Thread B : J = 1 From Thread B : J=4 From Thread B : J = 3
From Thread B : J = 2 From Thread C : K=1 From Thread B : J = 4
From Thread B : J = 3 From Thread C : K=2 From Thread B : J = 5
From Thread C : K=3
Exit From Thread A From Thread C : K=4 Exit From Thread B
From Thread C : K=5
From Thread A : I=1 From Thread A : I=4
From Thread C : K=1 Exit From Thread C From Thread C : K=1
From Thread C : K=2 From Thread C : K=2
From Thread C : K=3 From Thread B : J = 5 From Thread C : K=3
From Thread C : K=4 From Thread C : K=4
From Thread C : K=5 Exit From Thread B From Thread C : K=5
From Thread A : I= 5
Exit From Thread C From Thread A : I = 3
From Thread A : I = 4 Exit From Thread A
From Thread B : J = 4 From Thread A : I = 5
From Thread B : J = 5 Exit From Thread C
Exit From Thread A
Exit From Thread B.

// Illustrate the Sum of numbers by using Extending the Threads in Java?

import java.lang.*;
class HelloThread extends Thread // Declared Thread Class.
{
public void run() // Overrides the run() method
{
int sum = 0;
for(int i=1; i<=100; i++)
sum = sum + i;
System.out.println(" Sum : = " + sum);
}
}
public class HelloJavaThread
{
public static void main(String args[])
{
HelloThread t = new HelloThread(); // Instantiating the Thread Class
t.start(); // Invokes the run() method
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 155 II.B.Sc., III Sem Java
Save: - HelloJavaThread.java
Compile: - D:\Fareed Javaprog>javac HelloJavaThread.java
Run: - D:\Fareed Javaprog>java HelloJavaThread

Output: - Sum : = 5050.

(II). By Converting a Class to a Thread. (or) By Implementing Runnable Interface: -

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.

Step 1: - Declare the class as implementing the Runnable Interface.


Step 2: - Implement the run() method.
Step 3: - Create a thread by default object that is instantiated from this runnable class as the target of
thread.
Step 4: -Call the thread‟s start() method to run the thread foe execution.

Declaring the Class as Runnable Interface: - The Runnable interface can extend as follows:

class MyRunnable implements Runnable


{
…………………………………
…………………………………
…………………………………
}

Now we have a new type of Interface is „MyRunnable‟.

Implementing the run() Method: - The basic implementation of run() will look like this way:

public void run()


{
…………………………………
…………………………………
…………………………………
}

// Illustrate for implementing Runnable Interface in Java?

import java.lang.*;
class Runnably implements Runnable // Step 1
{
public void run() // Step 2
{
try
{
while(true)
{
Thread.sleep(10);
System.out.println("Mohammad Fareed.");
}
}
catch(InterruptedException ex)
{

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 156 II.B.Sc., III Sem Java
ex.printStackTrace();
}
}
}
class RunnableTest
{
public static void main(String args[])
{
Runnably ry = new Runnably();
Thread t = new Thread(ry); // Step 3.
t.start(); // Step 4.
}
}

Save: - RunnableTest.java
Compile: - D:\Fareed Javaprog>javac RunnableTest.java
Run: - D:\Fareed Javaprog>java RunnableTest

Output: - Mohammad Fareed.


Mohammad Fareed.
Mohammad Fareed.
Mohammad Fareed.
Mohammad Fareed.
Mohammad Fareed.
Mohammad Fareed.
Mohammad Fareed.
Mohammad Fareed.
Mohammad Fareed.
Mohammad Fareed.
Mohammad Fareed……………………………………….

// Illustrate the Sum of numbers by using Implementing Runnable Interface in Java?

import java.lang.*;
class ThreadRunable implements Runnable
{
public void run() // Overrides the run() method
{
int sum = 0;
for(int i=1; i<=100; i++)
sum = sum + i;
System.out.println(" Sum : = " + sum);
}
}
public class RunableThread
{
public static void main(String args[])
{
ThreadRunable tr = new ThreadRunable(); // Create Runnable Class Object.
Thread t = new Thread(tr); // Create Thread Object.
t.start(); // Invokes the run() method of the Thread.
}
}

Save: - RunableThread.java
Compile: - D:\Fareed Javaprog> RunableThread.java
Run: - D:\Fareed Javaprog>java RunableThread

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 157 II.B.Sc., III Sem Java
Output: - Sum : = 5050.

Stopping and Blocking a Thread: -

Stopping a Thread: - Whenever we want to stop a thread from running further, we may do by calling its
stop() method, like:

MyThread.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. The stop() method may be used when the
premature death of a thread is desire.

Blocking a Thread: - A Thread can also be temporarily suspended or blocked from entering into the
runnable and subsequently running state by using either of the following thread methods:

sleep() // Blocked for a specified time.


suspend() // Blocked Unit further orders.
wait() // Blocked Unit Certain Condition occurs.

These methods cause the thread to go into the blocked (or not runnable) 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 supend(), and the notify() method is called in the case of wait().

Thread Class: - The Thread Class in the “java.lang” package allows creating and managing threads. Each
thread is a separate instance of its class. Some Constructors for Thread are as follows:

Thread ();
Thread (Runnable r)
Thread (Runnable r, String S)
Thread (String S)

Here „r‟ is a reference to an object that implements Runnable interface and „S‟ is a String used
to identify the Thread.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 158 II.B.Sc., III Sem Java
(Q). Explain the Life-Cycle / State Transitions of a Thread with examples?

During the life-time of a thread, it may be in and out of several states. These states are used to
control the flow of execution of several parallel threads. The threads scheduler of Java Virtual Machine
(JVM) moves the threads from one state to another state when we call different methods.

Each thread in its entire life of execution may be in one of the following states.

1. New Born / New State.


2. Runnable Sate
3. Running State
4. Sleeping / Waiting / Blocked State
5. Dead State.
Stop ()
New Born
NewThread

Start ()

Killed
Thread

Stop ()
Active Running Runnable Dead
Thread

Yield ()
Stop ()

Sleep ()
Suspend () Resume ()
Notify ()
Wait ()

Ideal Thread Blocked


(Not Runnable)

Fig: - Life-Cycle / State Transitions of a Thread.

New Born Runnable Running Blocked Dead

1. New Born: - When we created a thread object, the thread is born and it said to be a „New Born‟ state.
The thread is not yet for scheduled for running. At this sate we do only one of the following things with it:

 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 methods at this
stage, an exception will be thrown.

New Born

start() stop()
Runnable State Dead State

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 159 II.B.Sc., III Sem Java
2. Runnable State: -

 Runnable state means the thread is ready for execution and it‟s waiting for the availability of the
processor. i.e. the thread has joined the queue of threads that are waiting for execution.

 Thread first enter the Runnable state when the start() method is invoked.

 If all threads have equal priority, then they are given time slots for execution in round robin fashion.
i.e. first-come and first-server (FIFO) manner.

 The thread is joins the queue at the end and again waits for its turn. The process of assigning time
to threads knows as „Time-Slicing‟.

 If we want a thread to relinquished control to another thread of equal priority before its turn comes
by using „yield()‟ method.
yield ()

Running Thread. Runnable Threads.

3. Running Sate: - Running State means the processor has given its time to the thread for its execution.
The thread may come to this stage more than once in its life time. A thread enters this stage whenever its
run() method is called. A running thread may relinquish control in one of the following situation.

 It has been suspended using suspend(). A suspended thread can be revived by using the resume ().
The approach is useful when we want to suspend a thread from a some time due to certain reasons,
but do not want to kill it.

suspend

resume

Running Runnable Suspended.

 We can put a thread to sleep for a specified time period using sleep(time) where time is in
milliseconds. This means that the thread is out of the queue during this time period. The tread re-
enters the Runnable state as soon as this time period is elapsed.

sleep (t)

after(t)

Running Runnable Suspended.

 It has been told to wait until some event occurs. This done using the wait() method. The thread can
be scheduled to run again using the notify() method.

wait

notify

Running Runnable Waiting.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 160 II.B.Sc., III Sem Java
4. Blocked State: -

 A Thread comes to this stage when it is made to stop its execution. This happen when the thread is
suspend, sleeping and waiting in order to satisfy certain requirements.

 A blocked thread is considered “not runnable” but not dead and therefore fully qualified to run
again.

5. Dead State: -

 A running thread ends its life when its happen complete executing its run() method. It is natural
death.

 However killed it by suspended the stop message to it any state thus causing a premature death.

 The thread enters this stage only once in its life time.

// Illustrate the Threads Stages Program?

import java.lang.*;
class First implements Runnable
{
public void run()
{
for(int i=1; i<=10; i+=2)
{
System.out.println(Thread.currentThread().getName() + " : " + i);
if(i%2 ==1)
Thread.yield(); // This Thread is give change to another Thread.
}
}
}
class Second implements Runnable
{
public void run()
{
for(int i=2; i<=10; i+=2)
{
System.out.println(Thread.currentThread().getName() + " : " + i);
if(i%2 ==0)
try
{
Thread.sleep(100); // Thread in Sleeping State.
}
catch (InterruptedException e) {}
}
}
}
public class ThreadStages
{
public static void main(String args[])
{
First f = new First();
Thread one = new Thread(f, "First"); // Thread One is in New Born State.
one.start(); // Thread One is in Runnable State.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 161 II.B.Sc., III Sem Java
Second s = new Second();
Thread two = new Thread(s, "Second"); // Thread Two is in New Born State.
two.start(); // Thread Two is in Runnable State.
}
}

Save: - ThreadStages.java
Compile: - D:\Fareed Javaprog> javac ThreadStages.java
Run: - D:\Fareed Javaprog> java ThreadStages

Output: -
First :1
Second : 2
First :3
First :5
First :7
First :9
Second : 4
Second : 6
Second : 8
Second : 10.

(Q) Explain using of Thread Methods with an one example?

The Thread calls in the “java.lang” package allow creating and managed threads. Each thread is a
separate instance of its class. Some Constructor for Thread are as follow:

Thread ();
Thread (Runnable r)
Thread (Runnable r, String S)
Thread (String S)

Here „r‟ is a reference to an object that implements Runnable interfaces and „S‟ is a String used to
identify the Thread.

The following table shows some „Static‟ methods provided by this class:

Method Description
Thread.currentThread() Returns a reference to the Current Thread.
void sleep(long msec) throws Interrupted Exception Causes the Current Thread to wait foe milliseconds.
Thread.yield() Causes the Current Thread to yield control of the
processor.

The following table shows some „Instance‟ methods provided by this class:

Method Description
start() Start the Thread.
sleep(mesec) Waiting for some milliseconds time to execution.
run() This method is overridden by sub class.
yield() Change to one thread to another thread.
stop() To stop middle of execution thread.
String getName() Return the Name of the thread.
Int getPriority() Returns the Priority of the Thread.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 162 II.B.Sc., III Sem Java
// Illustrate the Thread Methods like Yield(), Sleep() and Stop() Methods of Threads in Java?

import java.lang.*;
class A extends Thread
{
public void run()
{
for(int i=1; i<=5; i++)
{
if(i==1) yield();
System.out.println("\t From Thread A : I = " + i);
}
System.out.println("Exit From Thread A ");
}
}
class B extends Thread
{
public void run()
{
for(int j=1; j<=5; j++)
{
System.out.println("\t From Thread B : J = " + j);
if(j==3) stop();
}
System.out.println("Exit From Thread 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==1)

try
{
sleep(1000);
}
catch (Exception e) {}
}
System.out.println("Exit From Thread B ");
}
}
class ThreadMethods
{
public static void main(String args[])
{
A threadA = new A();
B threadB = new B();
C threadC = new C();

System.out.println("Start Thread A : ");


threadA.start();

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 163 II.B.Sc., III Sem Java
System.out.println("Start Thread B : ");
threadB.start();

System.out.println("Start Thread C : ");


threadC.start();

System.out.println("End of Main Thread : ");


}
}

Save: - ThreadMethods.java

Compile: - D:\Fareed Javaprog>javac ThreadMethods.java


Run: - D:\Fareed Javaprog>java ThreadMethods

Test Data (1): - Test Data (2): - Test Data (3): -

Output: - Output: - Output: -

Start Thread A : Start Thread A : Start Thread A :


Start Thread B : Start Thread B : Start Thread B :
From Thread A:I=1 From Thread A:I=1 Start Thread C :
Start Thread C : Start Thread C : From Thread A : I = 1
From Thread B : J=1 From Thread B : J = 1 From Thread A : I = 1
From Thread B : J=2 From Thread B : J = 2 From Thread A : I = 1
From Thread B : J=3 From Thread B : J = 3 From Thread A : I = 1
From Thread A : I=2 From Thread A : I = 2
From Thread C : K=1 From Thread A : I = 3 End of Main Thread
From Thread A : I = 4
End of Main Thread. From Thread A : I = 5 From Thread A : I = 1
From Thread A : I = 1
From Thread A : I = 3 Exit From Thread A. From Thread A : I = 1
From Thread A : I = 4 From Thread A : I = 1
From Thread A : I = 5 From Thread C : K = 1 From Thread A : I = 1

Exit From Thread A : End of Main Thread. Exit From Thread A.

From Thread C : K = 2 From Thread C : K = 2 From Thread A : I = 1


From Thread C : K = 3 From Thread C : K = 3 From Thread A : I = 1
From Thread C : K = 4 From Thread C : K = 4 From Thread A : I = 1
From Thread C : K = 5 From Thread C : K = 5 From Thread A : I = 1

Exit From Thread B. Exit Form Thread B. Exit From Thread C.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 164 II.B.Sc., III Sem Java
(Q). Explain the Thread Priorities? Give one example program in Java?

In Java, each thread is assigned a priority, which affects that order in which it is scheduled for
running. The thread that we have discussed so for are of the same priority. The threads are same priority
are given equal treatment by the Java scheduled and, therefore they share the processor on a First-Come
and First-Server manner.

The thread scheduler of Java Virtual Machine (JVM) uses priority based scheduling using time
slicing. Thread scheduler to decide when each thread should be allowed to run. In higher priority threads
get more CPU time than lower priority thread. The value of level must be with in the range of 1 to 10.

If a thread enters the runnable state and it has a higher priority than any of the threads in a pool.
Then the currently running thread will be preempted by the incoming thread and force to move to the
runnable state.

Java permits the programmers to set the priority of a thread using the method “setPriority ()”.
You can obtain the current priority setting by calling the “getPriority()”.

Syntax: - Thread Name.setPriority(int Number);

Here the „int‟ value is an integer value that specified the priority of the thread.
The Thread class defines three priority constants.

Constant Value
Thread.MIN_PRIORITY 1
Thread.NORM_PRIORITY 5
Thread.MAX_PRIORITY 10

The default priority given to a thread is Normal Priority, Plus or Minus 1.

When multiple threads are ready for execution, The Java Virtual Machine (JVM) chooses the highest
priority threads are ready to execution. For a thread low priority to gain control, one of the following things
to be happen:

1. It stops running at the end of run().


2. It is made to sleep using sleep()
3. It is told to wait using wait().

// Implementing Thread of Method setPriotirt() in Java?

import java.lang.*;
public class ThreadPriority
{
public static void main(String args[])
{
Athread thread1 = new Athread();
Bthread thread2 = new Bthread();
Cthread thread3 = new Cthread();

thread1.setPriority(1);
thread2.setPriority(10);

thread1.start();
thread2.start();
thread3.start();
}
}
Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 165 II.B.Sc., III Sem Java
class Athread extends Thread
{
public void run()
{
for (int i=0; i<5; i++)
{
System.out.println(" 'A' Thread is Running");
}
}
}
class Bthread extends Thread
{
public void run()
{
for (int i=0; i<5; i++)
{
System.out.println(" 'B' Thread is Running");
}
}
}
class Cthread extends Thread
{
public void run()
{
for (int i=0; i<5; i++)
{
System.out.println(" 'C' Thread is Running");
}
}
}

Save: - ThreadPriority.java
Compile: - D:\Fareed Javaprog> javac ThreadPriority.java

Run: - D:\Fareed Javaprog>java ThreadPriority

Test Data (1): - Test Data (2): - Test Data (3): -


Output: - Output: - Output: -

„B‟ Thread is Running. „A‟ Thread is Running. „A‟ Thread is Running.


„B‟ Thread is Running. „B‟ Thread is Running. „A‟ Thread is Running.
„B‟ Thread is Running. „B‟ Thread is Running. „A‟ Thread is Running.
„B‟ Thread is Running. „B‟ Thread is Running. „A‟ Thread is Running.
„B‟ Thread is Running. „B‟ Thread is Running. „A‟ Thread is Running.
„C‟ Thread is Running. „B‟ Thread is Running. „C‟ Thread is Running.
„C‟ Thread is Running. „A‟ Thread is Running. „C‟ Thread is Running.
„C‟ Thread is Running. „A‟ Thread is Running. „C‟ Thread is Running.
„C‟ Thread is Running. „A‟ Thread is Running. „C‟ Thread is Running.
„C‟ Thread is Running. „A‟ Thread is Running. „C‟ Thread is Running.
„A‟ Thread is Running. „C‟ Thread is Running. „B‟ Thread is Running.
„A‟ Thread is Running. „C‟ Thread is Running. „B‟ Thread is Running.
„A‟ Thread is Running. „C‟ Thread is Running. „B‟ Thread is Running.
„A‟ Thread is Running. „C‟ Thread is Running. „B‟ Thread is Running.
„A‟ Thread is Running. „C‟ Thread is Running. „B‟ Thread is Running.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 166 II.B.Sc., III Sem Java
Expiation of above program: -

When the program is run for the second of subsequent times, the sequence of the output
statements may be different. Through „B” Thread will come first, begin given maximum priority, the
sequence of the threads „A‟ and „C‟ may not always be the same.

First we will take the class „A‟ Thread. This class extends the class Thread. The run() method of this
class will print the statement, „A‟ Thread Running, five times on the screen. Same is the case the classes „B‟
and „C‟ Threads which also extends class Thread. Their run() methods will print the statements „B‟ and „C‟
Threads running five times on the screen.

Now let us examine the class “ThreadPriority”. The main() method of this class instantiates the
three classes like „A‟, „B‟ and „C‟ Threads respectively. That is, the objects of all these classes are created.

Thread1 is an object of the class „Athread‟, similarly Thread2 and Thread3 are the objects of the
classes „Bthread‟ and „Cthread‟ respectively.

Let us come to the next statement, which is as follows:

thread1.setPrority(1);

In the above statement, using the object “thread1” of the class „Athread‟. We are calling the
“setPriority()” method of the class Thread. This method sets the priority of a thread according to the
argument passes. Here „thread1‟ is set to „1‟ which is minimum priority.

The next statement is:

thread2.setPriority(10);

This statement sets the priority of „thread2‟ to „10‟. i.e maximum priority. The Java scheduler will
give preference to „thread2‟ and it will be scheduled before „thread1‟. No priority is given to „thread3‟.
Hence, it assumes the normal priority by default.

// Illustrate the Priority of Threads in Java?

import java.lang.*;
class One extends Thread
{
public void run()
{
System.out.println("Thread One is Started : ");
for(int i=1; i<=5; i++)
System.out.println(" Form Thread One 'I' : = " + i);
System.out.println(" Exit From Thread One ");
}
}
class Two extends Thread
{
public void run()
{
System.out.println("Thread Two is Started : ");
for(int j=1; j<=5; j++)
System.out.println(" Form Thread Two 'J' : = " + j);
System.out.println(" Exit From Thread Two ");
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 167 II.B.Sc., III Sem Java
class Three extends Thread
{
public void run()
{
System.out.println("Thread Three is Started : ");
for(int k=1; k<=5; k++)
System.out.println(" Form Thread Three 'K' : = " + k);
System.out.println(" Exit From Thread Three ");
}
}
public class ThreadPrioritys
{
public static void main(String args[])
{
One a = new One();
Two b = new Two();
Three c = new Three();

a.setPriority(Thread.MAX_PRIORITY);
b.setPriority(Thread.NORM_PRIORITY);
c.setPriority(Thread.MIN_PRIORITY);

b.start();
c.start();
a.start();
}
}
Save: - ThreadPrioritys.java
Compile: - D:\Fareed Javaprog> javac ThreadPrioritys.java
Run: - D:\Fareed Javaprog> java ThreadPrioritys

Output: -

Thread One is Started :


Thread Three is Started :
Thread Two is Started:
From Thread Three „K‟ : = 1
From Thread Three „K‟ : = 2
From Thread Three „K‟ : = 3
From Thread Three „K‟ : = 4
From Thread Three „K‟ : = 5
Exit From Thread Three.
From Thread One „I‟ : = 1
From Thread One „I‟ : = 2
From Thread One „I‟ : = 3
From Thread One „I‟ : = 4
From Thread One „I‟ : = 5
From Thread Two „J‟ : = 1
From Thread Two „J‟ : = 2
From Thread Two „J‟ : = 3
From Thread Two „J‟ : = 4
From Thread Two „J‟ : = 5
Exit From Thread One.
Exit From Thread Two.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 168 II.B.Sc., III Sem Java
// Implementing Thread of Method getPriotirt() in Java?

import java.lang.*;
class PThread extends Thread
{
public void run()
{
try
{
for(int i=1; i<=3; i++)
{
System.out.println(" Child Thread Name is : " + getName()+i);
}
}
catch(Exception e) {}
System.out.println("Exit From Child Thread : " + getName());
}
}
class ThreadsPriority
{
public static void main(String[] args)
{
PThread First = new PThread();
PThread Second = new PThread();
PThread Third = new PThread();

System.out.println(" First Thread Priority is : " + First.getPriority());


System.out.println(" Second Thread Priority is : " + Second.getPriority());
System.out.println(" Third Thread Priority is : " + Third.getPriority());

First.setName("A");
Second.setName("B");
Third.setName("C");

First.start();
Second.start();
Third.start();
}
}
Save: - ThreadsPriority.java
Compile: - D:\Fareed Javaprog> javac ThreadsPriority.java
Run: - D:\Fareed Javaprog> java ThreadsPriority

Test Data (1): - Test Data (2): - Test Data (3): -


Output: - Output: - Output: -

First Thread Priority is : 5 First Thread Priority is : 5 First Thread Priority is : 5


Second Thread Priority is : 5 Second Thread Priority is : 5 Second Thread Priority is : 5
Third Thread Priority is : 5 Third Thread Priority is : 5 Third Thread Priority is : 5

Child Thread Name is : B1 Child Thread Name is : A1 Child Thread Name is : A1


Child Thread Name is : A1 Child Thread Name is : B1 Child Thread Name is : C1
Child Thread Name is : A2 Child Thread Name is : B2 Child Thread Name is : C2
Child Thread Name is : A3 Child Thread Name is : B3 Child Thread Name is : C3
Exit From Child Thread : A Child Thread Name is : C1 Child Thread Name is : B1
Child Thread Name is : B2 Child Thread Name is : A2 Child Thread Name is : B2
Child Thread Name is : B3 Child Thread Name is : A3 Child Thread Name is : B3

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 169 II.B.Sc., III Sem Java
Exit From Child Thread : B Exit From Child Thread : A Exit From Child Thread : B
Child Thread Name is : C1 Child Thread Name is : C2 Child Thread Name is : A2
Child Thread Name is : C2 Child Thread Name is : C3 Child Thread Name is : A3
Child Thread Name is : C3 Exit From Child Thread : C Exit From Child Thread : A
Exit From Child Thread : C Exit From Child Thread : B Exit From Child Thread : C.

// implementing setpriority() and getPriority() plus 1?

import java.lang.*;
class A extends Thread
{
public void run()
{
System.out.println(" Thread 'A' Started : ");
for(int i=1; i<=5; i++)
{
System.out.println("\t From Thread A : I = " + i);
}
System.out.println("Exit From Thread A ");
}
}
class B extends Thread
{
public void run()
{
System.out.println(" Thread 'B' Started : ");
for(int j=1; j<=5; j++)
{
System.out.println("\t From Thread B : J = " + j);
}
System.out.println("Exit From Thread B ");
}
}
class C extends Thread
{
public void run()
{
System.out.println(" Thread 'C' Started : ");
for(int k=1; k<=5; k++)
{
System.out.println("\t From Thread C : K = " + k);
}
System.out.println("Exit From Thread C ");
}
}
class PriorityThreads
{
public static void main(String args[])
{
A threadA = new A();
B threadB = new B();
C threadC = new C();

threadC.setPriority(Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority()+1);
threadA.setPriority(Thread.MIN_PRIORITY);

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 170 II.B.Sc., III Sem Java
System.out.println("Start Thread A : ");
threadA.start();

System.out.println("Start Thread B : ");


threadB.start();

System.out.println("Start Thread C : ");


threadC.start();

System.out.println("End of Main Thread : ");


}
}

Save: - PriorityThreads.java

Compile: - D:\Fareed Javaprog>javac PriorityThreads.java

Run: - D:\Fareed Javaprog>java PriorityThreads

Test Data (1): - Test Data (2): - Test Data (3): -


Output: - Output: - Output: -

Start Thread A: Start Thread A: Start Thread A:


Start Thread B: Start Thread B: Start Thread B:
Thread „A‟ Started : Thread „A‟ Started : Thread „A‟ Started :
Thread „B‟ Started: Start Thread C: Thread „B‟ Started :
Start Thread C : From Thread A : I = 1 From Thread B : J=1
From Thread A : I = 1 From Thread A : I = 2 Start Thread C:
From Thread A : I = 2 From Thread A : I = 3 From Thread B : J=2
From Thread A : I = 3 From Thread A : I = 4 Thread „C‟ Started :
From Thread A : I = 4 From Thread A : I = 5 From Thread C : K = 1
From Thread A : I = 5 Exit From Thread A. From Thread C : K = 2
Exit From Thread A. Thread „B‟ Started: From Thread C : K = 3
End of Main Thread. Thread „C‟ started: From Thread C : K = 4
From Thread B :J=1 From Thread C : K = 1 From Thread C : K = 5
Thread „C‟ Started From Thread C : K = 2 Exit From Thread C.
From Thread C : K=1 From Thread C : K = 3 From Thread A : I=1
From Thread C : K=2 From Thread C : K = 4 From Thread B : J=3
From Thread C : K=3 From Thread C : K = 5 From Thread B : J=4
From Thread C : K=4 Exit From Thread C. End of Main Thread.
From Thread B : J=2 End of Main Thread. From Thread B : J=5
From Thread B : J=3 From Thread B : J = 1 Exit From Thread B.
From Thread B : J=4 From Thread B : J = 2 From Thread A : I = 2
From Thread B : J=5 From Thread B : J = 3 From Thread A : I = 3
From Thread C : K=5 From Thread B : J = 4 From Thread A : I = 4
Exit From Thread C. From Thread B : J = 5 From Thread A : I = 5
Exit From Thread B. Exit From Thread B. Exit From Thread A.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 171 II.B.Sc., III Sem Java
(Q). What is Synchronization? Explain with an example?

When two or more threads needs accesses to shared resources, they need some way to ensure that
the resource will be used by only one thread at a time. The process by which this is achieved is called
Synchronization.

Each thread of execution will have its own run() method to process data of its own. In this
case there will no problem for the thread to use the resource of the class. When a thread tries to use same
resources with two or more threads, they may be chances of completing with other threads of use the
resources.

Java enables us to overcome this problem using a technique known as „Synchronization‟.


Using synchronization, we can declare block or method as a „synchronization‟ which prevents parallel
access by multiple threads.

Key to synchronization is the concept of the „monitor‟. A monitor is an object that is used as a
mutually exclusive lock only one thread can own a monitor at a given time. When a thread acquires a lock,
it is said to have entered the monitor. All the other threads attempting to enter the locked monitor will be
suspended until the first thread exits the monitor. The other threads are said to be waiting for the monitor.

Releasing a lock means the thread holding the lock exits the synchronization code. Whenever a
thread completed its work of using synchronization code, it will hand over the lock to the next that is
waiting to use that code. If other threads are waiting for that object, the lock is free until some other
threads enter the synchronization code on that object.

Syntax of Synchronization Block: -

synchronized (lock-Object)
{
……………………………
…………………………… // Code for Synchronized
……………………………
}

Syntax of Synchronization Method: -

synchronized <Return Type> <Method Name>(Arguments List)


{
……………………………
…………………………… // Code for Synchronized
……………………………
}

The following methods help threads to communicate with each other.

 wait ()  Asks the current thread to wait for a signal from other thread.

 notify()  Signals the another thread to use the resources which are held by the currently
running thread.

 notifyAll()  Signals all the other threads to use the resources which are held by the
currently running thread.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 172 II.B.Sc., III Sem Java
Example: - This example simulates the actions of several bank customers who make deposits to a shared
account. The Account class encapsulates the current balance in the account. This value is incremented by a
synchronized so it is not corrupted. The getBlance () returns the current value of the account.

The customer class extends Thread. Its Constructor saves a reference to the shared account. The
run () executes a loop that makes 1,00,000 deposits. Each deposit equals to Rs: 10/-.

The BankDemo class first creates one Account object. Then 10 customer‟s objects are instantiated
and started. The join () is called to wait for each of these threads to complete. Finally balance in he
account is display.

// Illustrate the Bank Demo Program by using Synchronized in Java?

import java.lang.*;
class Account
{
private int balance = 0;
synchronized void deposit(int amount)
{
balance += amount;
}
int getBalance()
{
return balance;
}
}
class Customer extends Thread
{
Account account;
Customer(Account account)
{
this.account = account;
}
public void run()
{
try
{
for(int i=0; i<100000; i++)
{
account.deposit(10);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
class Bank
{
private final static int NUMCUSTOMERS = 10;
public static void main(String[] args)
{
Account account = new Account();
Customer Customers[] = new Customer[NUMCUSTOMERS];
for(int i=0; i<NUMCUSTOMERS; i++)

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 173 II.B.Sc., III Sem Java
{
Customers[i] = new Customer(account);
Customers[i].start();
}
for(int i=0; i<NUMCUSTOMERS; i++)
{
try
{
Customers[i].join();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
System.out.println(account.getBalance());
}
}

Save: - Bank.java
Compile: - D:\Fareed Javaprog> javac Bank.java
Run: - D:\Fareed Javaprog> java Bank

Output: - 100000.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 174 II.B.Sc., III Sem Java
Chapter – 12
Managing Errors and Exceptions.

(Q). What is Error? Discuss different types of Errors in Java with a one example?

It is Common to make mistake while developing as well as typing a program. A mistake might lead
to an error causing to program to produce the unexpected results.

An error may produce incorrect output or may terminate the execution of the program or even
may cause the system to crash. It is therefore important to detected and manage properly all the possible
errors conditions in the program, so that the program will not terminate or rash during of execution. Errors
may broadly classify into three types:

1. Syntactical Errors know as Compile-Time Errors.


2. Run-Time Errors.
3. Logical Errors.

1. Compile-Time Errors: - All Syntax errors will be detected by the Java Compiler and therefore these
errors are known as “Compile-Time” errors. The errors that are made while writing the programs. These
errors include misspelled identifiers and keywords, proper terminations of loop and blocks etc. These errors
are detected and display by the Java Compiler. It is necessary to fix all these errors before we successfully
complied and run the program.

Example: - / * Illustration of Compile-Time Error * /

Import java.lang.*;
class HelloWorld
{
public static void main(String args[])
{
System.out.println(“Hello! Welcome to Java. Mr.Shaik Mohammad Fareed”) // Missing ;
}
}

The Java Compiler does a nice job of telling us where the errors in the program. In above program we
have missed the semicolon (;) at the end of print statement in program. The following message will be
display on the screen.

Compile: - D:\Fareed Javaprog> javac HelloWorld.java

HelloWorld.java : 6 : „ ; ‟ expected.
System.out.println(“Hello! Welcome to Java. Mr.Shaik Mohammad Fareed”) ^
1 error.

We can now go to the appropriate line, correct the error, and recompile the program. Sometimes, a single
error may be the source of multiple errors. Most of the compile-time errors are due to typing mistakes.
These errors are sometimes very hard to find. To find these errors, we may need to check the code word
by word. The most common errors problems are:

 Missing the Semicolons Symbols (;).


 Missing (or mismatch of) brackets in class and methods.
 Misspelling identifiers and keywords.
 Missing double quotes in strings.
 Use of undeclared variables.
 Incompetent types in assignment / initializations.
 Bad references object.
 Use of single equal to (=) symbol in place of double equal to (= =). And so on…….

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 175 II.B.Sc., III Sem Java
2. Run Time Error: - The errors that are revealed at the time of executing a program are called as “Run
Time” error. Sometimes a program may compile successfully and created the “.class” file. But while
executing that program, it may be terminated because of an error.

Run-Time errors leads to terminate a program abnormally even without the knowledge of users. It
is very hard to find out Run-Time errors. Most of common Run-Time errors are:

 Dividing an integer value by zero.


 Accessing elements that are out of bound of an array.
 Trying to store a value into an array of an incompatible class or type.
 Passing a parameter that is not a valid range or value of method.
 Typing to illegal change the state of threads.
 Attempting to use a negative size of an array.
 Converting invalid string into a number.
 Accessing characters that are out of bound of string. And many more.

Example: - / * Illustration of Run-Time Error * /

import java.lang.*;
class RuntimeError
{
public static void main(String args[])
{
int a = 10;
int b = 5;
int c = 5;
int x = a/(b-c); // Diving by Zero.
System.out.println("X : = " + x);
int y = a/(b+c);
System.out.println("Y : = " + y);
}
}

Save: - RuntimeError.java
Compile: - D:\Fareed Javaprog>javac RuntimeError.java
Run: - D:\Fareed Javaprog>java RuntimeError

Exception in thread “main” java.lang.ArithmeticException : / by Zero.


At RuntimeError.main<RuntimeError.java: 9>

Example: - / * Illustration of Run-Time Error * /

import java.lang.*;
class RuntimeErrors
{
public static void main(String args[])
{
int a[] = {10,20,15,30};
for(int i=0; i<5; i++)
System.out.println(a[i]);
}
}

Save: - RuntimeErrors.java
Compile: - D:\Fareed Javaprog>javac RuntimeErrors.java
Run: - D:\Fareed Javaprog>java RuntimeErrors

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 176 II.B.Sc., III Sem Java
10
20
15
30

Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 4


At RuntimeError.main<RuntimeErrors.java: 4>

In the above program, we are typing to access the 5th element of the array. But there is no
element at index position 4th in the array. So it leads no compile-time error but it leads a run time error.

3. Logical Errors: - Logical Errors occur when the code complies successfully and runs without producing
error messages, but does not produce the desired results. These errors are usually difficult to defect and
debug.

Example: - When any loop is not closed at the right place.

(Q) What is an Exception? How to process of Handling Exceptions with an example in Java?

Exception Handling: -

An Exception is a condition that is caused by a run-time error in a program.


Whenever the Java interpreter encounters a run-time error, it creates an exception object of the relevant
class and throws it out of the method in which it is encountered.

If method throws an exception object, it must be handled properly by catching that exception
object. Even through the program raises exception; if we want to continue the execution of the program
then we should try to catch the exception object thrown by the error condition. This process is called as
“Exception Handling”. The Exception Handling code basically consists of two segments.

 To detect errors and throw exception.


 Catch the exception and take appropriate action.

This mechanism of handling exceptions includes the following tasks:

1. Find the problem (Hit or try the Exception).


2. Inform that an error has occurred (Throw the Exception).
3. Receive the error information (Catch the Exception).
4. Take appropriate action (Handle the Exception).

Java Common Exception: -

Java has several predefined exceptions inside the standard package


“Java.lang”. The most common exception that you may encounter is:

 ArithmeticException: -This Exception is thrown when an exceptional arithmetic condition error, such
as division by zero, etc.

 ArrayIndexOutOfBoundsExceptions: - This exception is thrown when an attempt is made to access


an array element beyond the array index. For ex: an Array of 5 elements and you try to access 6 th
elements. In such situation this type of exception is thrown.

 NullPointerException: - An exception is thrown when you attempting to an object whose value is null.

 NumberFormatExecption: - This exception is thrown when an attempt to perform an invalid


conversion of a string to a numeric format. For ex: if a string contains a value 12$ and you try to convert
in into an int value then this type of exception is thrown.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 177 II.B.Sc., III Sem Java
 InterruptedExecption: - This Exception is thrown when one thread interrupts another thread.

 ArratStoreExecption: - This Exception is thrown when we try to store wrong type of value in an array.

 FileNotFoundExecption: -This Exception is thrown when an attempt to access a non existent file.

 IOException: - This Exception is thrown when general I/O Failures.

 SecurityException: - This Exception is thrown when an Applet tries to perform insecure action.

 IllegalArgumentExecption: - This Exception is thrown when we pass irrelevant type of argument to a


method.

Exception Hierarchy: -
Object

Throwable

Error Exception

| | |
| | |
Virtual Machine Errors

| | | I/O Exceptions Runtime Exception


| | |
| | |
| | | | | |

IndexOutOfBoundsExecution
FileNotFoundException

| | | NullPointerException | | |
ArithmeticException

| | | | | |
EOF exceptions

| | | | | |
| | | | | |

Process of Exception Handling: -

Exception Handling works by transferring the execution of a program to an appropriate exception


handler when an exception occurs. So we need a way to tell the Java Virtual Machine (JVM) what code to
execute when a certain exception condition occurs.

Java‟s Exception Handling mechanism is implemented by using those keywords.

1. try.
2. catch.
3. throw.
4. finally.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 178 II.B.Sc., III Sem Java
1. try Block: - This keyword “try” used to specify a block of code that is likely to cause an error condition
and throw exception. This block is followed by one or more catch blocks to catch the exception thrown by
this block.

Syntax for try block: -

try
{
Statements; // generates an exception.
}

2. catch Block: - The keyword “catch” is used to catch and handle an exception thrown by the try block
which is preceded to it. If there are more than one catch block are defined for a single try block, then
appropriate catch block will receive the exception thrown by the try block. When a catch block receives an
exception object, then the code that is placed inside that block will be executed and remaining all the catch
blocks are skipped.

Syntax for try and nested catch block: -

try
{
Statements; // generates an exception.
}

catch(Exception1.type e1)
{
Statements; // Process the exception1.
}
catch(Exception2.type e2)
{
Statements; // Process the exception2.
}
------------
------------
------------

3. Throw Block: - The basic concept of exception handling are throwing an exception and catching it. This
is illustrating as:

try block
Exception Object Creator.
Statements that causes an
Throws exceptions
Exception
Objects

catch block

Statements that handling Exception Handler.


an exceptions

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 179 II.B.Sc., III Sem Java
4. Finally Block: - The keyword “finally” when a catch block completes execution control passes to the
statements on the finally block. The Java Compiler ensures that the finally block is executed in all
circumstances. When a try block completes without problem, the finally block executed. The finally block is
optional, for example: you may wish to close files or databases at this point, generally finally block is used.

Syntax for try , catch and finally block: -

try
{
Statements; // generates an exception.
}

catch(Exception.type e1)
{
Statements; // Process the exception.
------------
------------
------------
}
finally
{
------------
- - - - - - - - - - - - // Finally Block.
------------
}

// Illustrate the try and catch block statements in Java?

import java.lang.*;
class TryCatchest
{
public static void main(String[] args)
{
int a, b, c;
a = 10;
b = 0;
try
{
c = a / b;
System.out.println("This will Never Executed");
}
catch(Exception e)
{
System.out.println("Exception is Catched");
}
}
}
Save: - TryCatchest.java
Compile: - D:\Fareed Javaprog> javac TryCatchest.java
Run: - D:\Fareed Javaprog> java TryCatchest

Output: - Exception is Catched.

From the above program, once an exception is encountered, all the remaining statements are
skipped and the control is transferred to the catch block immediately. That‟s why the call to println() inside
the try block in never executed.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 180 II.B.Sc., III Sem Java
// Illustrate the Division by Zero by using exceptions in Java?

import java.lang.*;
class ChangeofException
{
public static void main(String[] args)
{
int a = 10;
int b = 5;
int c = 5; // int c = 10;
int res = 0;
try
{
res = a /(b-c); // Raises an Exception and throws an object.
}
catch(ArithmeticException ae) // Catches the object thrown.
{
System.out.println("Division by Zero");
}
System.out.println(" Results : = " + res);
}
}
Save: - ChangeofException.java
Compile: - D:\Fareed Javaprog>javac ChangeofException.java
Run: - D:\Fareed Javaprog>java ChangeofException

Test Data 1: - If “int c = 5;” then the following result.

Output: - Division by Zero


Results : = 0.

Test Data 2: - If “int c = 10;” then the following result.

Output: - Results : = -2

// Illustrate the Multiple catches block through an Exceptions in Java?

To handle multiple exceptional conditions with single try block, we use multiple catch blocks with
different types of exception object references.

import java.lang.*;
class MultipleofCatches
{
public static void main(String[] args)
{
int res = 0;
try
{
int a =Integer.parseInt(args[0]);
int b =Integer.parseInt(args[1]);
res = a + b;
}
catch(ArithmeticException ae)
{
System.out.println("Arithmetic Exception:");
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 181 II.B.Sc., III Sem Java
catch(ArrayIndexOutOfBoundsException aiob)
{
System.out.println("Array Index Out Of Bounds Exception:");
}
catch(Exception e)
{
System.out.println("Unknown Exception:");
}
System.out.println(res);
}
}

Save: - MultipleofCatches.java
Compile: - D:\Fareed Javaprog> javac MultipleofCatches.java
Run: - D:\Fareed Javaprog> java MultipleofCatches

Output: - Array Index Out Of Bounds Exception : 0

// Illustrate the program by using finally block an exception in Java?

import java.lang.*;
class FinallyExceptions
{
public static void main(String[] args)
{
int arr[] = new int[10];
try
{
for(int i=0; i<arr.length; i++)
arr[i] = i+1;
for(int i=0; i<arr.length; i++)
System.out.println(arr[i]*arr[i]);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
catch(ArithmeticException ae)
{
System.out.println(ae);
}
finally
{
System.out.println("Processing of Array Completed");
}
}
}
Save: - FinallyExceptions.java
Compile: - D:\Fareed Javaprog> javac FinallyExceptions.java
Run: - D:\Fareed Javaprog> java FinallyExceptions

Output: - 1 4 9 16 25 36 49 64 81 100

Processing of Array Completed.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 182 II.B.Sc., III Sem Java
// Illustrate the program on throw clause with the new keyword?

import java.lang.*;
class ThrowTest
{
public static void main(String[] args)
{
try
{
sample();
}
catch(NullPointerException e)
{
System.out.println("Catching on Exception :" + e);
}
}
static void sample() throws NullPointerException
{
System.out.println("Throwing a Null Pointer Exception:");
throw new NullPointerException();
}
}

Save: - ThrowTest.java
Compile: - D:\Fareed Javaprog>javac ThrowTest.java
Run: - D:\Fareed Javaprog>java ThrowTest

Output: -

Throwing a Null Pointer Exception:


Catching on Exception : java.lang.NullPointerException.

User-Defined Exceptions (or) Custom Exceptions: -

Java allows you to create your own exceptions classes so application specific problems can be
handled. Sometimes it is necessary to define our own exceptions classes to deal with various exceptional
conditions. The classes that are defined as sub classes to Exception class are called as user defined
exceptions. Every exception is a sub class to the class Exception in exception hierarchy.

When an exception is thrown, an object of a particular Exception sub type is instantiated and
handed over to the exception handler as an argument to the catch clause. To define a class that handles
any exceptional condition, we make the class as a sub class to the class “java.lang.Exception” by using the
keyword “extends”.

Syntax: - class <user defined exception class name> extends Exception


{
Class Definition;
}

Whenever the program wants to create an object to our own exception class, it can create an object
to the class and throw it out. To throw an object out of a try block, we use the keyword “throw”.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 183 II.B.Sc., III Sem Java
UNIT - IV
Chapter – 13
Applet Programming.
Introduction: -

An Applet is a small Java programs that are primarily used in Internet computing. They can
transport over the internet from one computer to another computer and executed by a Java compatible
web browser.

Applets can be embedded in web pages in two ways:

1. We can write our own Applet code and embed it in our own web pages; here the Applet is called
“Local Applet”.

2. We can download Applet code from a remote computer and then embed it into web pages; here the
Applet is called “Remote Applet”.

1. Local Applet: - An Applet is developed in locally and stored in a local system is known as “Local Applet”
when a web page is trying to find local Applet, it does not need to use Internet and therefore the local
system does not required the Internet connection. It simply searches the directories in the local system
and locates and loads the specified Applet.

Local Applet

Local Computer

2. Remote Applet: - A Remote Applet is that which is developed someone else and stored on the remote
computer connected to the internet. If your system connected to the internet, we can download the remote
Applet onto your computer via internet and run it. In order to locate and load a remote Applet, we must to
known the Applet‟s address on web. This address is known as URL (Uniform Resource Locator) and must be
specified the Applet‟s HTML document.

Remote Applet

Internet

Local Computer Remote Computer


(Client) (Server)

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 184 II.B.Sc., III Sem Java
Hierarchy of Applets: - Every Applet is implemented by creating a sub class of the Applet class.

Java.lang.object

Java.awt.component

Java.awt.container

Java.awt.panel

Java.awt.Applet

 Java.awt (Applet Window Tool Kit): - This package contains classes which are used for
implementing the Graphical User Interface (GUI) in Java. Some of the classes of this package are
Buttons, Lists, Menus, TextArea, and Window etc.

 Java.Applet: - This package contains classes for creating and implementing Applets. The most
important class in this package is Applet.

The Applet Class: - The abstract component class represents many of the different types of elements you
can include in Graphical User Interface (GUI). Some examples of the components that can be presented
are button, labels, list, choices, checkboxes etc. Because an Applet is also a component, you can receive
and process user interface elements.

Some methods defined by component:

Methods Description
Image create_Image(int width, int height) Returns Image object of dimensions width and height.
Font get_Font() Return the Current Font.
Color get_Foreground() Return the Foreground Color.
Dimension getSize() Return the size of this component.
public void paint(Graphics g) Paints the component on g.
void repaint() Requests that the JVM schedule a call to update()
void set_Background(Color c) Sets the background color to c.
void set_Foreground(Color c) Sets the Foreground color c.
public void update(Graphics g) Fills the components with its background color paint().

Some methods defined by Applet:

Void init() Initializes the Applet.


Void start() Start the Applet.
Void destroy() Destroys the Applet.
Void stop() Stops the Applet.
Image set_Image(URL url) Returns an Image object for the Image at URL.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 185 II.B.Sc., III Sem Java
Advantages of Applets: - The Applet Technologies provides many advantages for the programmers to
write Internet based programs.

 Applets technology is a cross platform technology witch allows us to work with different platforms
very easily.
 Applets technology is supported by majority of the web browsers available today.
 Applets will be cached by the web browsers which saves the network traffic.
 Applets can run at a speed that is compatible to other programming languages like C++.
 It can transfer the work from sever to client which reduces the burden on the servers

Disadvantages of Applets: -

 To execute an Applet, the browser needs a Java plug-ins.


 Applets can require a specific JRE (Java Resources Environment).

(Q). Explain How to Java differs from other Applications?

Applets Vs Applications: -

Applets Applications
Applets are not full-featured programs. They are Applications are full featured programs.
used to accomplish small tasks.
Applets do not use the main() method for Applications use the main() from which the program
initializing the execution of a program. execution starts.
Applets cannot run independently. They are run Applications can run at local systems command
on a web pages using HTML. prompt.
Applets cannot read from or write to the files in Applications can read from or write to the files in
the local computer. the local computers.
Applets cannot communicate with other servers Applications can communicate with any other
on the network. servers on the network.
Applets are restricted from using native methods Applications can access native methods from which
you can use libraries from other languages as C,
C++.
Applets cannot read local systems properties. Applications can read local system properties.

(Q). Explain the Applet Life Cycle in Java?

The Applet context calls methods in the Applet at the appropriate times during the life of the Applet
for specific purpose. As a each Java Applets is a sub class of “java.lang.Applet” class, it inherits a set of
methods of Applet class.

 Initialized the Applet. (init() method).


 Start the Applet. (start() method).
 Paint the Applet. (paint() method).
 Stop the Applet. (stop() method).
 Destroy the Applet. (destroy() method).

The methods of the Applet class responsible for these actions are “init()”, “start()”, “paint()”,
“stop()” and “destroy()”.

1. init() method: - This method is called as „initialized a Applet, once by the Applet context to inform
the Applet that it has been loaded into a system.

2. start() method: - This method is called as „Start the Applet‟, to start or continue the execution of
the Applet.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 186 II.B.Sc., III Sem Java
3. paint() method: - This method is called after Applet has been started.

4. stop() method: - This method is called when we want to stop the execution of the Applet.

5. destroy() method: - This method is called when system removes the Applet object.

NOTE: -
 The Initializing and destroying occurs only once.

 But Starting and Stopping the Applet occur every time the user returns to or leave the Applet
page.

Applet Life Cycle: -

Begin
Born
init()

start()

Runni stop()
paint() ng Idle

start()

destroy() Dead
End.

NOTE: -

 init() : - only once called in the life cycle of an Applet.


 start(): - It can be called more than one time in the life cycle of an Applet.
 paint(): - It can be called more than one time in the life cycle of an Applet.
 stop(): - It can be called more than one time in the life cycle of an Applet.
 destroy(): - only once called in the life cycle of an Applet.

Initializing/ Born State: - Applet enters the initialization state when it is first loaded. To make an Applet
into initialization state, “init()” of the Applet is called. When we call the init() method on a Applet it is said
to be “Born”. Initialization occurs only once in the life cycle of an Applet.

Running State: - When an Applet is born, it is said to be ready to run. It enters the running state when
we called “start()” method on the object. The method start() can be called multiple times in the life cycle of
an Applet. An Applet can move in and out from running state several times.

Idle State: - When an Applet is stopped from running, it is said to be in “Idle” state. An Applet moves into
idle state, when we leave the web page containing the currently running Applet.

Dead State: - An Applet is said to be “Dead” when it is removed from the memory. This happens
automatically when we close the browser. The method “destroy()” is used to kill an Applet.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 187 II.B.Sc., III Sem Java
(Q). Explain how to Preparing to write an Applet?

Before we try to write a Applets, we must make sure that Java is installed properly and also ensure
that either the Java “appletviewer” or a Java-enable browser is available. The steps involved in developing
and testing an Applet.

1. Building an Applet Code (.java file).


2. Create an executable Applet class (.class file).
3. Designing a web page using HTML tags.
4. Preparing Applet tag (<Applet> … </Applet>).
5. Incorporating <APPLET> tag into a web page.
6. Creating a HTML file.
7. Testing an Applet Code.

1. Building an Applet Code (.java file): - This requires that the Applet code imports the “java.awt”
package that contains the “Graphics” class. That an Applet code will have general format as below:

import java.awt.*;
import java.applet.*;
..................
..................

public class <Class Name> extends Applet


{
public void paint(Graphics g)
{
..................
.................. // Applet Operation Code.
..................
}

..................
..................
..................
}

Initializing/ Born State: - Applet enters the initialization state when it is first loaded. To make an Applet
into initialization state, “init()” of the Applet is called. When we call the init() method on a Applet it is said
to be “Born”. Initialization occurs only once in the life cycle of an Applet.

public void init()


{
..................
.................. // Action
..................
}

Running State: - When an Applet is born, it is said to be ready to run. It enters the running state when
we called “start()” method on the object. The method start() can be called multiple times in the life cycle of
an Applet. An Applet can move in and out from running state several times.

public void start()


{
..................
.................. // Action.
..................
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 188 II.B.Sc., III Sem Java
Idle State: - When an Applet is stopped from running, it is said to be in “Idle” state. An Applet moves into
idle state, when we leave the web page containing the currently running Applet.

public void stop()


{
..................
.................. // Action.
..................
}

Dead State: - An Applet is said to be “Dead” when it is removed from the memory. This happens
automatically when we close the browser. The method “destroy()” is used to kill an Applet.

public void destroy()


{
..................
.................. // Action.
..................
}

Display State: - Applet moves to display state whenever it has to perform some output operations on
screen. This happens immediately after the Applet enters into the running state. The “paint ()” method is
accomplished this task. Almost every Applet have paint () method.

public void paint(Graphics g)


{
..................
.................. // Display Statements.
..................
}

2. Create an executable Applet class (.class file): -

Executable Applet is nothing but the “.class” file of the Applet, which is obtained by compiling
the source code of Applet. Compiling an Applet is exactly the same as compiling the applications. Therefore
we can use the Java compiler to compile the Applet.

Let us consider the “HaiApplet” Applet is created. This Applet has been stored in a file called
“HaiApplet.java”. Here are the steps required for compiling the “HaiApplet” Applet.

 Move to the directory containing the source code and type the following command:
D:\Fareed Javaprog>javac HaiApplet.java.

 The Compiled output file called “HaiApplet.class” is placed in the same directory as the source.

 If any error message is receive, then we must check for errors, correct them and compile the Applet
again.

3. Designing a web page using HTML tags: - In order to run a Java Applet, it is first necessary to have
a web page that references that Applet.

A web page is basically made up a text and HTML tags that can be interpreted by a web
browser or a Applet Viewer. Like Java source code. A web page also known as HTML page or HTML
Document. Web pages are stored using a file name extension “.html”. Such as “HaiApplet.html” such files
are referred to as HTML files. HTML files should be stored in the same directory as the compiled code of the
Applet.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 189 II.B.Sc., III Sem Java
Web pages include the both text that we want to display and HTML (Commands) to web browser. A
web page is marked by an opening HTML tag <HTML> and closing HTML tag </HTML>. A Slash (/) is
signifies the end of the tag. HTML is divided into major three sections.

 Head Section.
 Title Section.
 Body Section.

 Head Section: - In HTML the Head section is the primary section. This is specify the heading of the
document .The header part will be using <HEAD> tag and closed tag is </HEAD> tag.

 Tile Section: - In this section we mansion the name of title of current browser window. The tag
<TITLE> and </TITLE>.

 Body Section: - In this section contain the tag <BODY> and </BODY>, the entire information
about the web page and its behaviors. We can set up many options to indicate how our page must
appear on the screen (like color, location, sound etc.)

Structure of HTML Document / Page: -

<HTML>
<head>
....... .. Head Section.
....... ..
</head>
<title>
....... ..
....... .. Title Section.
</title>
<body>
.. .......
.. ....... Body Section.
.. .......
</body>
</HTML>

Example: -

<html>
<head> My Details </head>
<title> Profile </title>
<body>
<h1> Shaik Mohammad Fareed MCA,IRPM </h1>
<h2> Department of Computers Science </h2>
</body>
</html>

Save: - MyDetails.html

Run: - D:\Fareed Javaprog\MyDetails.html

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 190 II.B.Sc., III Sem Java
Title

Header

Body of
Document

4. Preparing Applet tag (<Applet> … </Applet>): - The Applet tag supplies the name of the Applet
to be loaded and tells the browser how much space the applet required. The pair of <Applet ….> and
</Applet> tag in body section. The <Applet…..> tag indicates that it contains certain attributes that must
specify. The Applet tag gives below specification to minimum to require placed Applet on a web page.

Syntax: - <Applet
code = [Applet Java class name .class]
width = 100, height = 200>
</Applet>

Example: -

<applet code = "HaiApplet.class" width =100 height = 100> </applet>

5. Incorporating <Applet> tag in web page and Creating the Web page: -

The below way to merge the Applet tag in the web page:

Example: -

<html>
<body>
<applet code = "HaiApplet.class" width =500, height = 500>
</applet>
</html>
</body>

6. Running the Applet: - Now that we have created applet file as well as the HTML file containing the
Applet, we must following files in our current directory:

 HaiApplet.java.
 HaiApplet.class.
 HaiApplet.html.

To run an Applet we have required one of the following tool:

 Java-enable Web Browser (such as HotJava, Netscape Navigator, Internet Explore etc).
 Java Applet Viewer.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 191 II.B.Sc., III Sem Java
If we use Java-enable web browser, we will be able to see the entire web page containing the
Applet. If we use the “appletviewer” tool, we will only see the applet output. The appletviewer is the part of
the JDK (Java Development Kit) that we have using so far. We use it to run applet as follows:

D:\Fareed Javaprog> appletviewer HaiApplet.html

NOTE: - That the arguments of the HaiApplet are not the “.java” or “.class” file, but rather “.html” file.

// Illustrate the sample Applet Program to insert the text at the specified position in Java?

import java.awt.*;
import java.applet.*;
public class HaiApplet extends Applet
{
private String msg;
public void init()
{
msg = "Hello Welcome to Applet Program Mr. Shaik Mohammad Fareed";
System.out.println(" In init() Method....!");
}
public void start()
{
System.out.println("In start() Method....!");
}
public void stop()
{
System.out.println("In stop() Method....!");
}
public void destroy()
{
System.out.println("In destroy() Method....!");
}
public void paint(Graphics g)
{
System.out.println("In paint() Method...!");
g.setColor(Color.red);
g.drawString(msg, 100,120);
}
}

Save: - HaiApplet.java

Compile: - D:\Fareed Javaprog> javac HaiApplet.java

<html>
<body>
<applet code = "HaiApplet.class" width =500 height = 500>
</applet>
</html>
</body>

Run: - D:\Fareed Javaprog>appletviewer HaiApplet.html

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 192 II.B.Sc., III Sem Java
D:\Fareed Javaprog>appletviewer HaiApplet.html

In init() Method....! // When Applet is Initialized.


In start() Method....! // When Applet is Start.
In paint() Method....! // When Applet is Moves or Painted.
In paint() Method....!
In paint() Method....!
In stop() Method....! // When Applet is Stopped.
In destroy() Method....! // When Applet is Destroyed.

// Illustrate the sample Applet Program in Java?

import java.awt.*;
import java.applet.*;
public class Helloo extends Applet
{
public void paint(Graphics g)
{
g.drawString("Shaik", 10, 10);
}
}

Save: - Helloo.java

Compile: - D:\Fareed Javaprog> javac Helloo.java

<html>
<body>
<applet code = "Helloo.class" width =100 height = 100>
</applet>
</body>
</html>

Save: - Helloo.html

Running an Applet: - There are two ways or methods in which you can run an Applet. Executed an Applet
with in a Java-Compatible Web Browser, such as Internet Explorer, Netscape Navigator etc.

Using an Applet Viewer, such as the standard JDK (Java Development Kit) “appletViewer”. An Applet
Viewer executed you Applet in a window. This is the fastest and easiest

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 193 II.B.Sc., III Sem Java
Method 1: - D:\Fareed Javaprog>appletviewer Helloo.html

Output: -

Method 2: Browse: - D:\Fareed Javaprog\Helloo.html

Output: -

(Q). Explain the passing parameters to Applet? (or) Discuss the <PARAM> tag using Applets in
Java with an example?

We can pass the parameters to an Applet through the HTML web page in which we embed the
Applet. Java Applet can retrieve these parameters values and manipulate them. We can supply user-define
parameters to an Applet using <PARAM> tag of HTML.

Each <PARAM> tag has a name and a value associated with it. The Applet code can retrieve the
value of a parameter by using its name.

Syntax: - <PARAM name = “Parameter_Name” Value = “Text_Value”>

The Parameters are passed to an Applet when it is loaded into a memory. We can define “init()”
method of the Applet to get these parameters. We use the method “get Parameter()” by passing the name
of the parameters as arguments.

// Illustrate the <PARAM> values using in Applets?


import java.awt.*;
import java.applet.*;
public class PassParam extends Applet
{
String welcome = "Introduction Message";
String author = "Who is the Author";
public void init()
{
welcome = getParameter("welcome");
author = getParameter("author");
}
public void paint(Graphics g)
{
g.drawString(welcome, 50, 50);
g.drawString(author, 50, 150);
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 194 II.B.Sc., III Sem Java
Save: - PassParam.java

Compile: - D:\Fareed Javaprog> javac PassParam.java

<html>
<body>
<applet code = "PassParam.class" width =100 height = 200>
<param name = "welcome" value = "Welcome to Java">
<param name = "author" value = "Prepared by : Mr. Shaik Mohammad Fareed MCA">
</applet>
</html>
</body>

Run: - D:\Fareed Javaprog>appletviewer PassParam.html

// Applet for Drawing the Lines?

import java.awt.*;
import java.applet.*;
public class LineRect extends Applet
{
public void paint(Graphics g)
{
g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
g.fillRect(60,10,30,80);
g.drawRoundRect(10,100,80,50,10,10);
g.fillRoundRect(20,110,60,30,5,5);
g.drawLine(100,10,230,140);
g.drawLine(100,140,230,10);
}
}

Save: - LineRect.java

Compile: - D:\Fareed Javaprog> javac LineRect.java

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 195 II.B.Sc., III Sem Java
<html>
<body>
<applet code = "LineRect.class" width =250 height = 200>
</applet>
</html>
</body>

Save: - LineRect.html

Run: - D:\Fareed Javaprog> appletviewer LineRect.html

// Applet for drawing 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
}
}

Save: - Face.java

Compile: - D:\Fareed Javaprog> javac Face.java

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 196 II.B.Sc., III Sem Java
<html>
<body>
<applet code = "Face.class" width =250 height = 200>
</applet>
</html>
</body>

Save: - Face.html

Run: - D:\Fareed Javaprog> appletviewer Face.html

// Illustrate the program to display Image on Applet in Java?

import java.awt.*;
import java.applet.*;
public class ImageLoad extends Applet
{
Image image;
public void init()
{
image = getImage(getDocumentBase(), getParameter("img"));
}
public void paiant(Graphics g)
{
g.drawImage(image,0,0,this);
}
}

Save: - ImageLoad.java

Compile: - D:\Fareed Javaprog> javac ImageLoad.java

<html>
<body>
<applet code = "ImageLoad.class" width =250 height = 200>
<param name ="img" value = "D:\ObjectOriented Programming JAVA Notes\Java Fareed Services.jpeg">
</applet>
</html>
</body>

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 197 II.B.Sc., III Sem Java
Save: - ImageLoad.html

Run: - D:\Fareed Javaprog> appletviewer ImageLoad.html

// Illustrate to display the Font Events by using Applet in Java?

import java.awt.*;
import java.applet.*;
public class FontText extends Applet
{
public void paint(Graphics g)
{
int baseline = 100;
g.setColor(Color.black);
g.drawLine(0, baseline, 200, baseline);
g.setFont(new Font("Serif", Font.BOLD, 26));
g.setColor(Color.red);
g.drawString("Mohammad Fareed",5,baseline);
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 198 II.B.Sc., III Sem Java
Save: - FontText.java

Compile: - D:\Fareed Javaprog>javac FontText.java

<html>
<body>
<applet code = "FontText.class" width =250 height = 200>
</applet>
</html>
</body>

Save: - FontText.html

Run: - D:\Fareed Javaprog> appletviewer FontText.html

// Illustrate the ActionListener interface Applet in Java?

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class SumofTwoNumbers extends Applet implements ActionListener
{
TextField a, b;
Label one;
Label two;
Button tot;
public void init()
{
one = new Label("Enter the A Value : ");
two = new Label("Enter the B Value : ");
a = new TextField(8);
b = new TextField(8);
tot = new Button("Click Result Now");
a.setText("");
b.setText("");
tot.addActionListener(this);
add(one);
add(a);
add(two);
add(b);
add(tot);
}
public void paint(Graphics g)
{
int tot = 0;
try
{
String val1 = a.getText();
String val2 = b.getText();
tot = Integer.parseInt(val1) + Integer.parseInt(val2);
}
catch(Exception e) {}
g.drawString("Result is : ", 30, 100);
g.drawString(String.valueOf(tot),80,100);
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 199 II.B.Sc., III Sem Java
public void actionPerformed (ActionEvent ae)
{
Button source = (Button)ae.getSource();
repaint();
}
}

Save: - SumofTwoNumbers.java

Compile: - D:\Fareed Javaprog>javac SumofTwoNumbers.java

<html>
<body>
<applet code = "SumofTwoNumbers.class" width =250 height = 200>
</applet>
</html>
</body>

Save: - SumofTwoNumbers.html
Run: - D:\Fareed Javaprog> appletviewer SumofTwoNumbers.html

// The Following Applet shows how to process Mouse Click, Enter, Exit, Press and Release Events?

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MouseEventTest extends Applet implements MouseListener
{
public void init()
{
addMouseListener(this);
}
public void mouseClicked(MouseEvent me)
{
setBackground(Color.green);
repaint();
}
public void mouseEntered(MouseEvent me)
{
setBackground(Color.blue);
repaint();
}
public void mouseExited(MouseEvent me)
{
setBackground(Color.yellow);
repaint();
}
public void mousePressed(MouseEvent me)
{
setBackground(Color.red);
repaint();
}
public void mouseReleased(MouseEvent me)
{
setBackground(Color.white);
repaint();
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 200 II.B.Sc., III Sem Java
Save: - MouseEventTest.java

Compile: - D:\Fareed Javaprog>javac MouseEventTest.java

<html>
<body>
<applet code = "MouseEventTest.class" width =250 height = 200>
</applet>
</html>
</body>

Save: - MouseEventTest.html

Run: - D:\Fareed Javaprog>appletviewer MouseEventTest.html

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 201 II.B.Sc., III Sem Java
Chapter – 14
Package.

(Q). What is package? Explain how to create the Packages in Java with an example?

Definition of Package: - “A Package is a group of classes and interfaces”.


(OR)
“Packages are Java‟s way of grouping a variety of classes and/or interfaces together”. The
grouping is usually done according to purpose and functionality. In fact, Packages acts as a “Containers”
the Classes.
(OR)
Java supports another important feature called package, which Isolates one class from
another class. A package is a sub directory or container of classes and interfaces. A Java package bundles
or wraps a set of classes and interfaces into a single unit.

Advantages and Benefits of Packages: - By organizing our classes into packages we achieve the
following benefits:

1. The Classes contains in the packages of other program can be easily reused.

2. It helps users to group similar classes and interfaces.

3. In Packages, classes can be unique compared with classes with classes in other packages. That is no
two classes can have same name in a package.

4. Two different classes in two different packages can have the same name.

5. 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. It is
possible to change the implementation of any method without affecting the rest of the design.

Types of Packages: - Java packages are classified into two types.

1. Java API (Application Programming Interface) Packages.


2. User Defined Packages.

1. Java API (Application Programming Interface) Packages: - (Java Built-In Package)

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)”.
Classes and Methods are parts of the “Java Standard Library (JSL)” also known as the “Application
Programming Interface (API)”.

Java Environment

(I). Java Development Kit (JDK) (II). Java Standard Library (JSL)
(or)
Application Programming Interface (API).

 Java Development Kit (JDK) based on part of „Development Tools‟.


 Java Standard Library (JSL) or Application Programming Interface based on part of „Classes & Methods‟.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 202 II.B.Sc., III Sem Java
(I). Java Development Kit (JDK): -

Java Development Kit (JDK) comes with a collection of tools which are essential to developing and
running Java programs. The Java Development Kit (JDK) following elements are:

 javac. (Java Compiler)


 java. (Java Interpreter)
 javap. (Java Disassembler)
 jdb. (Java Debugger)
 javadoc. (Java Document)
 javah. (Java Header File Generator)
 Appletviewer. (Java Applets)
 Text Editor.

1. javac: - Java Compiler, named „javac‟. It translates Java Source Codes to bytecodes file, that the
Interpreter can read or understands.
2. java: - Java Interpreter, names „java‟. Which runs Applets and Applications by reading and interpreting
bytecode files.
3. javap: - Java Disassembler named „javap‟. It encodes bytecodes to program files.
4. jdb: - Java Debugger named „jdb‟. Which helps us to find errors and remove them from the programs?
5. javadoc: - Java Documentation named „javadoc‟. It creates HTML formats documents from java code.
6. javah: - Java Header File Generator named „javah‟. It is produces Header files for native C-Language.
7. Appletviewer: - Java Applet Viewer named „Appletviewer‟. It enables us to run Java Applets.
8. Text Editor: - To create a Java program, we need to create a source code file using Text Editor.

(II). Java Stranded Library (JSL) or Application Programming Interface (API): -

Java API (Application Programming Interface) or JSL (Java Stranded Library) consists of nearly
about 1500 classes and interfaces and more than 13000 methods. These classes and methods are grouped
in to several packages. The most commonly used packages are following below.

Java

lang net util io awt Applet sql

 Java.lang: - This package contains language support classes. It includes classes like String, Math,
Thread etc.,

 Java.util: - This package contains language utility classes. Such as Vectors, Has Tables, Random,
Data etc.

 Java.io: - This package contains classes which support input / output of data.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 203 II.B.Sc., III Sem Java
 Java.awt: - This package contains classes which are used for implementing the Graphical User
Interface (GUI) in Java. Some of the classes of this package are Buttons, Lists, Menus, TextArea,
Window etc.

 Java.net: - This package contains classes which are used for networking. That is, for
communication between interconnected with local computers as well as with internet servers.

 Java.Applet: - This package contains classes for creating and implementing Applets. The most
important class in this package is Applet.

 Java.sql: - This package contains classes for implementing database connectivity. The classes in
this package are used for connecting to the database and performing operations on the database.

2. User Defined Package: - We can create out own packages as well. We have created programs without
using any packages name, so classes and interface will be posted to a default package which is a package
without any name. default packages are used only for temporary applications.

Importing Packages: -

The Java library code is present in in-built packages with specific names. These
package names corresponding to directories. Thus, the package, „java.lang‟ can be found in the sub-
directory „java\lang‟.

Java automatically looks in the package „java.lang‟ when we run our programs. In case, we want
the program to use classes or interfaces from packages other than „java.lang‟, these packages have to be
imported explicitly using the import statement. The import statement should be the first statement of such
programs.

Import Statement: To create a package includes a „package‟ command as the first statement in a Java
Source file. Any classes declared within that file will belong to the specified package. The package
statement defines a name space in which classes are stored. Import statement can be used to search list of
packages for a particular class.

Import Statement is used to instruct the Interpreter to load a class or set of classes or an
interfaces or set of interfaces into a program. Import java.lang.* This Import is API (Application
Programming Interface) or JSL (Java Stranded Library) consists the respected classes and methods.

Syntax of Representation of Import Statement: -

Import Package Name.Class Name;


(or)
Import Package Name.*;

Let us consider the concept of importing packages with the help of an example. Consider
following statements:

1. import java.Applet.*;
2. import java.awt.*;
3. import java.Applet.Applet;
4. import java.awt.Button;

All the four statements above import two packages.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 204 II.B.Sc., III Sem Java
 Statement 1 and 2 import the packages „java.Applet‟ and „java.awt‟.

 Statement 3 and 4 also import the same packages, but by using a different technique.

 The first two statements could be viewed as following:

import java.Applet.*;

Keyword Package Name All the public classes and interfaces of the specified Package.

The above statement import all the public classes and interfaces of the packages, “java.Applet”.

 import java.awt.*;

Keyword Package Name All the public classes and interfaces of the specified Package.

The above statement import all the public classes and interfaces of the packages, “java.awt”.

 Similarly, the last two statements could be viewed as follows:

import java.Applet.Applet;

Keyword Package Name Class Name

The above statement imports the Applet class of the package “java.Applet”.

 import java.awt.Button;

Keyword Package Name Class Name

The above statement imports the Button class of the package “java.awt”.

Thus, in the first two statements, we are importing all the public classes and interfaces of
the respective packages, whereas in the last two statements, we are importing only the specified classes of
the respectively packages. An important point to be noted is that, we can import only the public classes in
packages.

NOTE: - There is not much different between using the asterisk (*) to import all the classes of a package
and importing only a required class by specifying its name. In reality, only those classes which are actually
used in the program are imported. This is because, Java links in classes only when they are actually used
in a program.

Some packages contain sub packages. Importing package only imports the classes directly
under that package and not the sub packages of that package. For importing classes in a sub package, we
have to explicitly specify the sub package name.

Example: - For example consider the following statement.

import java.awt.event.*;

In the above statement, „java.awt‟ is a package and event is its sub package. The statement
tells the compiler to import all the public classes of the sub package event of the package „java.awt‟.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 205 II.B.Sc., III Sem Java
Creating Packages: -

In a program, we can created and use our own packages which may include classes as well
as interfaces. We use the keyword „package‟. Here the keyword „package‟ is used to define the hierarchy of
the package structure. For this, we just have to write the following statement as the first statement of the
program.

Syntax: - package <PackageName>;


<Access specifier> class <Class Name>
{
.............
.............
Body of Class;
.............
.............
}

Example: - package firstPackage; // Package Declarations.


public class FirstClass // Class definition.
{
.............
.............
Body of Class;
.............
.............
}
Here Package name is „firstPackage‟ the class name is „FirstClass‟ is now consider a part of this
package. This listing will be saved as a file called “Firstclass.java”, and located in a directory named
„firstPackage‟. When a source file is compiled, Java created a „.class‟ file and store in the same package.

Create our own packages involves the following steps:

1. Declare the package at the beginning of a file using the form : package PackageName;
2. Define the class that is to be put in the package and declare it „public‟.
3. Create a sub directory under the directory where the main source files are stored.
4. Store the listing as the “classname.java” file in the sub directory created.
5. Compile the file. This creates “.class” file in the sub directory.

We can add multiple interfaces and classes with a single source file or individual files. We can define
packages and sub packages using single package statement.

Syntax: - package <Package Name>.<Sub Package Name>;


<Access specifier> class <Class Name>
{
.............
.............
Body of Class;
.............
.............
}

NOTE: - Here each package and its sub packages must be separated with a dot ( . ) operator.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 206 II.B.Sc., III Sem Java
Example: - package student; // Define a Package with the name „student‟.
public class StudentMarks // Add the class „SutdentMarks‟ to the package.
{
long sid;
string sname;
string result;
public void setValues()
{

}
public void displayValues()
{

}
}
The above example creates packages with the name „student‟ and adds the class „StudentMarks‟ to
that package. After compiling the above source file creates a sub-directory with the name „student‟ and
palaces the „.class‟ file inside it.

Accessing a Package: -

The class and interface of a package can be accessed either using a fully qualified name or
using shortcut approach through the „import‟ statement.

The fully qualified name of a class or interface contains all its package and sub-package names
separated with dot ( . ) operator appending with the class or interface name. The general form of import
statement for searching a class is as follows:

Syntax: - import package 1 [.package 2] [.package 3].class name / interface name;

Here „package 1‟ is the name of the top level package, „package 2‟ is the name of the package that
is inside the „package 1‟ and so on. We can have any number of packages in a package hierarchy. Finally,
the explicit class name 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. The following is an
example of importing a particular class:

import firstPackage .secondPackage. MyClass;

After defining this statement, all the members of the class „MyClass‟ can be directly accessed using
the class name or its objects directly without using the package name. we can also use another approach
as follows:
import packagename.*;

Here, „packagename‟ may denote a single package or hierarchy of packages as mentioned earlier.
The airsick ( * ) indicates that the complier should search this entire package hierarchy where it encounter
a class name. this implies that we can access all classes contained in the above package directly.

 The major drawback of the shortcut approach is that it is difficult to determine from which package
a particular member came. This is particularly true when a large number of packages are imported.

 But the advantage is that we need not have to use long package names repeatedly in the program.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 207 II.B.Sc., III Sem Java
Let us consider an example to understand how packages are created. This program
involves a Class „Salary‟, an Interface „Commission‟ and a Class „Income‟ derived from the former two. We
will modify this program to create a package, „MyPack‟ containing the Class „Salary‟ and the Interface
„Commission‟. Then we will import this package to another file containing a program in which the Class
„Income‟ has been defined.

 Main Directory Name is “D:\Fareed Javaprog”.


 Sub-Directory Name is “D:\Fareed Javaprog\MyPack”.
 Package Name is “MyPack”.
 Sub-Directory (MyPack) consist one class, that class name is “Salary”.
 Sub-Directory (MyPack) consist one interface, that interface name is “Commission”.
 Main Directory (D:\Fareed Javaprog )consist one class, that class name is: “Income”.

This process is done in the following steps:

Step 1: - Switch over to the MS-DOS mode and create a new sub-directory in the current directory
“D: \Fareed Javaprog” by typing the following commands at the DOS Prompt:

Start  Programs  Accessories  Command Prompt. (Press Enter)

C:\Documents and Settings\ShaikMohammadFareed> d:

D:\> md Fareed Javaprog Create a Main Directory “Fareed Javaprog”.


D:\> cd Fareed Javaprog (md  means Make Directory)
(cd  means Create Directory)

D:\Fareed Javaprog> md MyPack Create a Sub-Directory “MyPack”


D:\Fareed Javaprog> cd MyPack

D:\Fareed Javaprog\MyPack> edit

Step 2: - make the Sub-Directory „MyPack” the current directory by typing the following command:

D:\Fareed Javaprog> cd MyPack

Press enter key. The current directory now becomes “MyPack” and DOS prompt appears:

D:\Fareed Javaprog\MyPack>

Step 3: - Open the Notepad window by typing the following command at the DOS Prompt.

D:\Fareed Javaprog\MyPack>Notepad

Step 4: - Write the following code in the Notepad Window.

package MyPack;
public class Salary // Salary class defined
{
public void show_salary()
{
System.out.println("Salary : 40000");
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 208 II.B.Sc., III Sem Java
Save the above code block with the name “Salary.java” and compile it, with this, we have places the class
„Salary‟ inside the package „MyPack‟. (“D:\Fareed Javaprog\MyPack\Salary.java”).

Step 5: - Open another new Notepad window by typing the following command at the DOS Prompt.

D:\Fareed Javaprog\MyPack>Notepad

Step 6: - Write the following code in the Notepad Window.

package MyPack;
public interface Commission // Interface Commission defined.
{
void show_comm(); // only Declaration.
}

Save the above code block with the name “Commission.java” and compile it, with this, we have places the
class „Commission‟ inside the package „MyPack‟. (“D:\Fareed Javaprog\MyPack\Commission.java”).

With this we have include the interface Commission inside the package „MyPack‟. Thus the
package, „MyPack‟, now contains the Class „Salary‟ and Interface „Commission‟.

Step 7: - Close the Notepad Window and return to the MS-DOS Prompt.

Step 8: - Change the Current Directory from „MyPack‟ to „Fareed Javaprog‟, by typing following command:

D:\Fareed Javaprog\MyPack> cd.. (cd.. helps to removing last directory form the list).

Press enter key. This makes the directory „Fareed Javaprog‟ the Current directory. “D:\Fareed Javaprog>”.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 209 II.B.Sc., III Sem Java
Step 9: - Open another new Notepad window by typing the following command at the DOS Prompt.

D:\Fareed Javaprog>Notepad

Step 6: - Write the following code in the Notepad Window inside the current directory “D:\Fareed
Javaprog”. We will import the package (MyPack) and use it along with the Class „Income‟.

import MyPack.*;
class Income extends Salary implements Commission
{
public void show_comm() // Method defined.
{
System.out.println("Commission : 5000");
}
void show_income() // Method defined.
{
System.out.println("Total Income Includes");
show_salary(); // Method of the class Salary and Interface.
show_comm(); // Commission Called.
}
public static void main(String args[])
{
Income obj = new Income(); //Object Created.
obj.show_income(); // Method called using the object.
}
}

Save the above code block with the name “Income.java” and compile it, with this, we have places the class
„Income‟. (“D:\Fareed Javaprog\Income.java”).

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 210 II.B.Sc., III Sem Java
Save: - Income.java
Compile: - D:\Fareed Javaprog> javac Income.java
Run: - D:\Fareed Javaprog> java Income

Output: - Total Income Includes:


Salary : 40000.
Commission : 5000

// Illustrate Arithmetical Operations by using Packages in Java?

 Main Directory Name is “D:\Fareed Javaprog”.


 Sub-Directory Name is “D:\Fareed Javaprog\Arithemetic”.
 Package Name is “Arithemetic”.
 Sub-Directory (Arithemetic) consist one class, that class name is “Aop”.
 Main Directory (D:\Fareed Javaprog )consist one class, that class name is: “AritheProg”.

This process is done in the following steps:

Step 1: - Switch over to the MS-DOS mode and create a new sub-directory in the current directory
“D: \Fareed Javaprog” by typing the following commands at the DOS Prompt:

Start  Programs  Accessories  Command Prompt. (Press Enter)

C:\Documents and Settings\ShaikMohammadFareed> d:

D:\> md Fareed Javaprog Create a Main Directory “Fareed Javaprog”.


D:\> cd Fareed Javaprog (md  means Make Directory)
(cd  means Create Directory)

D:\Fareed Javaprog> md Arithemetic Create a Sub-Directory “Arithemetic”


D:\Fareed Javaprog> cd Arithemetic

D:\Fareed Javaprog\Arithemetic> edit

Step 2: - make the Sub-Directory „Arithemetic” the current directory by typing the following command:

D:\Fareed Javaprog> cd Arithemetic

Press enter key. The current directory now becomes “Arithemetic” and DOS prompt appears:

D:\Fareed Javaprog\ Arithemetic >

Step 3: - Open the Notepad window by typing the following command at the DOS Prompt.

D:\Fareed Javaprog\ Arithemetic k>Notepad

Step 4: - Write the following code in the Notepad Window.

package Arithemetic; // Package Name is Arithemetic


public class Aop // Class Name of Arithemetic Package is Aop.
{
public Aop(){}
public float add(float x, float y)
{
return(x+y);
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 211 II.B.Sc., III Sem Java
public float sub(float x, float y)
{
return(x-y);
}
public float mul(float x, float y)
{
return(x*y);
}
public float div(float x, float y)
{
return(x/y);
}
}

Save the above code block with the name “Aop.java” and compile it, with this, we have places the class
„Aop‟ inside the package „Arithemetic‟. (“D:\Fareed Javaprog\ Arithemetic\Aop.java”).

Step 5: - Change the Current Directory from „Arithemetic‟ to „Fareed Javaprog‟, by typing following
command:

D:\Fareed Javaprog\Arithemetic> cd.. (cd.. helps to removing last directory form the list).

Press enter key. This makes the directory „Fareed Javaprog‟ the Current directory. “D:\Fareed Javaprog>”.

Step 6: - Open another new Notepad window by typing the following command at the DOS Prompt.

D:\Fareed Javaprog>Notepad

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 212 II.B.Sc., III Sem Java
Step 7: - Write the following code in the Notepad Window inside the current directory “D:\Fareed
Javaprog”. We will import the package (Arithemetic) and use it along with the Class „AritheProg‟.

import Arithemetic.*;
import java.io.*;
class AritheProg
{
public static void main(String args[]) throws IOException
{
Aop A1 = new Aop();
DataInputStream in = new DataInputStream(System.in);
float n, m, r = 0;
int ch;
System.out.println("1 - Addition of two values ");
System.out.println("2 - Subtraction of two values ");
System.out.println("3 - Multiplication of two values ");
System.out.println("4 - Division of two values ");
System.out.println("Select any one operation in a list");
ch = Integer.parseInt(in.readLine());
System.out.println("Enter n , m Values ");
n = Float.valueOf(in.readLine()).floatValue();
m = Float.valueOf(in.readLine()).floatValue();
switch(ch)
{
case 1:
r = A1.add(n,m);
break;
case 2:
r = A1.sub(n,m);
break;
case 3:
r = A1.mul(n,m);
break;
case 4:
r = A1.div(n,m);
break;
default:
System.out.println("Invalid Number Choose Correct Operation");
}
System.out.println("The Two Values Result is : = " + r);
} }

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 213 II.B.Sc., III Sem Java
Save the above code block with the name “AritheProg.java” and compile it, with this, we have places the
class „AritheProg‟. (“D:\Fareed Javaprog\A AritheProg.java”).

Save: - AritheProg.java
Compile: - D:\Fareed Javaprog> javac AritheProg.java
Run: - D:\Fareed Javaprog> java AritheProg

Output: -

1 - Addition of two values.


2 - Subtraction of two values
3 - Multiplication of two values
4 - Division of two values

Select any one operation in a list:

Enter n , Values: 25
50

The Two values of Result is : = 75.0

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 214 II.B.Sc., III Sem Java
(Q) Explain the Hidden Classes in Java?

When we are importing a package using asterisk ( * ), all the classes are imported. However, we
may perform to „not import‟ certain classes. That is, we may like to hidden these classes from accessing
from outside of the package. Such class should be declared “not public”.

Example: - package fareed;


public class x // Public Class available outside
{
// Body of X Class

}
class y // Not Public , hidden
{
// Body of Y Class

}
Here, the Class „Y‟ which is not declared public is hidden from outside of the package „fareed‟. This
class can be seen and use only by the other classes in same package.

Now consider the following code, which import the Java package „fareed‟ that consist Classes
„X‟ and „Y‟.

Example: - import fareed.*;


x object x; // OK Class „X‟ is available.
y object y; // Not OK Class „Y‟ is not available.

Java compiler would generated an error message for this code because the class „Y‟ which is not
been declared „public‟. Is not imported and therefore not available for creating its objects.

(Q). Explain the Static Import in Java?

Java supports a special feature called „static import‟. That eliminates the need of qualifying
a static member of an imported class or interface. We can use static import to import static members of
the classes and interfaces from packages. We can use these static members without qualifying the package
name.

Syntax: - import static package name . sub package name . class name . static member name;
(or)
import static package name . sub package name . class name . *;

Example: - import static java.lang.Math.pi;

// Illustrate the Area of Circle by using Static Import in Java?


import static java.lang.Math.*;
public class StaticCircle
{
public void circle(double r)
{
double area = PI * r * r;
System.out.println("The Area of Circle is : = " + area);
}
public static void main(String args[])
{
StaticCircle obj = new StaticCircle();
obj.circle(2.3);
}
}

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 215 II.B.Sc., III Sem Java
Chapter -15
Managing Input/Output Files in Java

(Q) What is Stream? Discuss about Input & Output Classes in Java?

Stream: - “A Stream represented flow of data from one place to another place”. It is like a water-pipe
where water flows. Like a water-pipe carries water from one place to another.

A Stream carries data from one place to another place. A Stream can carry data from
Keyboard to Memory or from Memory to Printer or from Memory to a Files, etc. A Stream is always
required if we want to move data from one place to another. A Stream is required to accept Input from the
Keyboard.

All Streams are represented by classes in “java.io” (io: Input & Output) Package. This
Package contains a lot of classes, all of which can be classified into two basic categories: Basically, there
are two types of Streams:

 Input Stream.
 Output Stream.

 Input Stream: - “Input Stream is those Streams which Receive or Read data coming from some
other place”.

 Output Stream: - “Output Stream is those Streams which Send or Write data to some other
place”.

The “System Class” is found in “java.lang” package and has three fields as shown below:

 System.in: - This represents InputStream object, which by default represent standard input
devices, therefore Keyboard.

 System.out: - This represents OutputStream object, which by default represent standard output
devices, therefore Monitor.

 System.err: - This field also represents PrintStream object, which by default represents Monitor.

NOTE: - That both System.out & System.err can be used to represent the Monitor and hence any of these
two can be used to send data to the Monitor.

Example: - System.out.println (“Shaik Mohammad Fareed”);


(or)
System.err.println (“Hello Mr. Shaik Mohammad Fareed.”);

(Q) Explain the InputStreamReader class Constructors and methods?

The “java.io.InputStreamReader” class server as a bridge between “Byte Stream and


Character Stream”. It reads Bytes from the Input Stream and translates them into characters according to
a specified character encoding.

InputStreamReader: - To accept data from the Keyboard, therefore “System.in”, we need to connect it
to an Input Stream as some Input Stream is needed to read the data.

 InputStreamReader obj = new InputStreamReader(System.in);

1. Connect the Keyboard to an Input Stream object. Here we can use InputStreamReader that can read
data from the Keyboard.

InputStreamReader obj = new InputStreamReader (System.in);


Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 216 II.B.Sc., III Sem Java
In this Statement, we are creating InputStreamReader Object and connecting the Keyboard
(System.in) to it.

2. Connect InputStreamReader to BufferedReader, which is another Input type of Stream. We are using
BufferedReader as it has got methods to read data properly, coming from the Stream.

BufferedReader br = new BufferedReader (obj);

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

In the above two steps, we got BufferedReader object (br). These two steps can be combined
and rewritten in a single statement as:

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

3. Now, we can read the data coming from Keyboard using “read()” and “readLine()” methods available in
BufferedReader Class.

Example: -

char ch = (char) br.read(); // Read a Single Character.


String str = br.readLine(); // Read a String.
int n = Integer.parseInt(br.readLine()); // Reads an Integer.
float n = Float.parseFloat(br.readLine()); // Reads Floating pointer number.
double n = Double.parseDouble(br.readLine()); // Reads Double Value.

InputStreamReader Constructors: - An InputStreamReader is a bridge from Byte Streams to Character


Streams. It reads Bytes and decodes them into characters using a specified charset. The charset that it
uses may be specified by name be accepted. The following Constructors are allows to InputStreamReader.

 InputStreamReader(InputStream in): - Create an InputStreamReader that uses the default


charset.

 InputStreamReader(InputStream in, Charset cs): - Create an InputStreamReader that uses


the given charset.

 InputStreamReader(InputStream in, CharsetDecode dec): - Create an InputStreamReader


that uses the given charset decoder.

 InputStreamReader(InputStream in, String charsetName): - Create an InputStreamReader


that uses the named charset.

InputStreamReader Methods: - There are following Methods are listed below:

 close(): - This Method is used to close the stream.

 getEncoding(): - This Method is used to know the name of the character encoding being used by
this stream.

 read(): - This Method is used to read a single character.

 readby(): - This Method tells us whether this stream is ready to be read or not.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 217 II.B.Sc., III Sem Java
(Q) Discuss is BufferedReader class in Java?

The “java.io.BufferReader” class is a subclass of “java.io.Reader” that you chain to another Reader
class to buffer characters. This allows more efficient reading of characters and line.

Connect InputStreamReader to BufferedReader, which is another Input type of Stream. We are


using BufferedReader as it has got methods to read data properly, coming from the Stream.

BufferedReader br = new BufferedReader (obj);

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

In the above two steps, we got BufferedReader object (br). These two steps can be combined
and rewritten in a single statement as:

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

Now, we can read the data coming from Keyboard using “read()” and “readLine()” methods
available in BufferedReader Class.

Constructors: - There are two constructors, one with a default buffer size of 8192 characters, and other
one that lets you specify the buffer size.

BufferReader(Reader inputStream)
BufferReader(Reader inputStream, int bufSize)
Methods: -

 close(): - Close the Stream.


 mark(int readAheadLimit): - Mark the present position in the stream.
 read(): - This method is used to read a characters and returns an integer in the range 0 to 65535.
 ready(): - This method is used to find whether this stream is ready to be read and return Boolean.

(Q) Explain Scanner Class in Java?

The Scanner class is a class in “java.util”, which allows the users to read values of various types. A
Scanner object can read user input entered on the console or from a file. A Scanner breaks its input into
separates tokens (which are typically separated by with space), and then returns them one at a time. The
Scanner provides methods to convert the tokens into values of different types.

Example: - This code reads two numbers from the console and prints their sum:

Scanner in = new Scanner(System.in)


int i = in.nextInt();
int j = in.nextInt();
System.out.println(i+j);

The Scanner also provides methods to test whether ther is any input left, and if there is, what type
of token appears next. This functionality is provides through methods like „hasNextInt‟ & „hasNextDouble‟.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 218 II.B.Sc., III Sem Java
Creating Scanner Objects: - Whenever using Scanner, be sure to include the proper „import line‟.
Therefore “Import java.util.Scanner;”. We will create Scanner into two ways:

1. To read from the console, use the following:

Scanner input new Scanner(System.in);

2. To read from a file, use the following:

Scanner input = new Scanner(new FileStream(“filename.txt”));

Scanner Methods: -

Methods Descriptions
nextBoolean() Reads and converts next token to a Boolean Values.
nextInt() Reads and converts next token to a Integer Values.
nextLong() Reads and converts next token to a Long Values.
nextDouble() Reads and converts next token to a Double Values.
nextString() Reads next token and returns it as a String.
nextLine() Reads until the next new line and returns a String.
hasNextBoolean() Returns true if the next token is either „true‟ or „false‟.
hasNextInt() Return true if the next token is an Integer.
hasNextLong() Return true if the next token is an Long.
hasNextDouble() Return true if the next token is a real number.
hasNextString() Return true if there is at least one more token of input.
hasNextLine() Return true if there is another line of input.

(Q) Discuss about “System.out” in Java?

“System.out” is a “PrintStream”. „System.out‟ normally output the data on the console. This is often
used for console-only programs like command line tools.

System: - It is a standard java class. It comes from the “java lang.package”. It is a default package.

Out: - The class system contains static field name “out”. It comes from “java.io” package.

Println(): - println() method associates with the „printStream‟ object referred to by static field “out”.

Shaik Mohammad Fareed, MCA, M.Sc., IRPM. 219 II.B.Sc., III Sem Java

Das könnte Ihnen auch gefallen