0% found this document useful (0 votes)
27 views

Java Unit1

The document discusses object-oriented thinking and programming. It describes how object-oriented programming uses concepts like objects, classes, messages, and methods to organize complex programs. It provides an example of sending flowers to illustrate how these concepts work together to solve problems.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Java Unit1

The document discusses object-oriented thinking and programming. It describes how object-oriented programming uses concepts like objects, classes, messages, and methods to organize complex programs. It provides an example of sending flowers to illustrate how these concepts work together to solve problems.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 180

Object - Oriented

Thinking

1
1 Object-Oriented Thinking

When computers were first invented, programming was done manually by toggling in a binary machine
instructions by use of front panel. As programs began to grow, high level languages were introduced
that gives the programmer more tools to handle complexity. The first widespread high level language is
FORTRAN. Which gave birth to structured programming in 1960’s. The Main problem with the high
level language was they have no specific structure and programs becomes larger, the problem of
complexity also increases. So C became the popular structured oriented language to solve all the above
problems.

However in SOP, when project reaches certain size its complexity exceeds. So in 1980’s a new
way of programming was invented and it was Object Oriented Programming. Object Oriented
Programming is a programming methodology that helps to organize complex programs through the use
of inheritance, encapsulation & polymorphism. Object Oriented Programming is a Revolutionary idea
totally unlike anything that has came before in programming Object Oriented Programming is an
evolutionary step following naturally on the heels of earlier programming abstractions.

Item situated writing computer programs is as often as possible alluded to as another


programming worldview. The word worldview initially implied model, or model. For instance, a
worldview sentence would assist you with recalling how to conjugate an action word in an unknown
dialect. All the more for the most part, a model is a model that causes you see how the world functions.
For instance, the Newtonian model of material science discloses why apples tumble to the ground. In
software engineering, a worldview clarifies how the components that go into making a PC program are
sorted out furthermore, how they associate with one another. Hence the first step in getting Java is
valuing the item situated world view.

1.1 A Way of Viewing World


To illustrate the major ideas in object-oriented programming, let us consider how we might go about
handling a real-world situation and then ask how we could make the computer more closely model the
techniques employed. Suppose I wish to send flowers to a friend who lives in a city many miles away.
2
Let me call my friend Sally. So I chooce a agent called Flora to carry flowers to my friend.I tell Flora
the variety and quantity of flowers I wish to send and give Sally's address, and I can be assured the
flowers will be delivered expediently and automatically

Figure 1.1: The community of agents helping me

1.1.1 Agents and Communities

At the risk of belaboring a point, let me emphasize that the mechanism I used to solve my
problem was to find an appropriate agent (namely, Flora) and to pass to her a message containing my
request. It is the responsibility of Flora to satisfy my request. There is some method or some algorithm
or set of operations used by Flora to do this. I do not need to know the particular method that Flora will
use to satisfy my request; indeed, often I do not want to know the details. This information is usually
hidden from my inspection.

If I investigated however, I might discover that Flora delivers a slightly diferent message to another
againt in my friend's city. That agent , in turn, perhaps has a subordinate who makes the flflflowers
arrangement. The agent then passes the flowers , along with yet another message, to a delivery person,
and so on. Earlier, the agent in Sally's city had obtained her flowers from a flower wholesaler who, in
turn, had interactions with the flowers growers, each of whom had to manage a team of gardeners.

So, our first observation of object-oriented problem solving is that the solution to my problem
required the help of many other individuals (Figure 1.1). Without their help, my problem could not be
easily solved. We phrase this in a general fashion as the following:

An object oriented program is structured as a community of interacting agents, called objects. Each
object has a role to play. Each object provides a service, or performs an action, that is used by other
members of the community.
3
1.1.2 Messages and Methods

The chain reaction that ultimately resulted in the solution to my program began with my request to
Flora. This request lead to other requests, which lead to still more requests, until my flowers
ultimately reached my friend. We see, therefore, that members of this community interact with each
other by making requests. So, our next principle of object- oriented problem solving is the vehicle by
which activities are initiated:

Action is initiated in object-oriented programming by the transmission of a message to an agent


(an object) responsible for the action. The message encodes the request for an action and is
accompanied by any additional information (arguments) needed to carry out the request. The receiver
is the object to whom the message is sent. If the receiver accepts the message, it accepts the
responsibility to carry out the indicated action. In response to a message, the receiver will perform
some method to satisfy the request.

We have noted the important principle of information hiding in regard to message passing that
is, the client sending the request need not know the actual means by which the request will be
honored. There is another principle, all too human, that we see is implicit in message passing. If there
is a task to perform, the first thought of the client is to find somebody else he or she can ask to do the
work. This second reaction often becomes thin in many programmers with extensive experience in
conventional techniques. Frequently, a dificult hurdle to overcome is the idea in the programmer's
mind that he or she must write everything and not use the services of others.

An important part of object-oriented programming is the development of reusable components,


and an important first step in the use of reusable components is a willingness to trust software written
by others.

Information hiding is also an important aspect of programming in conventional languages. In


what sense is a message difierent from, say, a procedure call? In both cases, there is a set of well-
defined steps that will be initiated following the request. But, there are two important distinctions. The
first is that in a message there is a designated receiver for that message; the receiver is some object to
which the message is sent. In a procedure call, there is no designated receiver.

4
The second is that the interpretation of the message (that is, the method used to respond to the
message) is dependent on the receiver and can vary with difierent receivers. I can give a message to
my neighbor Elizabeth, for example, and she will understand it and a satisfactory outcome will be
produced (that is, flflowers will be delivered to my friend). However, the method Elizabeth uses to
satisfy the request (in all likelihood, simply passing the request on to Flora) will be different from that
used by Flora in response to the same request. If I ask , someother to send flowers to my friend, he
may not have a method for solving that problem.

Let us move our discussion back to the level of computers and programs. There, the distinction
between message passing and procedure calling is that, in message passing, there is a designated
receiver, and the interpretation may vary with difierent receivers(the selection of a method to execute
in response to the message). Usually, the specific receiver for any given message will not be known
until run time, so the determination of which method to invoke cannot be made until then. Thus, we
say there is late binding between the message (function or procedure name) and the code fragment
(method) used to respond to the message. This situation is in contrast to the very early (compile-time
or link-time) binding of name to code fragment in conventional procedure calls.

1.1.3 Responsibilities

A fundamental concept in object-oriented programming is to describe behavior in terms of


responsibilities. My request for action indicates only the desired outcome (flowers for my friend).
Flora is free to pursue any technique that achieves the desired objective and is not hampered by
interference on my part.

By discussing a problem in terms of responsibilities we increase the level of abstraction. This


permits greater independence between objects, a critical factor in solving complex problems. The
entire collection of responsibilities associated with an object is often described by the term protocol.

A traditional program often operates by acting on data structures, for example changing fields
in an array or record. In contrast, an object oriented program requests data structures (that is, objects)
to perform a service. This difference between viewing software in traditional, structured terms and
viewing it from an object-oriented perspective can be summarized by a twist on a well-known quote:

5
“Ask not what you can do to your data structures, but rather ask what your data structures can do for you”.

1.1.4 Classes and Instances

Although I have only dealt with Flora a few times, I have a rough idea of the behavior I can expect
when I go into her shop and present her with my request. I am able to make certain assumptions
because I have information about forists in general, and I expect that Flora, being an instance of this
category, will fit the general pattern. We can use the term Florist to represent the category (or class) of
all forists. Let us incorporate these notions into our next principle of object-oriented programming:

All objects are instances of a class.The method invoked by an object in response to a message is
determined

by the class of the receiver. All objects of a given class use the same method in response to similar
messages.

Figure 1.2: The category surrounding Flora

6
1.1.5 Class Hierarches - Inheritance

I have more information about Flora not necessarily because she is a florist but because she is a
shopkeeper. I know, for example, that I probably will be asked for money as part of the transaction,
and that in return for payment I will be given a receipt. These actions are true of grocers, stationers,
and other shopkeepers. Since the category Florist is a more specialized form of the category
Shopkeeper, any knowledge I have of Shopkeepers is also true of Florists and hence of Flora.

One way to think about how I have organized my knowledge of Flora is in terms of a hierarchy
of categories (see Figure 1.2). Flora is a Florist, but Florist is a specialized form of Shopkeeper.
Furthermore, a Shopkeeper is also a Human; so I know, for example, that Flora is probably bipedal. A
Human is a Mammal (therefore they nurse their young and have hair), and a Mammal is an Animal
(therefore it breathes oxygen), and an Animal is a Material Object (therefore it has mass and weight).
Thus, quite a lot of knowledge that I have that is applicable to Flora is not directly associated with her,
or even with her category Florist.

Figure 1.3: A class hirearchy for various meteral objects


7
The principle that knowledge of a more general category is also applicable to a more specific
category is called inheritance. We say that the class Florist will inherit attributes of the class (or
category) Shopkeeper.

There is an alternative graphical technique often used to illustrate this relationship, particularly
when there are many individuals.. This technique shows classes listed in a hierarchical tree-like
structure, with more abstract classes (such as Material Object or Animal) listed near the top of the
tree, and more specific classes, and finally individuals, are listed near the bottom. Figure 1.3 shows
this class hierarchy for Flora.

“Classes can be organized into a hierarchical inheritance structure. A child class (or subclass) will inherit
attributes from a parent class higher in the tree. An abstract parent class is a class (such as Mammal) for
which there are no direct instances; it is used only to create subclasses.”

1.1.6 Method Binding, Overriding and Exceptions

I know that mammals give birth to live children, but Phyl is certainly a Mammal, but it lays eggs. To
accommodate this, we need to find a technique to encode exceptions to a general rule.

We do this by declearing that information contained in a subclass can override information


inherited from a parent class. Most often, implementations of this approach takes the form of a method
in a subclass having the same name as a method in the parent class, combined with a rule for how the
search for a method to match a specific message is conducted:

The search for a method to invoke in response to a given message begins with the class of the receiver. If no
appropriate method is found, the search is conducted in the parent class of this class. The search continues up
the parent class chain until either a method is found or the parent class chain is exhausted. In the former case
the method is executed; in the latter case, an error message is issued. If methods with the same name can be
found higher in the class hierarchy, the method executed is said to override the inherited behavior.

8
Even if the compiler cannot determine which method will be invoked at run time, in many
object-oriented languages, such as Java, it can determine whether there will be an appropriate method
and issue an error message as a compile-time error diagnostic rather than as a run-time message.

If Elizabeth and my florist Flora will respond to my message by difierent methods is an


example of one form of polymorphism. We will discuss this important part of object-oriented
programming in Chapter. As explained, that I do not, and need not, know exactly what method Flora
will use to honor my message is an example of information hiding.

1.1.7 Summary of Object - Oriented Concepts

The following are fundamental to OOP :

 Everything is an object.
 An object is a runtime entity in an object oriented programming
 Computation is performed by objects communicating with each other. Objects
communicate by sending and receiving messages. A message is a request for action
bundled with whatever arguments may be necessary to complete the task.
 Each object has its own memory, which consists of other objects.
 Every object is an instance of a class. A class simply represents a grouping of similar
objects, such as integers or lists.
 The class is the repository for behavior associated with an object. That is, all objects that
are instances of the same class can perform the same actions.
 Classes are organized into a singly rooted tree structure, called the inheritance hierarchy.
Memory and behavior associated with instances of a class are automatically available to
any class associated with a descendant in this tree structure.
 Wrapping of data and methods into a single unit (called class)is known as
“encapsulation”
 Encapsulation makes it possible to treat Object as a blackbox each performing a specific
task without any conceren for internal implementation.

9
Figure 1.3:Encapusulation

 Insulation of the data from direct acess by the program is called as “data hiding”.
 Abstraction refers to the act of representing essential features without including
background details or exaplanations
 Inheritance is the process by which objects of one class acquire the properties of objects
of another class.Inheritance supports the concept of hierarchical classification as shown
below.

Figure 1.4:Property inheritance

 Polymorphism means the ability to take more than one form.For example ,an operation
may exhibit different behaviour in different instance.

10
Figure 1.5:Polymorphism

Applications of Object Oriented Programming


Main application areas of OOP are:
User interface design such as windows, menu.
Real Time Systems
Simulation and Modeling
Object oriented databases
AI and Expert System
Neural Networks and parallel programming
Decision support and office automation systems etc.
1. Client-Server Systems
Object-oriented Client-Server Systems provide the IT infrastructure, creating object-oriented Client-Server
Internet (OCSI) applications. Here, infrastructure refers to operating systems, networks, and hardware. OSCI
consist of three major technologies:
 The Client Server
 Object-Oriented Programming
 The Internet
2. Object-Oriented Databases
They are also called Object Database Management Systems (ODBMS). These databases store objects
instead of data, such as real numbers and integers. Objects consist of the following:

Attributes: Attributes are data that defines the traits of an object. This data can be as simple as integers and
real numbers. It can also be a reference to a complex object.

Methods: They define the behavior and are also called functions or procedures.

3. Object Oriented Databases


These databases try to maintain a direct correspondence between the real-world and database objects in
order to let the object retain their identity and integrity. They can then be identified and operated upon.

4. Real-Time System Design


Real time systems inherit complexities that makes difficult to build them. Object-oriented techniques make it
easier to handle those complexities. These techniques present ways of dealing with these complexities by
providing an integrated framework which includes schedulability analysis and behavioral specifications.

5. Simulation And Modelling System


It’s difficult to model complex systems due to the varying specification of variables. These are prevalent in
medicine and in other areas of natural science, such as ecology, zoology, and agronomic systems.
Simulating complex systems requires modelling and understanding interactions explicitly. Object-oriented
Programming provides an alternative approach for simplifying these complex modelling systems.

6. Hypertext And Hypermedia


OOP also helps in laying out a framework for Hypertext. Basically, hypertext is similar to regular text as it
can be stored, searched, and edited easily. The only difference is that hypertext is text with pointers to other
text as well.Hypermedia, on the other hand, is a superset of hypertext. Documents having hypermedia, not
only contain links to other pieces of text and information, but also to numerous other forms of media,
ranging from images to sound.
11
7. Neural Networking And Parallel Programming
It addresses the problem of prediction and approximation of complex time-varying systems. Firstly, the
entire time-varying process is split into several time intervals or slots. Then, neural networks are developed
in a particular time interval to disperse the load of various networks. OOP simplifies the entire process by
simplifying the approximation and prediction ability of networks.

8. Office Automation Systems


These include formal as well as informal electronic systems primarily concerned with information sharing
and communication to and from people inside as well as outside the organization. Some examples are Email,
Word processing, web calendars, Desktop publishing
9. CIM/CAD/CAM Systems
OOP can also be used in manufacturing and design applications as it allows people to reduce the effort
involved. For instance, it can be used while designing blueprints, flowcharts, etc. OOP makes it possible for
the designers and engineers to produce these flowcharts and blueprints accurately.

10. AI Expert Systems


These are computer applications which are developed to solve complex problems pertaining to a specific
domain, which is at a level far beyond the reach of a human brain. It has the following characteristics:
Reliable,Highly responsive,Understandable,High-performance

1.1.8 Java Buzzwords or Features of Java


The primary objective of Java programming language creation was to make it portable, simple
and secure programming language. Apart from this, there are also some excellent features which
play an important role in the popularity of this language. The features of Java are also known as
java buzzwords.
A list of most important features of Java language is given below.

1. Simple
2. Object-Oriented
3. Platform independent
4. Secured
5. Robust
6. Architecture neutral
7. Portable
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
12
Figure 1.6: Features of Java

Simple:

Java language is simple because:


1) Syntax is based on C++ (so easier for programmers to learn it after C++).
2) Removed many confusing and/or rarely-used features
Ex.; explicit pointers, operator overloading etc.
3) No need to remove unreferenced objects ,to do this Automatic Garbage Collection in java.
Object-oriented :
Object-Oriented means we organize our software as a combination of different types of objects
that incorporates both data and behavior. Object-oriented programming (OOPs) is a
methodology that simplify software development and maintenance by providing some
principles. They are :

13
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independence :
Java provides software-based platform. The Java platform differs from most other platforms in
the sense that it's a software-based platform that runs on top of other hardware-based platforms.
It has two components:
1. Runtime Environment
2. API(Application Programming Interface)
Java code can be run on multiple platforms e.g.Windows,Linux,SunSolaris,Mac/OS etc. Java
code is compiled by the compiler and converted into bytecode.This bytecode is a platform
independent code because it can be run on multiple platforms i.e. Write Once and Run
Anywhere(WORA).

Figure 1.7: platform independency

14
Secured:
Java is secured because

1. There is no explicit pointers.


2. Programs run inside virtual machine sandbox.

Robust :

Robust simply means strong. Java uses strong memory management. There is automatic
garbage collection in java. There is exception handling and type checking mechanism in java.
All these points makes java robust.

Architecture-neutral:

There are no implementation dependent features Ex.;size of primitive types is set

Portable :

We may carry the java bytecode to any platform.

High-performance:

Java is faster than traditional interpretation since byte code is "close" to native code still
somewhat slower than a compiled language (e.g., C++)

Distributed :

We can create distributed applications in java. RMI and EJB are used for creating distributed
applications. We may access files by calling the methods from any machine on the internet.

Multi-threaded:

A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-

15
threading is that it shares the same memory. Threads are important for multi-media, Web
applications etc.

1.1.9 An Overview of Java

Java is a Programming Language and a Platform.

Platform : Any hardware or software environment in which a program runs, known as a platform.
Since Java has its own Runtime Environment (JRE) and API, it is called platform.

History of Java

Java team members (also known as Green Team), initiated a revolutionary task to develop a language
for digital devices such as set-top boxes, televisions etc. It was best suited for internet programming.
Later, Java technology as incorporated by Netscape.

Currently, Java is used in internet programming, mobile devices, games, e-business solutions etc. There
are given the major points that describes the history of java.

James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.

Firstly, it was called "Greentalk" by James Gosling and file extension as .gt.After that, it was called
Oak and was developed as a part of the Green project.

Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A., France,
Germany, Romania etc. In 1995, Oak was renamed as "Java" because it was already a trademark by
Oak Technologies. Java is an island of Indonesia where first coffee was produced (called java coffee).

Note: Java is just a name not an acronym.

Java Version History

There are many java versions that has been released.

16
1. JDK Alpha and Beta (1995)
2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)

Applications using Java: There are mainly 4 type of applications that can be created using java

a. Standalone Application:

It is also known as desktop application or window-based application. An application that we


need to install on every machine such as media player, antivirus etc. AWT and Swing are used
in java for creating standalone applications.

b. Web Application:

An application that runs on the server side and creates dynamic page, is called web application.
Currently, Servlet, JSP, struts, JSF etc. technologies are used for creating web applications in
java.

c. Enterprise Application:

An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for creating
enterprise applications.

17
d. Mobile Application:

An application that is created for mobile devices. Currently Android and Java ME are used for
creating mobile applications.

JDK, JRE and JVM

Java Development Kit(JDK)

JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.

Figure 1.8: Java Development Kit (JDK)

Java Runtime Environment (JRE) :

JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the
implementation of JVM.It physically exists.It contains set of libraries + other files that JVM uses at
runtime.implementation of JVMs are also actively released by other companies besides Sun Micro
Systems.

18
Figure 1.9: Java Runtime Environment (JRE)

Java Virtual Machine (JVM)

JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that
actually calls the main method present in a java code. JVM is a part of JRE(Java Runtime
Environment).

Java applications are called WORA (Write Once Run Anywhere). This means a programmer can
develop Java code on one system and can expect it to run on any other Java enabled system without
any adjustment. This is all possible because of JVM.

JVM is an abstract machine. It is a specification that provides runtime environment in which java
bytecode can be executed . JVMs are available for many hardware and software platforms.

JVM is:

1. A specification where working of Java Virtual Machine is specified. But


implementation provider is independent to choose the algorithm. Its implementation
has been provided by Sun and other companies.
2. An implementationIts implementation is known as JRE (Java Runtime
Environment).
3. Runtime Instance Whenever you write java command on the command prompt to
run the java class, and instance of JVM is created.

NOTE:JVM, JRE and JDK are platform dependent because configuration of each OS differs.
But, Java is platform independent

Internal Architecture of JVM

When we compile a .java file, .class files(contains byte-code) with the same class names
present in .java file are generated by the Java compiler. This .class file goes into various
steps when we run it. These steps together describe the whole JVM.
19
Class Loader Subsystem

It is mainly responsible for three activities.

 Loading
 Linking
 Initialization

Loading : The Class loader reads the .class file, generate the corresponding binary data
and save it in method area.

20
Linking : Performs verification, preparation, and (optionally) resolution.

o Verification : It ensures the correctness of .class file i.e. it check whether this file is
properly formatted and generated by valid compiler or not. If verification
fails, we get run-time exception java.lang.VerifyError.
o Preparation : JVM allocates memory for class variables and initializing the memory to
default values.
o Resolution : It is the process of replacing symbolic references from the type with
direct references. It is done by searching into method area to locate the
referenced entity.

Initialization : In this phase, all static variables are assigned with their values defined in the
code and static block(if any). This is executed from top to bottom in a class and from parent to
child in class hierarchy.

Method area /Class area:In method area, all class level information like class name, immediate parent
class name, methods and variables information etc. are stored, including static variables. There is only
one method area per JVM, and it is a shared resource.

Heap area :Information of all objects is stored in heap area. There is also one Heap Area per JVM. It
is also a shared resource.

Stack area :For every thread, JVM create one run-time stack which is stored here. Every block of this
stack is called “activation record/stack frame” which store methods calls. All local variables of that
method are stored in their corresponding frame. After a thread terminate, it’s run-time stack will be
destroyed by JVM. It is not a shared resource.

PC Registers :Store address of current execution instruction of a thread. Obviously each thread has
separate PC Registers.

Native method stacks :For every thread, separate native stack is created. It stores native method
information.

21
Execution Engine

Execution engine execute the .class (bytecode). It reads the byte-code line by line, use data and
information present in various memory area and execute instructions. It can be classified in three parts
:-

Interpreter : It interprets the bytecode line by line and then executes. The disadvantage here is that
when one method is called multiple times, every time interpretation is required.

Just-In-Time Compiler(JIT) : It is used to increase efficiency of interpreter.It compiles the entire


bytecode and changes it to native code so whenever interpreter see repeated method calls,JIT provide
direct native code for that part so re-interpretation is not required,thus efficiency is improved.

Garbage Collector : It destroy un-referenced objects.

22
Java Native Interface (JNI) :

It is an interface which interacts with the Native Method Libraries and provides the native libraries(C,
C++) required for the execution. It enables JVM to call C/C++ libraries and to be called by C/C++
libraries which may be specific to hardware.

Native Method Libraries :

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

Installation of Java
The following steps will demonstrate the installation of Java

1. Type http://java.sun.com link and press enter.

2. Click on “Java SE” on the right (under “Popular Downloads”.)

23
24
3. On the page that loads, scroll down until you see “Java SE Development Kit (JDK).”
Click on the “Download” button to the right.

NOTE: At the time of writing (January 2009) the latest version of the JDK is 6 Update 11.

4. On the page that loads, choose Windows as your platform, set language to Multi-
Language, and select the checkbox. Finally, click the orange “Continue >>” button.

NOTE: If you are confident that you are on a 64-bit Windows installation, you can select
Windows x64 as your platform, but do not need to do so.

25
5. On the next screen that loads click to download the “Java SE Development Kit.”

NOTE: You may be requested to use the Sun Downloader to download Java. I advise just
using the directly linked full download.

6. Chose to save the file.

26
7. loading the file may take a couple of minutes based on your connection speed.

8. Go to where you downloaded the JDK.

27
9. Launch the installer. If User Account Control given a security warning click the “Yes”
button. The installer should begin loading. Please be patient.

10. Eventually you will be presented with an End User License Agreement (EULA). Read
it before clicking the “Accept >” button.

28
11. For this course, a default installation is completely fine, so just click the
“Next >” button.

NOTE: Pay attention to the “Install to:” location, you will need it later.

12. Be patient while Java installs the JDK.

29
13. You will then be asked to install the Java Runtime Engine (JRE.) Click the “Next >”
button.

14. Be patient while Java installs the JRE.

30
15. You are now done installing Java. All that is left is configuration.

Note: You may be asked to reboot your computer at this point. If you are, please do so.

31
Setting of path and class path

1. Now load the System Information Window by right clicking on “Computer” in the start
menu and selecting properties.

Note: This step can be done in other ways too. Such as…

Right clicking on Computer on the desktop and selecting properties.


 Holding the Windows-key () on your keyboard and pressing the “Pause” key.
(This may require holding FN on some laptops.)

32
2. The System Information Window should load.

3. Click on “Advanced system settings” on the left of the window.

33
4. System Properties window should open with the “Advanced” tab already selected.
Click on “Environment Variables” button.

5. The “Environment Variables” dialog should load.

34
6. In the “System variables” region, scroll down until you see the “Path” variable.

7. Click the lower “Edit” button.

35
8. You should now be editing the “Path” variable.

9. Remember the “Install to:” location on Step 12? That is the line you need to add to the
end of the path. Be sure to prefix the location with a ; and post fix it with bin
Therefore you want to add:
;<YOUR_INSTALL_LOCATION>bin
On MY computer, a Windows 7 beta x64 machines where I installed the 32-bit JDK, that
meant:

; C:\Program Files (x86)\Java\jdk1.6.0_11\bin

WARNING: BE VERY CAREFUL NOT TO OVERWRITE ALL THE


EXISTING ENTRIES IN YOUR PATH!

36
10. Click the “OK” button to confirm your change.

11. Click the “OK” button in the Environment Variables dialog.

37
12. Click the “OK” button in the System Properties dialog.

13. Close the System information window by clicking on the x icon on the top right.

38
14. Now to test our changes. Open the “Command Prompt” by going to:

Start  All Programs  Accessories  Command Prompt

Note: This step can be done in other ways too. Such as…

 Opening the Run Dialog and entering the command “cmd” (without the
quotes.)
 Searching for “Command Prompt” in the start menu.

15. The command prompt should load.

39
16. Enter the command “path” (without the quotes) and press enter. You should see the new
path location, which includes your update.

17. Enter the command “java -version” (without the quotes) and press enter. You should
see the JRE version you have installed.

40
18. Enter the command “javac -version” (without the quotes) and press enter. You should
see the JDK version you have installed.

19. Close the command prompt by click on the x on the top right or typing “exit”
(without the quotes) and pressing enter.

At this point, you can delete the JDK installer that you downloaded on step 6.

41
Setting of CLASSPATH in Java

CLASSPATH: CLASSPATH is an environment variable which is used by Application ClassLoader to


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

You need to set the CLASSPATH if:

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

There are two ways to ways to set CLASSPATH:

1. Using Command Prompt

2. Using Environment Variable.

1.Setting CLASSPATH in Windows Using Command Prompt


Type the following command in your Command Prompt and press enter.

set CLASSPATH=%CLASSPATH%;C:\Program Files\Java\jre1.8\rt.jar;

In the above command, The set is an internal DOS command that allows the user to change the
variable value. CLASSPATH is a variable name. The variable enclosed in percentage sign (%) is an
existing environment variable. The semicolon is a separator, and after the (;) there is the PATH of
rt.jar file.

2.Setting CLASSPATH in Windows Using Environment Variable.

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

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

Step 2: Click on Advanced System Settings.


Java Programming 43

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

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

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

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

43
Java Programming 44

Difference between PATH and CLASSPATH

PATH CLASSPATH

PATH is an environment CLASSPATH is also an environment variable.


variable.

It is used by the operating It is used by Application ClassLoader to locate the .class file.
system to find the executable
files (.exe).

You are required to include the You are required to include all the directories which contain
directory which contains .exe .class and JAR files.
files.

PATH environment variable The CLASSPATH environment variable can be overridden by


once set, cannot be overridden. using the command line option -cp or -CLASSPATH to both
javac and java command.

44
Java Programming 45

Writing and Execution of simple Program

1.Open a simple text editor program such as Notepad and type the following content:

public class HelloWorld


{
public static void main(String[] args)
{
System.out.println("Hello world!");
}
}

2.Save the file as HelloWorld.java (note that the extension is .java) under a directory, let’s say, C:\Java

3.Compile your first Java program

Now let’s compile our first program in the HelloWorld.java file using javac tool.
Syntax: javac programname.java
Type the following command to change the current directory to the one where the source file is stored:

4.Run your first Java program

It’s now ready to run our first Java program. To run java program use following Syntax

Syntax: java programname

That invokes the Java Virtual Machine to run the program called HelloWorld (note that there is no .java or
.class extension). You would see the following output:

45
Java Programming 46

Structure of the Java Program

Structure of a java program is the standard format released by Language developer to the Industry
programmer.

Sun Micro System has prescribed the following structure for the java programmers for developing
java application.

Structure of Java Program Example


package detials import java.lang.*;

class Classname class Demo

{ {

Datamembers int x=10;

user defined methods; void display(){

public static void main(string args[]) System.out.println(“java program structure”);

{ }

block of statements; public static void main(string args[])

} {

} Demo obj=new Demo();

System.out.println(“x value is”+obj.x);

Obj.display();

46
Java Programming 47

A package is a collection of classes, interfaces and sub-packages. A sub package contains collection of
classes, interfaces and sub-sub packages etc. java.lang.*; package is imported by default and this package
is known as default package.

Class is keyword used for developing user defined data type and every java program must start with a
concept of class.

"ClassName" represent a java valid variable name treated as a name of the class each and every class
name in java is treated as user-defined data type.

Data member represents either instance or static they will be selected based on the name of the class.

User-defined methods represents either instance or static they are meant for performing the operations
either once or each and every time.

Each and every java program starts execution from the main() method. And hence main() method is
known as program driver.

Since main() method of java is not returning any value and hence its return type must be void.

Since main() method of java executes only once throughout the java program execution and hence its
nature must be static.

Since main() method must be accessed by every java programmer and hence whose access specifier must
be public.

Each and every main() method of java must take array of objects of String.

Block of statements represents set of executable statements which are in term calling user-defined
methods are containing business-logic.

The file naming conversion in the java programming is that which-ever class is containing main()
method, that class name must be given as a file name with an extension .java.

Lexical Issues In Java


A source code of a Java program consists of tokens. Tokens are atomic code elements. Java programs are a
collection of Tokens such as white space identifiers, comments, literals, operators, separators, and keywords.
Whitespace:

Java is a free-form language. This means that you do not need to follow any special indentation rules. For
example, the Example program could have been written all on one line or in any other strange way you felt like
typing it, as long as there was at least one whitespace character between each token that was not already delineated
by an operator or separator. In java, whitespace is a space, tab, or new line.

47
Java Programming 48

Identifiers:

Identifiers are used for class names, method names, and variable names. An identifier may be any
descriptive sequence of uppercase and lowercase letters, numbers or the underscore and dollar sign characters. They
must not begin with a number, lest they be confused with a numeric literal. Again, java is case-sensitive,
so VALUE is a different identifier the Value. Some examples of valid identifiers are:

AvgTemp count a4 $test this_is_ok

Invalid variable names include:

2count high-temp Not/ok

Literals:

Using a literal representation of it creates a constant value in java. For example, here are some literals:

100 98.6 ‘X’ “This is a test”

Left to right, the first literal specifies an integer, the next is a floating-point value, the third is a character
constant, and the last is a string. A literal can be used anywhere a value of its type is allowed.

Comments:

As mentioned, there are three types of comments defined by java. You have already seen two: single-line
and multilane. The third type is called a documentation comment. This type of comment is used to produce an
HTML file that documents your program. The documentation comment begins with a /** and ends with a*/.
Separators

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

Java Keywords

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

1.1.10 Data Types

Every variable has a type, every expression has a type and all types are strictly define .Every assignment
should be checked by the compiler by the type compatibility hence java language is considered as
strongly typed language. In java, There are two types of Data Types:

Primitive Data Types

48
Java Programming 49

Non-Primitive Data Types

1. Primitive Data Types

Data Types make a variable to store a single value at a time

The Eight Primitive data types in Java are:


The integer types:

 byte
 short
 int
 long

The floating-point types:

 float
 double

49
Java Programming 50

Values of class type are references. Strings are references to an instance of class String.

Type Size(bytes) Range Default


byte 1 -128 .. 127 0
short 2 -32768 to32767 0
Int 4 -2147483648 to 2147483647 0

-9223372036854775808 to
long 8 0
9223372036854775807

float 4 3.4 e38 to 1.4 e-45 0.0


double 8 1.e-308 to 4.9e-324 0.0
boolean JVM Specific true or false FALSE
char 2 0 ..65535 \u0000

2. Non-Primitive Data Types:Derived data types are those that are made by using any other data type
and can make a variable to store multiple values ,for example, arrays.
3. User Defined Data Types: User defined data types are those that user / programmer himself
defines. For example, classes, interfaces.
Note : int a

Here a is a variable of int data type.

MyClass obj;

Here obj is a variable of data type MyClass and we call them reference variables as they can be used
to store the reference to the object of that class.

In java char uses 2 byte in java because java uses unicode system rather than ASCII code system.
\u0000 is the lowest range of unicode system.

Unicode System

Unicode is a universal international standard character encoding that is capable of representing

50
Java Programming 51

most of the world's written languages.

1.1.11 Variables

Introduction of variables:

Variable is name of reserved area allocated in memory

int data=10; //Here data is variable

A variable has these attributes:

 Name

1. The string of letters in a program used to designate a variable.


2. A name should start with a letter and consist of letters and/or digits.
3. Variables in names are case sensitive (capitalization matters).
4. The naming convention in Java is to start a variable name with a lower case letter.
5. New words within a name with a name start with a capital letter(example:
numberOfCustomers).

 Value
The binary data contained in memory. The value is interpreted according to the variable's
datatype.

 Address
The location in memory where the value is stored.

 Size
The number of bytes that the variable occupies in memory.

51
Java Programming 52

 Datatype
The interpretation of the value.

 Range
The minimum and maximum values of the variable. The range of a variable depends on its size. In
general, the bigger the size in bytes, the bigger the range.

Declaration of variables:

Syntax:

Datatype variable_name;

Example on variable declarations:


int maxAge;
int x, y, selectedIndex;
char a, b;
boolean flag;
double maxVal, massInKilos;

Initialization of Variable:

Two types of initializations:

i.Compile time initialization

ii.Runtime initialization

i)Compile time initialization:

Syntax:

Datatype variable_name=value;

52
Java Programming 53

Example on Variable initialization in declaration:


int timeInSeconds = 245;
char a = 'K', b = '$';
boolean flag = true;
double maxVal = 35.875;

Dynamic initialization of variable:

Datatype variable_name=Expression;

Example on Dynamic initialization

double a =10.0,b=20.0;

double d=Math.squart(49)+a+b;

ii)Runtime Initialization

In Java, there are three different ways for reading input from the user in the command line
environment(console).

1.Using Buffered Reader Class


2.Using Scanner Class
3.Using Console Class

1.Using Buffered Reader Class:

This is the Java classical method to take input, Introduced in JDK1.0. This method is used by wrapping
the System.in (standard input stream) in an InputStreamReader which is wrapped in a BufferedReader, we
can read input from the user in the command line.

Advantages
The input is buffered for efficient reading.
Drawback:
The wrapping code is hard to remember.

Example program on BufferedReader Class;

import java.io.*;
class Readdemo

53
Java Programming 54

{
public static void main(String args[]) throws IOException
{
int x;String str;
System.out.println("enter x value");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
x=Integer.parseInt(br.readLine());
System.out.println("x value is"+x);
System.out.println("enter ur name");
str=br.readLine();
System.out.println(" ur name is"+str);
}
}

Note: To read other types, we use functions like Integer.parseInt(), Double.parseDouble(). To read
multiple values, we use split().

2. Using Scanner Class

This is probably the most preferred method to take input. The main purpose of the Scanner class is to
parse primitive types and strings using regular expressions, however it is also can be used to read input
from the user in the command line.

Advantages:
Convenient methods for parsing primitives (nextInt(), nextFloat(), …) from the tokenized input.
Regular expressions can be used to find tokens.
Drawback:
The reading methods are not synchronized
class GetInputFromUser
{
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner(System.in);
System.out.println("enter a string”);
String s = in.nextLine();

System.out.println("enter a integer”);
int a = in.nextInt();

System.out.println("enter a float”);
float b = in.nextFloat();
System.out.println("You entered string "+s);
System.out.println("You entered integer "+a);
System.out.println("You entered float "+b);
}

54
Java Programming 55

}
Output:

enter a string
CMREC
enter a integer
12
enter a float
3.4

You entered string CMREC


You entered integer 12
You entered float 3.4

3. Using Console Class

It has been becoming a preferred way for reading user’s input from the command line. In addition, it can
be used for reading password-like input without echoing the characters entered by the user; the format
string syntax can also be used (like System.out.printf()).
Advantages:

Reading password without echoing the entered characters.


Reading methods are synchronized.
Format string syntax can be used.
Drawback:
Does not work in non-interactive environment (such as in an IDE).

// Java Program to demonstrate Console Methods

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

55
Java Programming 56

//Obtaining a reference to the console.


Console con = System.console();

// Checking If there is no console available, then exit.


if(con == null)
{
System.out.print("No console available");
return;
}
// Using Console to input data from user
System.out.println(“enter name”);
String name =con.readLine();
System.out.println(name);

//to read password and then display it


System.out.println("Enter the password: ");
char[] ch=con.readPassword();

//converting char array into string


String pass = String.valueOf(ch);
System.out.println("Password is: " + pass);
}
}
Output:

Enter your name: abc


Here is your name: abc
Enter the password:
Password is: xzzzz

Note: System.console() returns null in an online IDE


Types of Variable

There are three types of variables in java


 Local Variable
 Instance Variable
 Static Variable

56
Java Programming 57

Local Variable

A variable that is declared inside the method is called Local variable.

Instance Variable

A variable that is declared inside the class but outside the method is called instance variable .

It is not declared as static.


Static variable

A Variable that is declared as static is called static variable. It cannot be local.

Example to understand the types of variables

class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90; //local variable
}
} //end of class

Scope and life time of a variable

The scope determines what objects are visible to other parts of program and also determine Lifetime of
the those objects.

In java,scope is defined by the class and by the method.The instance variables and static variables are
declared which the class and out of any method ,so this types variables are available through out the class

57
Java Programming 58

The local variables are declared in side the method .so this avariables are available with the block in
which there are declared.

Type conversion and casting

The process of converting one data type to another data type is called as Casting

Types of castings:

There are two type of castings

1. Explicit type conversion (or) Narrowing conversion


2. Implicit type conversion (or ) Widening conversion

1.Casting Incompatible Types or explicit type conversion or narrowing conversion

Casting larger data type into smaller data type may result in a loss of data.

This kind of conversion is sometimes called a narrowing conversion, since you are explicitly making the
value narrower.

To create a conversion between two incompatible types, you must use a cast. A cast is

simply an explicit type conversion.

It has this general form:

type variable1=(target-type) variable2;


Example:

double m=50.00;

int n=(int)m;

58
Java Programming 59

2.Java’s Automatic Conversions or implicit type conversion or widening conversion

When one type of data is assigned to another type of variable, an automatic type conversion

will take place if the following two conditions are met:

a. The two types are compatible.


b. The destination type is larger than the source type.

When these two conditions are met, a widening conversion takes place.

Example:

int i=30;

double x;

x=i;

The double type is always large enough to hold all valid int values, so no explicit cast statement is

required.

class Typecastdemo

public static void main(String args[])

double f=3.141,x;

int i,j=30;

i=(int)f;//explicit conversion

x=j;//implicit conversion

System.out.println("i value is"+i);

System.out.println("x value is"+x);

59
Java Programming 60

Output: i value is 3

x value is 30.00

Type promotion rules

The sequence of promotion rules that are applied while implicit type conversion is as follows: All
byte,short and char are automatically converted to int; then

1. if one of the operands is long, the other will be converted to long and the result will be long

2. else, if one of the operands is float, the other will be converted to float and the result will be float

3. else, if one of the operands is double, the other will be converted to double and the result will be

.The final result of an expression is converted to the type of the variable on the left of the assignment sign
before assigning the value to it. However the following changes are introduced during the final
assignment.

Float to int causes truncation of the fractional part. Double to float causes rounding of digits.

60
Java Programming 61

Long int to int causes dropping of the excess higher order bits.

1.1.12 Arrays

Introduction

Definition of Array

Normally, array is a collection of similar type of elements that have contiguous memory location.

 Java array is an object the contains elements of similar data type.


 It is a data structure where we store similar elements.
 We can store only fixed set of elements in a java array.
 Array in java is index based, first element of the array is stored at 0 index.
 An array is an indexed collection of fixed number of homogeneous data elements.

Types of Array in java

There are two types of array.

1. Single Dimensional Array


2. Multidimensional Array.

Single Dimensional Array:

Single dimensional array declaration:

Sytax:
Datatype arrayname[ ];
Or
Datatype[ ] arrayname;

Example :

int a[ ];

61
Java Programming 62

int[ ] a; //recommended to use because name is clearly separated from the type int
[ ]a;

At the time of declaration we can’t specify the size otherwise we will get compile time error.

Example :

int[ ] a;//valid

int[5] a;//invalid

Creation of Array construction:

Every array in java is an object hence we can create by using new operator.

Syntax for Creating:

arrayname=new datatype[size];

Example :

a= new int[3];

we can also combine declaration and creation into one step

Syntax Datatype[ ] arrayname= new datatype[size];

Example:

int[] a=new int[3];

Diagram:

62
Java Programming 63

For every array type corresponding classes are available but these classes are part of java
language and not available to the programmer level.
Rules for creating an Array
Rule 1 :

 At the time of array creation compulsory we should specify the size otherwise we will get
compile time error.

Example :

int[] a=new int[3];

int[] a=new int[];//C.E:array dimension missing

Rule 2:

 It is legal to have an array with size zero in java.

Example :

int[] a=new int[0];


System.out.println(a.length);//0

Rule 3 :

 If we are taking array size with -ve int value then we will get runtime exception saying
NegativeArraySizeException.

Example :

int[] a=new int[-3];//R.E:NegativeArraySizeException

Rule 4:

 The allowed data types to specify array size are byte, short, char, int. By mistake if we are using
any other type we will get compile time error.
63
Java Programming 64

Example :

int[] a=new int['a'];//(valid)

byte b=10;

int[] a=new int[b];//(valid)


short s=20;

int[] a=new int[s];//(valid)

int[] a=new int[10l];//C.E:possible loss of precision//(invalid)

int[] a=new int[10.5];//C.E:possible loss of precision//(invalid)

Rule 5 :

 The maximum allowed array size in java is maximum value of int size [2147483647].

Example :

int[] a1=new int[2147483647];(valid)

int[] a2=new int[2147483648];//C.E:integer number too large: 2147483648(invalid)

Array initialization:

Syntax for initialization of Single Dimensional Array:

arrayname[subscript]=value;

Example:

int[] a=new int[4];

a[0]=10;

64
Java Programming 65

a[1]=20;

a[2]=30;

a[3]=40;

a[4]=50;//R.E:ArrayIndexOutOfBoundsException: 4

a[-4]=60;//R.E:ArrayIndexOutOfBoundsException: -4

Diagram:

Note:if we are trying to access array element with out of range index we will
get RuntimeException saying ArrayIndexOutOfBoundsException

Declaration construction and initialization of an array in a single line:

 We can perform declaration construction and initialization of an array in a single line.

Example:

int [] a={10,20,30};//valid

String[] s={"abc","def","jog","lmn”};(valid)

65
Java Programming 66

Whenever we are creating an array every element is initialized with defaultvalue automatically.

Example 1:

int[] a=new int[3];


System.out.println(a);//
System.out.println(a[0]);
Diagram :

Array Length:

length Vs length():

length:

 It is the final variable applicable only for arrays.


 It represents the size of the array.

length() method:

 It is a final method applicable for String objects.


 It returns the no of characters present in the String.

Example:

66
Java Programming 67

int[] x=new int[3];

System.out.println(x.length);//3

System.out.println(x.length());//C.E: cannot find symbol

Example:

String s="bhaskar";
System.out.println(s.length);//C.E:cannot find symbol
System.out.println(s.length());//7

Example on Single Dimensional Array :

class Testarray1
{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output :
33
3
4
5

67
Java Programming 68

Array and Functions (or)Passing single dimensional array to a function

Passing Array to method in java. We can pass the java array to method so that we can reuse the same
logic on any array.

Let's see the simple example to get minimum number of an array using method.

class Testarray2 {
static void min(int arr[]) {
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[])
{
int a[]={33,3,4,5};
min(a); //passing array to method
}
}
Output: 3

2.Multidimensional Array

Two dimensional array

68
Java Programming 69

 In java multidimensional arrays are implemented as array of arrays approach but not matrix
form.
 The main advantage of this approach is to improve memory utilization.

Two dimensional array declaration:

Datatype arrayname[ ][ ];
Or
Datatype[ ][ ] arrayname;

Alternate two dimensional array Declaration Syntax

int [ ][ ]a;

int [ ][ ]a;

int a[ ] [ ]; All are valid statements

int [ ] [ ]a;

int [ ] a[ ];

int [ ]a[ ];

Example :

Creation of Two- Dimensional array:

69
Java Programming 70

syntax:

arrayname=new datatype[size] [size];

Example:

int a[ ] [ ];

a=new int[3][2];

we can also combine declaration and creation into one step

Syntax

Datatype[ ][ ] arrayname= new datatype[size] [size];

Example1:

Variable Size Array:

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

70
Java Programming 71

a[0]=new int[2];

a[1]=new int[4];

a[2]=new int[3];

Two- Dimensional array Array initialization :

Syntax for initialization of Two- Dimensional Array:

datatype [subscript][subscript] arrayname ={list of value};

Example:

int[][] a={{10,20,30},{40,50}};`

Diagram:

If we want to use this short cut compulsory we should perform declaration, construction and
initialization in a single line. If we are trying to divide into multiple lines then we will get compile
time error.

Two Dimensional array length

Length variable applicable only for arrays where as length()method is applicable for String objects.

Example :

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


System.out.println(a.length);//6
System.out.println(a[0].length);//3

71
Java Programming 72

Diagram:

Examples on Two Dimensional array


Example 1: program to declare,create,initialize and access the elements of 2-D array
class array2d

public static void main(String args[]) {

//declaring and initializing 2D array

int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array

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

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

System.out.print(arr[i][j]+" ");

System.out.println();

}
}
}
Output:1 2 3
245
445

72
Java Programming 73

Example 2 : program for Addition of two matrix

class twodarrayaddition
{
public static void main(String args[]) {
//creating two matrices
int a[][]={{1,3,4},{3,4,5}};
int b[][]={{1,3,4},{3,4,5}};
//creating another matrix to store the sum of two matrices
int c[][]=new int[2][3];
//adding and printing addition of 2 matrices
for(int i=0;i<2;i++){
for(int j=0;j<3;j++){
c[i][j]=a[i][j]+b[i][j];
System.out.print(c[i][j]+" ");
}
System.out.println();//new line
}
}
}
Output : 2 6 8
6 8 10

73
Java Programming 74

Alternate Three dimensional array declaration Syntax:

int[ ][ ][ ] a;

int [ ][ ][ ]a;

int a[ ][ ][ ]; All are valid statements

int [ ] a[ ][ ];

int [ ][ ]a[ ];

Anonymous Arrays:

Sometimes we can create an array without name such type of nameless arrays are called
anonymous arrays.
The main objective of anonymous arrays is “just for instant use”.
We can create anonymous array as follows.

new int[]{10,20,30,40}; (valid)


new int[][]{{10,20},{30,40}}; (valid)

At the time of anonymous array creation we can’t specify the size otherwise we will get compile time
error.

Example :

new int[3]{10,20,30,40};//C.E:';' expected(invalid)

74
Java Programming 75

Advantage of Java Array

o Code Optimization : It makes the code optimized, we can retrieve or sort the data easily.
o Random access : We can get any data located at any index position.
o Readability : we can represent multiple values with the same name so that readability of the
code will be improved

Disadvantage of Java Array

o Fixed in size that is once we created an array there is no chance of increasing or decreasing
the size based on our requirement that is to use arrays concept compulsory we should know
the size in advance which may not possible always.
o We can resolve this problem by using collections.

1.1.13 Operators

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups −

 Arithmetic Operators

 Relational Operators

 Bitwise Operators

 Logical Operators

 Assignment Operators

 Misc Operators

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra.
The following table lists the arithmetic operators −

75
Java Programming 76

Assume integer variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

+ (Addition) Adds values on either side of the operator. A + B will give 30

- (Subtraction) Subtracts right-hand operand from left-hand operand. A - B will give -10

* (Multiplication) Multiplies values on either side of the operator. A * B will give 200

/ (Division) Divides left-hand operand by right-hand operand. B / A will give 2

Divides left-hand operand by right-hand operand and


% (Modulus) B % A will give 0
returns remainder.

++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives 19

The Relational Operators

There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −Show Examples

Operator Description Example

Checks if the values of two operands are equal or not, if yes


== (equal to) (A == B) is not true.
then condition becomes true.

76
Java Programming 77

Checks if the values of two operands are equal or not, if


!= (not equal to) (A != B) is true.
values are not equal then condition becomes true.

Checks if the value of left operand is greater than the value of


> (greater than) (A > B) is not true.
right operand, if yes then condition becomes true.

Checks if the value of left operand is less than the value of


< (less than) (A < B) is true.
right operand, if yes then condition becomes true.

>= (greater than Checks if the value of left operand is greater than or equal to
(A >= B) is not true.
or equal to) the value of right operand, if yes then condition becomes true.

<= (less than or Checks if the value of left operand is less than or equal to the
(A <= B) is true.
equal to) value of right operand, if yes then condition becomes true.

The Bitwise Operators

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

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in
binary format they will be as follows −

a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011

The following table lists the bitwise operators −

Assume integer variable A holds 60 and variable B holds 13 then −

Show Examples

77
Java Programming 78

Operator Description Example

Binary AND Operator copies a bit to


& (bitwise
the result if it exists in both (A & B) will give 12 which is 0000 1100
and)
operands.

Binary OR Operator copies a bit if it


| (bitwise or) (A | B) will give 61 which is 0011 1101
exists in either operand.

Binary XOR Operator copies the bit


^ (bitwise
if it is set in one operand but not (A ^ B) will give 49 which is 0011 0001
XOR)
both.

Binary Ones Complement Operator (~A ) will give -61 which is 1100 0011 in 2's
~ (bitwise
is unary and has the effect of complement form due to a signed binary
compliment)
'flipping' bits. number.

Binary Left Shift Operator. The left


<< (left operands value is moved left by the
A << 2 will give 240 which is 1111 0000
shift) number of bits specified by the right
operand.

Binary Right Shift Operator. The left


>> (right operands value is moved right by the
A >> 2 will give 15 which is 1111
shift) number of bits specified by the right
operand.

Shift right zero fill operator. The left


>>> (zero operands value is moved right by the
fill right number of bits specified by the right A >>>2 will give 15 which is 0000 1111
shift) operand and shifted values are filled
up with zeros.

78
Java Programming 79

The Logical Operators


The following table lists the logical operators −
Assume Boolean variables A holds true and variable B holds false, then −

Show Examples

Operator Description Example

Called Logical AND operator. If both the


&& (logical
operands are non-zero, then the condition (A && B) is false
and)
becomes true.

Called Logical OR Operator. If any of the two


|| (logical or) operands are non-zero, then the condition (A || B) is true
becomes true.

Called Logical NOT Operator. Use to reverses


the logical state of its operand. If a condition is
! (logical not) !(A && B) is true
true then Logical NOT operator will make
false.

The Assignment Operators

Following are the assignment operators supported by Java language −

Show Examples

Operator Description Example

Simple assignment operator. Assigns values from C = A + B will assign value of


=
right side operands to left side operand. A + B into C

Add AND assignment operator. It adds right


C += A is equivalent to C = C
+= operand to the left operand and assign the result
+A
to left operand.

79
Java Programming 80

Subtract AND assignment operator. It subtracts


C -= A is equivalent to C
-= right operand from the left operand and assign the
=C–A
result to left operand.

Multiply AND assignment operator. It multiplies


C *= A is equivalent to C = C
*= right operand with the left operand and assign the
*A
result to left operand.

Divide AND assignment operator. It divides left


C /= A is equivalent to C = C /
/= operand with the right operand and assign the
A
result to left operand.

Modulus AND assignment operator. It takes


C %= A is equivalent to C = C
%= modulus using two operands and assign the result
%A
to left operand.

<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2

>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2

&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2

|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2

Miscellaneous Operators

Miscellaneous operators includes

80
Java Programming 81

 Conditional Operator ( ? : )
 instanceof Operator

There are few other operators supported by Java Language.

Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three operands and
is used to evaluate Boolean expressions. The goal of the operator is to decide, which value should be
assigned to the variable. The operator is written as −

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


Following is an example −

Example

publicclassTest {
publicstaticvoid main(String args[]){
int a, b;
a =10;
b =(a ==1)?20:30;
System.out.println("Value of b is : "+ b );
b =(a ==10)?20:30;
System.out.println("Value of b is : "+ b );
}
}

This will produce the following result −

Output

Value of b is : 30
Value of b is : 20

81
Java Programming 82

instanceof Operator

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

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

If the object referred by the variable on the left side of the operator passes the IS-A check for the
class/interface type on the right side, then the result will be true. Following is an example −

Example

publicclassTest{
publicstaticvoid main(String args[]) {
String name ="James";
// following will return true since name is type of String
boolean result = name instanceofString;
System.out.println( result );
}
}

This will produce the following result −

Output

true
This operator will still return true, if the object being compared is the assignment compatible with the
type on the right. Following is one more example −

Example

classVehicle{}
publicclassCarextendsVehicle{
publicstaticvoid main(String args[]){
Vehicle a =newCar();

82
Java Programming 83

boolean result = a instanceofCar;


System.out.println( result );
}
}

This will produce the following result −

Output

true

Precedence of Java Operators

Operator precedence determines the grouping of terms in an expression. This affects how an expression is
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator
has higher precedence than the addition operator −

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher precedence than +,
so it first gets multiplied with 3 * 2 and then adds into 7.

Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () Left toright


[]
. (dot operator)
Unary ++ Right to left
--
!
~

83
Java Programming 84

Multiplicative * Left to right


/
%

Additive + Left to right


-

Shift >> Left to right


>>>
<<

Relational > Left to right


>=
<
<=

Equality == Left to right


!=

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

Assignment = Right to left


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

84
Java Programming 85

ssignment, Arithmetic, and Unary Operators

The Simple Assignment Operator

One of the most common operators that you'll encounter is the simple assignment operator " =".

int cadence = 0;

int speed = 0;

int gear = 1;

The Arithmetic Operators

classArithmeticDemo {

public static void main (String[] args) {

int result = 1 + 2;

// result is now 3

System.out.println("1 + 2 = " + result);

intoriginal_result = result;

result = result - 1;

// result is now 2

System.out.println(original_result + " - 1 = " + result);

original_result = result;

result = result * 2;

// result is now 4

System.out.println(original_result + " * 2 = " + result);

85
Java Programming 86

original_result = result;

result = result / 2;

// result is now 2

System.out.println(original_result + " / 2 = " + result);

original_result = result;

result = result + 8;

// result is now 10

System.out.println(original_result + " + 8 = " + result);

original_result = result;

result = result % 7;

// result is now 3

System.out.println(original_result + " % 7 = " + result);

This program prints the following:

1+2=3

3-1=2

2*2=4

4/2=2

2 + 8 = 10

10 % 7 = 3

86
Java Programming 87

You can also combine the arithmetic operators with the simple assignment operator to create
compound assignments. For example, x+=1; and x=x+1; both increment the value of x by 1.

The + operator can also be used for concatenating (joining) two strings together, as shown in the
following ConcatDemo program:

classConcatDemo

public static void main(String[] args)

String firstString = "This is";

String secondString = " a concatenated string.";

String thirdString = firstString+secondString;

System.out.println(thirdString);

The Unary Operators

The unary operators require only one operand; they perform various operations such as incrementing /
decrementing a value by one, negating an expression, or inverting the value of a boolean.

Operator Description

+ Unary plus operator; indicates positive value (numbers are positive without this, however)

- Unary minus operator; negates an expression

++ Increment operator; increments a value by 1

-- Decrement operator; decrements a value by 1

! Logical complement operator; inverts the value of a boolean

87
Java Programming 88

The following program, UnaryDemo, tests the unary operators:

ClassUnaryDemo {

public static void main(String[] args) {

int result = +1;

// result is now 1

System.out.println(result);

result--;

// result is now 0

System.out.println(result);

result++;

// result is now 1

System.out.println(result);

result = -result;

// result is now -1

System.out.println(result);

boolean success = false;

// false

System.out.println(success);

// true

System.out.println(!success);

88
Java Programming 89

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. The
code result++; and ++result; will both end in result being incremented by one. The only difference is that
the prefix version (++result) evaluates to the incremented value, whereas the postfix version ( result++)
evaluates to the original value. If you are just performing a simple increment/decrement, it doesn't
really matter which version you choose. But if you use this operator in part of a larger expression, the
one that you choose may make a significant difference.

The following program, PrePostDemo, illustrates the prefix/postfix unary increment operator:

classPrePostDemo {

public static void main(String[] args) {

int i = 3;

i++;

// prints 4

System.out.println(i);

++i;

// prints 5

System.out.println(i);

// prints 6

System.out.println(++i);

// prints 6

System.out.println(i++);

// prints 7

System.out.println(i);

89
Java Programming 90

Equality, Relational, and Conditional Operators


The Equality and Relational Operators
The equality and relational operators determine if one operand is greater than, less than, equal to, or
not equal to another operand. The majority of these operators will probably look familiar to you as
well. Keep in mind that you must use "==", not "=", when testing if two primitive values are equal.
Operator Description
== equal to
!= not equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
classComparisonDemo {
public static void main(String[] args) {
int value1 = 1;
int value2 = 2;
if(value1 == value2)
System.out.println("value1 == value2");
if(value1 != value2)
System.out.println("value1 != value2");
if(value1 > value2)
System.out.println("value1 > value2");
if(value1 < value2)
System.out.println("value1 < value2");
if(value1 <= value2)
System.out.println("value1 <= value2");
}
}

90
Java Programming 91

The Conditional Operators

The && and || operators perform Conditional-AND and Conditional-OR operations on two boolean
expressions. These operators exhibit "short-circuiting" behavior, which means that the second operand
is evaluated only if needed.

Operator Description
&& Conditional-AND
|| Conditional-OR

class ConditionalDemo1 {

public static void main(String[] args){

int value1 = 1;

int value2 = 2;

if((value1 == 1) && (value2 == 2))

System.out.println("value1 is 1 AND value2 is 2");

if((value1 == 1) || (value2 == 1))

System.out.println("value1 is 1 OR value2 is 1");

91
Java Programming 92

The following program, ConditionalDemo2, tests the ?: operator:

class ConditionalDemo2 {

public static void main(String[] args){

int value1 = 1;

int value2 = 2;

int result;

booleansomeCondition = true;

result = someCondition ? value1 : value2;

System.out.println(result);

Because someCondition is true, this program prints "1" to the screen. Use the ?: operator instead of
an if-then-else statement if it makes your code more readable; for example, when the expressions
are compact and without side-effects (such as assignments).

Bitwise and Bit Shift Operators

The Java programming language also provides operators that perform bitwise and bit shift operations
on integral types. The operators discussed in this section are less commonly used. Therefore, their
coverage is brief; the intent is to simply make you aware that these operators exist.

The unary bitwise complement operator "~" inverts a bit pattern; it can be applied to any of the integral
types, making every "0" a "1" and every "1" a "0". For example, a byte contains 8 bits; applying this
operator to a value whose bit pattern is "00000000" would change its pattern to "11111111".

The signed left shift operator "<<" shifts a bit pattern to the left, and the signed right shift operator
">>" shifts a bit pattern to the right. The bit pattern is given by the left-hand operand, and the number

92
Java Programming 93

of positions to shift by the right-hand operand. The unsigned right shift operator ">>>" shifts a zero
into the leftmost position, while the leftmost position after ">>" depends on sign extension.

The bitwise & operator performs a bitwise AND operation.

The bitwise ^ operator performs a bitwise exclusive OR operation.

The bitwise | operator performs a bitwise inclusive OR operation.

The following program, BitDemo, uses the bitwise AND operator to print the number "2" to standard
output.

classBitDemo {

public static void main(String[] args) {

int bitmask = 0x000F;

intval = 0x2222;

// prints "2"

System.out.println(val& bitmask);

93
Java Programming 94

1.1.14 Expressions

Expressions, Statements, and Blocks

Definition: An expression is a series of variables, operators, and method calls (constructed according to
the syntax of the language) that evaluates to a single value. As discussed in the previous section, operators
return a value, so the use of an operator is an expression. This partial listing of
the MaxVariablesDemo program shows some of the program's expressions in boldface:

...

// other primitive types

char aChar = 'S';

boolean aBoolean = true;

// display them all

System.out.println("The largest byte value is " + largestByte);

...

if (Character.isUpperCase(aChar)) {

... }

Each expression performs an operation and returns a value, as shown in the following table.

Expression Action Value Returned


Assign the character 'S' to the character The value of aChar after
a Char = 'S'
variable aChar the assignment ('S')
Concatenate the string "The largest byte
"The largest byte value The resulting string: The
value is " and the value
is " + largestByte largest byte value is 127
of largestByte converted to a string
Character.isUpperCase( The return value of the
Call the method isUpperCase
aChar) method: true

94
Java Programming 95

The data type of the value returned by an expression depends on the elements used in the expression. The
expression aChar = 'S' returns a character because the assignment operator returns a value of the same data
type as its operands and aChar and 'S' are characters. As you see from the other expressions, an expression
can return a boolean value, a string, and so on.

The Java programming language allows you to construct compound expressions and statements from
various smaller expressions as long as the data type required by one part of the expression matches the
data type of the other. Here's an example of a compound expression:

x*y*z

. For example, the following expression gives different results, depending on whether you perform the
addition or the division operation first:

x + y / 100 //ambiguous

You can specify exactly how you want an expression to be evaluated, using balanced parentheses—
( and ). For example, to make the previous expression unambiguous, you could write:

(x + y)/ 100 //unambiguous, recommended

If you don't explicitly indicate the order in which you want the operations in a compound expression to be
performed, the order is determined by the precedence assigned to the operators in use within the
expression. Operators with a higher precedence get evaluated first. For example, the division operator has
a higher precedence than does the addition operator. Thus, the two following statements are equivalent:

x + y / 100

x + (y / 100) //unambiguous, recommended

When writing compound expressions, you should be explicit and indicate with parentheses which
operators should be evaluated first. This pratice will make your code easier to read and to maintain.

95
Java Programming 96

1.1.15. Control Statements

A control statement works as a determiner for deciding the next task of the other statements whether to
execute or not. An ‘If’ statement decides whether to execute a statement or which statement has to execute
first between the two. In Java, the control statements are divided into three categories which are selection
statements, iteration statements, and jump statements. A program can execute from top to bottom but if
we use a control statement. We can set order for executing a program based on values and logic, see below
table .

» Decision Making in Java

 Simple if Statement
 if…else Statement
 Nested if statement
 if...else if…else statement
 Switch statement

» Looping Statements in Java

 While
 Do…while
 For
 For-Each Loop

» Branching Statements in Java

 Break
 Continue
 Return

Decision Making in Java

96
Java Programming 97

Decision making statements are statements which decides what to execute and when. They are similar to
decision making in real time. Control flow statements control the flow of a program’s execution. Here
flow of execution will be based on state of a program. We have 4 decision making statements available in
Java.

Simple if Statement :

Simple if statement is the basic of decision-making statements in Java. It decides if certain amount of code
should be executed based on the condition.

Syntax:
if (condition)
{
Statemen 1; //if condition becomes true then this will be executed
}

Statement 2; //this will be executed irrespective of condition becomes true or false

Example:

class ifTest {

public static void main(String args[]) {

int x = 5;

if (x > 10)

System.out.println("Inside If");

System.out.println("After if statement");

Output:

After if statement
97
Java Programming 98

if…else Statement :

In if…else statement, if condition is true then statements in if block will be executed but if it comes out as
false then else block will be executed.

Syntax: if (condition) {

Statemen 1; //if condition becomes true then this will be executed

Example:

class ifelseTest {

public static void main(String args[]) {

int x = 9;

if (x > 10)

System.out.println("i is greater than 10");

else

System.out.println("i is less than 10");

System.out.println("After if else statement");

Output:

98
Java Programming 99

i is less than 10

After if else statement

Nested if statement :

Nested if statement is if inside an if block. It is same as normal if…else statement but they are written
inside another if…else statement.

Syntax: if (condition1)
{
Statemen 1; //executed when condition1 is true
if (condition2)
{
Statement 2; //executed when condition2 is true
}
else
{
Statement 3; //executed when condition2 is false
}
}

Example:

class nestedifTest {

public static void main(String args[]) {

int x = 25;

if (x > 10) {

if (x%2==0)

99
Java Programming 100

System.out.println("i is greater than 10 and even number");

else

System.out.println("i is greater than 10 and odd number");

else {

System.out.println("i is less than 10");

System.out.println("After nested if statement");

Output:

i is greater than 10 and odd number


After nested if statement

if…else statement :

if…else if statements will be used when we need to compare the value with more than 2 conditions. They
are executed from top to bottom approach. As soon as the code finds the matching condition, that block
will be executed. But if no condition is matching then the last else statement will be executed.

Syntax:
if (condition1) {
Statemen 1; //if condition1 becomes true then this will be executed
}
else if (condition2) {
Statement 2; // if condition2 becomes true then this will be executed
}
....
....
else {
Statement 3; //executed when no matching condition found
100
}
Java Programming 101

Example:

class ifelseifTest {

public static void main(String args[]) {

int x = 2;

if (x > 10) {

System.out.println("i is greater than 10");

else if (x <10)

System.out.println("i is less than 10");

else {

System.out.println("i is 10");

System.out.println("After if else if ladder statement");

Output:

i is less than 10

101
Java Programming 102

After if else if ladder statement

Switch statement :

Java switch statement compares the value and executes one of the case blocks based on the condition. It is
same as if…else if ladder. Below are some points to consider while working with switch statements:

» case value must be of the same type as expression used in switch statement
» case value must be a constant or literal. It doesn’t allow variables
» case values should be unique. If it is duplicate, then program will give compile time error

Let us understand it through one example.

class switchDemo{

public static void main(String args[]) {

int i=2;

switch(i){

case 0:

System.out.println("i is 0");

break;

case 1:

System.out.println("i is 1");

break;

case 2:

System.out.println("i is 2");

break;

case 3:

102
Java Programming 103

System.out.println("i is 3");

break;

case 4:

System.out.println("i is 4");

break;

default:

System.out.println("i is not in the list");

break;

Looping Statements in Java :

Looping statements are the statements which executes a block of code repeatedly until some condition
meet to the criteria. Loops can be considered as repeating if statements. There are 3 types of loops
available in Java.

While :

While loops are simplest kind of loop. It checks and evaluates the condition and if it is true then executes
the body of loop. This is repeated until the condition becomes false. Condition in while loop must be
given as a Boolean expression. If int or string is used instead, compile will give the error.

Syntax:
Initialization;
while (condition)
{
statement1;
increment/decrement;
}
103
Java Programming 104

Example:

class whileLoopTest {

public static void main(String args[]) {

int j = 1;

while (j <= 10) {

System.out.println(j);

j = j+2;

Output:

1 3 5 7 9

Do…while :

Do…while works same as while loop. It has only one difference that in do…while, condition is checked
after the execution of the loop body. That is why this loop is considered as exit control loop. In do…while
loop, body of loop will be executed at least once before checking the condition

Syntax: do
{
statement1;
}while(condition);

104
Java Programming 105

Example:

class dowhileLoopTest {

public static void main(String args[]) {

int j = 10;

do {

System.out.println(j);

j = j+1;

} while (j <= 10)

Output: 10

For Statement :

It is the most common and widely used loop in Java. It is the easiest way to construct a loop structure in
code as initialization of a variable, a condition and increment/decrement are declared only in a single line
of code. It is easy to debug structure in Java.

Syntax:
for (initialization; condition; increment/decrement)

statement;

105
Java Programming 106

Example:

class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
Output:

For-Each Loop :

For-Each loop is used to traverse through elements in an array. It is easier to use because we don’t have to
increment the value. It returns the elements from the array or collection one by one.

Example:

class foreachDemo {

public static void main(String args[]) {

int a[] = {10,15,20,25,30};

for (int i : a) {

106
Java Programming 107

System.out.println(i);

Output:

10

15

20

25

30

Branching Statements in Java :

Branching statements jump from one statement to another and transfer the execution flow. There are 3
branching statements in Java.

Break :

Break statement is used to terminate the execution and bypass the remaining code in loop. It is mostly
used in loop to stop the execution and comes out of loop. When there are nested loops then break will
terminate the innermost loop.

Example:

class breakTest {

public static void main(String args[]) {

for (int j = 0; j < 5; j++) {

// come out of loop when i is 4.

107
Java Programming 108

if (j == 4)

break;

System.out.println(j);

System.out.println("After loop");

Output:

After loop

Continue :

Continue statement works same as break but the difference is it only comes out of loop for that iteration
and continue to execute the code for next iterations. So it only bypasses the current iteration.

Example:

class continueTest {

public static void main(String args[]) {

108
Java Programming 109

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

// If the number is odd then bypass and continue with next value

if (j%2 != 0)

continue;

// only even numbers will be printed

System.out.print(j + " ");

Output:

02468

ASIS FOR
BREAK CONTINUE
COMPARISON

Task It terminates the execution of It terminates only the current

remaining iteration of the loop. iteration of the loop.

Control after 'break' resumes the control of the 'continue' resumes the control

break/continue program to the end of loop enclosing of the program to the next

that 'break'. iteration of that loop

enclosing 'continue'.

109
Java Programming 110

Causes It causes early termination of loop. It causes early execution of

the next iteration.

Continuation 'break' stops the continuation of loop. 'continue' do not stops the

continuation of loop, it only

stops the current iteration.

Other uses 'break' can be used with 'switch', 'continue' can not be

'label'. executed with 'switch' and

'labels'.

Return :

Return statement is used to transfer the control back to calling method. Compiler will always bypass any
sentences after return statement. So, it must be at the end of any method. They can also return a value to
the calling method.

1.1.16 Introducing Classes

Class fundamentals

How to create classes by using the following basics:

» The parts of a class definition

» Declaring and using instance variables

» Defining and using methods

» Creating Java applications, including the main() method and how to pass arguments to a
Java program from a command line

110
Java Programming 111

Definition :

A class is a sort of template which has attributes and methods. An object is an instance of a class,
e.g. Ram is an object of type Person.

A class is defined as follows:

class classname {

// declare instance variables

type var1;

type var2;

// ... type varN;

// declare methods

type method1(parameters) {

// body of method

type method2(parameters) {

// body of method

// ...

type methodN(parameters) {

// body of method

The classes we have used so far had only one method, main(), however not all classes specify a
main method. The main method is found in the main class of a program (starting point of
program).

111
Java Programming 112

A Simple Class

Let’s begin our study of the class with a simple example. Here is a class called Box that defines three
instance variables: width, height, and depth. Currently, Box does not contain any methods (but some will
be added soon).

class Box {

double width;

double height;

double depth;

As stated, a class defines a new type of data. In this case, the new data type is called Box. You will use
this name to declare objects of type Box. It is important to remember that a class declaration only creates a
template; it does not create an actual object. Thus, the preceding code does not cause any objects of type
Box to come into existence.

Declaration of Object and its initialization

To create an object of the class we use new keyword as shown below syntaxt

classname objectname=new classname( );


To actually create a Box object, you will use a statement like the following:

Box mybox = new Box(); // create a Box object called mybox

After this statement executes, mybox will be an instance of Box. Thus, it will have “physical” reality.
For the moment, don’t worry about the details of this statement.

As mentioned earlier, each time you create an instance of a class, you are creating an object that
contains its own copy of each instance variable defined by the class. Thus, every Box object will contain
its own copies of the instance variables width, height, and depth. To access these variables, you will use
the dot (.) operator. The dot operator links the name of the object with the name of an instance variable.

112
Java Programming 113

To set the values of the parameters we use the following syntax:

object.member=value;

For example, to assign the width variable of mybox the value 100, you would use the following statement:

mybox.width = 100;

This statement tells the compiler to assign the copy of width that is contained within the mybox object
the value of 100. In general, you use the dot operator to access both the instance variables and the methods
within an object.

Here is a complete program that uses the Box class:

/* A program that uses the Box class. Call this file BoxDemo.java */

class Box {

double width;

double height;

double depth;

// This class declares an object of type Box.

class BoxDemo {

public static void main(String args[]) {

Box mybox = new Box();

double vol;

// assign values to mybox's instance variables

mybox.width = 10;

mybox.height = 20;

mybox.depth = 15;

113
Java Programming 114

// compute volume of box

vol = mybox.width * mybox.height * mybox.depth;

System.out.println("Volume is " + vol);

You should call the file that contains this program BoxDemo.java, because the main( ) method is in the
class called BoxDemo, not the class called Box. When you compile this program, you will find that two
.class files have been created, one for Box and one for BoxDemo. The Java compiler automatically puts
each class into its own .class file. It is not necessary for both the Box and the BoxDemo class to actually
be in the same source file. You could put each class in its own file, called Box.java and BoxDemo.java,
respectively.

To run this program, you must execute BoxDemo.class. When you do, you will see the following output:

Volume is 3000.0

As stated earlier, each object has its own copies of the instance variables. This means that if you have
two Box objects, each has its own copy of depth, width, and height. It is important to understand that
changes to the instance variables of one object have no effect on the instance variables of another.

Constructors
 Constructor is a special type of method that is used to initialize the object.
 Constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
Rules for creating Constructor
There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type
Types of Constructors
There are two types of constructors:

1. default constructor (no-arg constructor)


114
Java Programming 115

2. parameterized constructor

1) Default Constructor

A constructor that have no parameter is known as default constructor.

Syntax of Default Constructor:

class_name( )

Statements;

Example of Default Constructor

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

class DefaultConstructor
{
DefaultConstructor()
{
System.out.println("hai");
}
public static void main(String args[])
{
DefaultConstructor obj=new DefaultConstructor();
}
}

115
Java Programming 116

Output: hai

Rule: If there is no constructor in a class, compiler automatically creates a default constructor.

Purpose of Default Constructor

Default constructor provides the default values to the object like 0, null etc. depending on the
typeExample of default constructor that displays the default values

class DefaultC
{
int stdid;
String name;
static void dispaly()
{
System.out.println("stdid"+"");
System.out.println("name"+"");
}
public static void main(String args[])
{
Output: dc=new DefaultC();
DefaultC
dc.display();
}0 null
}
Explanation : In the above class,you are not creating any constructor so compiler provides you a default
constructor. Here 0 and null values are provided by default constructor.
2. Parameterized constructor
A constructor that have parameters is known as parameterized constructor.

116
Java Programming 117

Usage of Parameterized Constructor

Parameterized constructor is used to provide different values to the distinct objects.

Example on Parameterized constructor :.

class Paraconstructor
{
int stdid;
String name;
Paraconstructor(int x,String n)
{
stdid=x;
name=n;
}
void display()
{
System.out.println("stdid is"+""+stdid);
System.out.println("name is"+""+name);
}
public static void main(String args[])
{
Paraconstructor obj1=new Paraconstructor(5,"abc");
obj1.display();
Paraconstructor obj2=new Paraconstructor(7,"def");
obj2.display();
}
}

Output:

stdid is 5

name is abc

stdid is 7

name is def

117
Java Programming 118

Difference between constructor and method

Constructor Method

Constructor is used to initialize the state of an


Method is used to expose behaviour of an object.
object.

Constructor must not have return type. Method must have return type.

Constructor is invoked implicitly. Method is invoked explicitly.

The java compiler provides a default constructor


Method is not provided by compiler in any case.
if you don't have any constructor.

Constructor name must be same as the class Method name may or may not be same as class
name. name.

Understanding of This Keyword


Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the ‘this’ keyword. this can be used inside any method to refer to the current object. That is,
this is always a reference to the object on which the method was invoked. You can use this
anywhere a reference to an object of the current class’ type is permitted.
To better understand what this refers to, consider the following version of Box( ):
/* Here, Box uses a parameterized constructor to initialize the dimensions of a box.*/
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
// compute and return volume
double volume() {

118
Java Programming 119

return width * height * depth;


}
}
class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1= new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);

double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
The use of this is redundant, but perfectly correct. Inside Box( ), this will always refer to the invoking
object.

Instance Variable Hiding


Because this lets you refer directly to the object, you can use it to resolve any name space collisions
thatmight occur between instance variables and local variables. For example, here is another version of
Box( ), which uses width, height, and depth for parameter names and then uses this to access the instance
variables by the same name:
// Use this to resolve name-space collisions.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
Aword of caution: The use of this in such a context can sometimes be confusing, and
some programmers are careful not to use local variables and formal parameter names that
hide instance variables. Of course, other programmers believe the contrary—that it is a good
convention to use the same names for clarity, and use this to overcome the instance variable
hiding. It is a matter of taste which approach you adopt.

119
Java Programming 120

1.1.17 Methods and Classes

Class Methods in Java

A method is a collection of statements that are grouped together to perform an operation.

Methods describe behavior of an object.

For example, if we have a class Human, then this class should have methods like eating(), walking(),
talking(), etc, which in a way describes the behaviour which the object of this class will have.

Syntax: return-type methodName(parameter-list)

//body of method

Example of a Method:

public String getName(String st) {

String name="StudyTonight";

name=name+st;

return name;

120
Java Programming 121

Modifier : Modifier are access type of method. We will discuss it in detail later.

Return Type : A method may return value. Data type of value return by a method is declare in method
heading.

Method name : Actual name of the method.

Parameter : Value passed to a method.

Method body : collection of statement that defines what method does.

Parameter Vs. Argument in a Method :

While talking about method, it is important to know the difference between two
terms parameter and argument.

Parameter is variable defined by a method that receives value when the method is called. Parameter are
always local to the method they dont have scope outside the method. While argument is a value that is
passed to a method when it is called.

Overloading:

Overloading:

Overloading is a machanisum by which Java supports polymorphism.

In Java we have 2 types of Overloading namely

121
Java Programming 122

i)Method Overloading

ii)Constructor Overloading

i)Method overloading:

In Java it is possible to define two or more methods within the same class that share the
same name, as long as their parameter declarations are different. When this is the case, the methods are
said to be overloaded, and the process is referred to as method overloading. Method overloading is one of
the ways that Java supports polymorphism.

When an overloaded method is invoked, Java uses the type and/or number of arguments as its
guide to determine which version of the overloaded method to actually call.

Example on Method Overloading

class Methodoverload
{
void display()
{
System.out.println("display method without arguements");
}
void display(int a)
{
System.out.println("display method with integer"+""+a);
}
void display(int a,double b)
{
System.out.println("display method with integer"+a+"and double"+b);
}
public static void main(String args[])
{
Methodoverload obj=new Methodoverload();
obj.display();
obj.display(10);
obj.display(20,65.99);
}
}

Output:

display method without arguments

122
Java Programming 123

display method with integer 10

display method with integer 20 and double 65.99

Constructor Overloading:

In addition to overloading normal methods, you can also overload constructor methods

class Coverload
{

int a;double b;
Coverload()
{
System.out.println("constructor without parameters");
}
Coverload(int i)
{
a=i;
System.out.println("constructor with one parameter");
System.out.println("a value is"+a);
}
Coverload(int i,double d)
{
a=i;
b=d;

System.out.println("constructor with two parameter");


System.out.println("a value is"+a);
System.out.println("b value is"+b);
}
public static void main(String args[])
{
Coverload obj1=new Coverload();
Coverload obj2=new Coverload(10);
Coverload obj3=new Coverload(40,29.99);
}
}

Output:

constructor without parameters

123
Java Programming 124

constructor with one parameter


a value is 10
constructor with two parameter
a value is 40
b value is29.99

Recursion:

Recursion:

Java supports recursion. Recursion is the process of defining something in terms of itself. As it relates to
Java programming, recursion is the attribute that allows a method to call itself. Amethod that calls itself
is said to be recursive.

Example on Recursion:

class Recursion
{
int fact(int n)
{
int result;
if(n==0||n==1)
return 1;
else
result=n*fact(n-1);
return result;
}
public static void main(String args[])
{
int ans;
Recursion obj=new Recursion();
ans=obj.fact(5);
System.out.println("factorial of 5 is"+ans);
}
}

Output:factorial of 5 is 120.

124
Java Programming 125

Parameter passing Techniques (or) call-by-value and call-by-reference

call-by-value and call-by-reference :

There are two ways to pass an argument to a method

1. call-by-value : In this approach copy of an argument value is pass to a method. Changes made to
the argument value inside the method will have no effect on the arguments.
2. call-by-reference : In this reference of an argument is pass to a method. Any changes made inside
the method will affect the agrument value.

Example of call-by-value:

public class Test {


public void callByValue(int x) {
x=100;
}
public static void main(String[] args) {
int x=50;
Test t = new Test();
t.callByValue(x); //function call
System.out.println(x);
}
}
Output: 50

125
Java Programming 126

Example of call-by-Reference:
public class CBRTest {
int a;
CBRTest(int i)
{
a=i;
}
public void callByReference(CBRTest obj)
{
obj.a=obj.a+10;
}
public static void main(String[] args)
{
CBRTest obj = new CBRTest(10);
System.out.println("before calling a value is"+obj.a);
obj.callByReference(obj)//function call by passing object
System.out.println("after calling a value is"+obj.a);
}
}

Output:

before calling a value is 10

after calling a value is 20

NOTE: When a primitive type is passed to a method, it is done by use of call-by-value. Objects are
implicitly passed by use of call-by-reference.

126
Java Programming 127

Understanding of Static and Final Keyword

Static Keyword:
The static keyword in Java is used for memory management mainly. We can apply java static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the class than an instance
of the class.

The static can be:

i. Variable (also known as a class variable)


ii. Method (also known as a class method)
iii. Block

i)Java static variable

If you declare any variable as static, it is known as a static variable.

The static variable can be used to refer to the common property of all objects (which is not unique for each
object), for example, the company name of employees, college name of students, etc.

The static variable gets memory only once in the class area at the time of class loading.

Advantages of static variable

It makes your program memory efficient (i.e., it saves memory).

Understanding the problem without static variable

class Student{

int rollno;

String name;

String college="CMREC";

Suppose there are 500 students in my college, now all instance data members will get memory each time
when the object is created. All students have its unique rollno and name, so instance data member is good
in such case. Here, "college" refers to the common property of all objects. If we make it static, this field
will get the memory only once.

127
Java Programming 128

Note:Java static property is shared to all objects

//Java Program to demonstrate the use of static variable

class Student{

int rollno;//instance variable

String name;

static String college ="CMREC";//static variable

Note:As we have mentioned above, static variable will get the memory only once, if any object changes
the value of the static variable, it will retain its value

class Counter{

static int count=0;//will get memory only once and retain its value

Counter(){

count++;//incrementing the value of static variable

System.out.println(count);

public static void main(String args[]){

//creating objects

Counter c1=new Counter();

Counter c2=new Counter();

Counter c3=new Counter();

Output:

128
Java Programming 129

ii) Java static method

If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

class Calculate{
static int cube(int x){
return x*x*x;
}
public static void main(String args[]){
int result=Calculate.cube(5);
System.out.println(result);
}
}

Restrictions for the static method

There are two main restrictions for the static method. They are:

 The static method can not use non static data member or call non-static method directly.
 this and super cannot be used in static context.

iii) Java static block

Is used to initialize the static data member.

It is executed before the main method at the time of classloading.

Example:

class Demo{

static{System.out.println("static block is invoked");}

public static void main(String args[]){

System.out.println("Hello main");

129
Java Programming 130

Output:

static block is invoked

Hello main

Final Keyword In Java:


The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:
 variable
 method
 class
 if a variable is made as final it cannot change its value
Example:
class Demo
{

int a=10;

final int b=20;

public static void main(String arg[])

a=a+10;

System.out.println(a);

b=b+20;//error because variable ‘b’ is final

System.out.println(b);

130
Java Programming 131

 if a method is made as final it cannot override it.

Class Demo

Final void display( )

System.out.println(“hello”);

Class FinalDemo extends Demo

void display( ) //overriding is not premitted

System.out.println(“hello”);

public static void main(String arg[])

FinalDemo fd=new FinalDemo();

fd. display( );

If a class is made as final it cannot be extended by another class

131
Java Programming 132

Program to demonstrate using final with inheritance

final class A
{

Class B extends A //error since A is final we can’t inherit it properties


{
void display()
{
System.out.println("demo on final");
}

public static void main(String args[]){


B obj=new B();
Obj.display();
}
}

symbolic constants
Symbolic constants in Java are named constants. Constants may appear repeatedly in number of
places in the program. Constant values are assigned to some names at the beginning of the
program, then the subsequent use of these names in the program has the effect of caving their
defined values to be automatically substituted in appropriate points. The constant is declared as
follows:

Syntax : final datatype symbolicname= value;

Eg: final float PI =3.14159;


final int STRENTH =100;

Rules :-

1. Symbolic names take the some form as variable names. But they one written in capitals to
distance from variable names. This is only convention not a rule.

2.After declaration of symbolic constants they shouldn’t be assigned any other value within the
program by using an assignment statement.

132
Java Programming 133

For eg:- STRENTH = 200 is illegal

3. They can’t be declared inside a method. They should be used only as class data members in the
beginning of the class.

class SymbolicDemo

static final int A=10;

static final double PI=3.141;

public static void main(String args[])

//final int A=10;

//final double PI=3.141;

int a=20,sum;

double r=30.49;

sum=A+a;

System.out.println("sum is "+sum);

double area=PI*r*r;

System.out.println("area is "+area);

//A=A+1;//ERROR CANNOT ASSIGN A VALUE FOR FINAL VARIABLE

133
Java Programming 134

Introduction of Nested and Inner classes


Nested classes in Java

A class declared inside a class is known as nested class.

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

Additionally, nested class can access all the members of outer class including private data members
and methods but viceverse is not possible

Syntax of Nested class

class Outer_class_Name

...

class Nested_class_Name

...

...

Advantage of nested classes

There are basically three advantages of nested classes. They are

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

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

134
Java Programming 135

• Code Optimization: It requires less code to write.

Types of Nested class:

There are two types of nested classes non-static and static nested classes.

The Non-static nested classes are also known as Inner classes.

1. Non-static nested class(inner class)

a)Member inner class

b) Local inner class

c) Annomynous inner class

2. Static nested class

135
Java Programming 136

1.Member inner class

A class that is declared inside a class but outside a method is known as member inner
class.

Invocation of Member Inner class

 From within the class


 From outside the class

Example of member inner class :

In this example, we are invoking the method of member inner class from the display method of Outer
class.

class Outer
{
private int data=20;
class MemberInner
{
void message()
{
System.out.println("private data of outerclass is"+data);
}
}
void display()
{
MemberInner in=new MemberInner();
in.message();
}
public static void main(String args[])
{
Outer out=new Outer();
out.display();
}
}
Output:
private data of outerclass is 20

136
Java Programming 137

2) Local inner class

A class that is created inside a method is known as local inner class. If you want to invoke the
methods of local inner class, you must instantiate this class inside the method.

Program of local inner class


class Outer{
private int data=30;//instance variable
void display()
{
class LocalInner
{
void massage()
{
System.out.println("private data of outer class"+data);
}
}
LocalInner in=new LocalInner();
in.massage();
}
public static void main(String args[]){
Outer obj=new Outer();
obj.display();
}
}
Output:

private data of outer class 30

Rules for Local Inner class

1) Local inner class cannot be invoked from outside the method.

2) Local inner class cannot access non-final local variable.

3)Annonymous inner class

A class that have no name is known as annomymous inner class.

Example:

Program of annonymous inner class by abstract class

abstract class Demo

137
Java Programming 138

{
abstract void display();
}
class Annomynous
{
public static void main(String args[])
{

Demo obj=new Demo()


{
void display()
{
System.out.println("Demo on annomynous inner class");
}
};
obj.display();
}
}
Output: Demo on annomynous inner class

4)static nested class

A static class that is created inside a class is known as static nested class. It cannot access the non-static
members outer class.

 It can access static data members of outer class including private.


 static nested class cannot access non-static (instance) data member or method.

Program of static nested class that have instance method


class Outer{
static int data=30;

static class Inner


{
void msg(){System.out.println("data is "+data);}
}

public static void main(String args[]){


Outer.Inner obj=new Outer.Inner();
obj.msg();
}
}

Output:data is 30

138
Java Programming 139

In this example, you need to create the instance of static nested class because it has
instance method msg(). But you don't need to create the object of Outer class because nested class is
static and static properties, methods or classes can be accessed without object.

1.1.18 Java String

Introduction to Java string class and String object

 String is a sequence of characters. But in java, string is an object that represents a sequence of
characters. The java.lang.String class is used to create string object.

For example:

char[] ch={'j','a','v','a'};

String s=new String(ch);

is same as:

String s="java";

 Java String class provides a lot of methods to perform operations on string such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

There are two ways to create String object:

i. By String Literal
ii. By new keyword

i) String Literal

Java String literal is created by using double quotes. For Example:

String s="welcome";

Each time you create a string literal, the JVM checks the string constant pool first. If the string already
exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new
string instance is created and placed in the pool. For example:

139
Java Programming 140

String s1="Welcome";
String s2="Welcome";//will not create new instance

ii) By new keyword

String s= new String("Welcome"); //creates two objects and one reference variable

In such case, JVM will create a new string object in normal(non pool) heap memory and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the object in heap(non
pool).

Java String Example:

public class StringExample


{
public static void main(String args[])
{
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
140
Java Programming 141

String manipulation methods

Java String class method

String objects are immutable, whenever you want to modify a String, you must

either copy it into a StringBuffer or StringBuilder, or use one of the following String methods,

which will construct a new copy of the string with your modifications complete.

The java.lang.String class provides many useful methods to perform operations on sequence of char
values

No. Method Description

1 char charAt(int index) returns char value for the particular index

2 int length() returns string length

3 static String format(String format, returns formatted string


Object... args)

4 String substring(int beginIndex, int returns substring for given begin index and end
endIndex) index

5 boolean contains(CharSequence s) returns true or false after matching the


sequence of char value

6 static String join(CharSequence returns a joined string


delimiter, CharSequence...
elements)

7 boolean equals(Object another) checks the equality of string with object

141
Java Programming 142

8 boolean isEmpty() checks if string is empty

9 String concat(String str) concatinates specified string

10 String replace(char old, char new) replaces all occurrences of specified char value

11 String replace(CharSequence old, replaces all occurrences of specified


CharSequence new) CharSequence

12 static String compares another string. It doesn't check case.


equalsIgnoreCase(String another)

13 String[] split(String regex) returns splitted string matching regex

14 String[] split(String regex, int limit) returns splitted string matching regex and limit

15 int indexOf(int ch) returns specified char value index

16 int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index

17 int indexOf(String substring) returns specified substring index

18 int indexOf(String substring, int returns specified substring index starting with
fromIndex) given index

19 String toLowerCase() returns string in lowercase.

142
Java Programming 143

20 String toUpperCase() returns string in uppercase.

21 String trim() removes beginning and ending spaces of this


string.

22 static String valueOf(int value) converts given type into string. It is


overloaded.

Program on StringHandling :

public class StringhandlingExample

public static void main(String args[])

String name="JAVA PROGRAMMING";

String s1="hello";

String s2="hello";

String joinstring,stringlower,stringupper;

char ch=name.charAt(4);//returns the char value at the 4th index

System.out.println(ch);

System.out.println(s1.compareTo(s2));//0 because both are equal

System.out.println(s1.equals(s2));//true because content and case is same

System.out.println("string length is: "+s1.length());//5 is the length of hello string

joinstring=string.join(“welcome”, “to”, “javaprogramming”);

System.out.println(joinstring); //welcome to javaprogramming

143
Java Programming 144

stringlower=name.toLowerCase( );

System.out.println(stringlower); // javaprogramming

stringupper= s1.toUpperCase();

System.out.println(stringupper); //HELLO

System.out.println(s1.trim()+"javaprogramming");//hellojavaprogramming

//space between s1 contents and javaprogramming is removed

StringBuffer

Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer
class in java is same as String class except it is mutable i.e. it can be changed.

StringBuffer Constructors

Important Constructors of StringBuffer class

Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of


16.

StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int creates an empty string buffer with the specified capacity


capacity) as length.

144
Java Programming 145

Important methods of StringBuffer class

Modifier Method Description


and Type

public append(String s) is used to append the


synchronized specified string with this
StringBuffer string. The append()
method is overloaded like
append(char),
append(boolean),
append(int),
append(float),
append(double) etc.

public insert(int offset, is used to insert the


synchronized String s) specified string with this
StringBuffer string at the specified
position. The insert()
method is overloaded like
insert(int, char),
insert(int, boolean),
insert(int, int), insert(int,
float), insert(int, double)
etc.

public replace(int is used to replace the


synchronized startIndex, int string from specified
StringBuffer endIndex, String str) startIndex and endIndex.

public delete(int startIndex, is used to delete the string


synchronized int endIndex) from specified startIndex
StringBuffer and endIndex.

public reverse() is used to reverse the


synchronized string.
StringBuffer

public int capacity() is used to return the


current capacity.

public void ensureCapacity(int is used to ensure the


minimumCapacity) capacity at least equal to
the given minimum.

145
Java Programming 146

public char charAt(int index) is used to return the


character at the specified
position.

public int length() is used to return the


length of the string i.e.
total number of
characters.

public String substring(int is used to return the


beginIndex) substring from the
specified beginIndex.

public String substring(int is used to return the


beginIndex, int substring from the
endIndex) specified beginIndex and
endIndex.

Command-Line Arguments

Sometimes you will want to pass information into a program when you run it. This is

accomplished by passing command-line arguments to main( ). A command-line argument is

the information that directly follows the program’s name on the command line when it is

executed.

To access the command-line arguments inside a Java program is quite easy—

they are stored as strings in a String array passed to the args parameter of main( ). The first

command-line argument is stored at args[0], the second at args[1], and so on.

146
Java Programming 147

Example 1:

The following program displays all of the command-line arguments that it is called with:

// Display all command-line arguments.

class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
}
Running:
C:>\ java CommandLine have a nice time
output:
args[0]:have
args[1]: a
args[2]:nice
args[3]:time
REMEMBER All command-line arguments are passed as strings.

Example 2:

Program to add to numbers that are passed through command prompt

class CommandLine
{
public static void main(String args[])
{
int a,b,sum;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
sum=a+b;
System.out.println("addition of"+a+"and"+b+"is"+sum);
}
}

147
Java Programming 148

1.
Inherirance Concept

Inheritance is the mechanism of deriving new class from old one, old class is knows as superclass and new
class is known as subclass. The subclass inherits all of its instances variables and methods defined by the
superclass and it also adds its own unique elements. Thus we can say that subclass are specialized version
of superclass.

Benefits of Java’s Inheritance

1. Reusability of code
2. Code Sharing
3. Consistency in using an interface

1. Inherirance Basics

Defination:The process by which one class acquires the properties(data members) and functionalities
(methods) of another class is called inheritance.

(or)

Inheritance is a process of defining a new class based on an existing class by extending its common data
members and methods.

Child Class:

The class that extends the features of another class is known as child class, sub class or derived class.

Parent Class:

The class whose properties and functionalities are used(inherited) by another class is known as parent
class, super class or Base class.

148
Java Programming 149

Inheritance allows us to reuse of code, it improves reusability in your java application.

The biggest advantage of Inheritance is that the code that is already present in base class need not be
rewritten in the child class.This means that the data members(instance variables) and methods of the
parent class can be used in the child class .Child class has to write only the unique features and rest of
the common properties and functionalities can be extended from the another class.

Syntax: Inheritance in Java

To inherit a class we use extends keyword. Here class XYZ is child class and class ABC is parent
class. The class XYZ is inheriting the properties and methods of ABC class.

class XYZ extends ABC

Types of inheritance

1. Single Inheritance
2. Multilevel inheritance
3. Hierarchical inheritance
4. Multiple Inheritance

1.Single Inheritance: refers to a child and parent class relationship where a class extends the another
class.

149
Java Programming 150

Program to demonstrate Single Level Inheritance:


class A
{
int i=10;
void Adisplay()
{
System.out.println("class A display");
}
}
class B extends A
{
int j=20;
void Bdisplay()
{
System.out.println("class B display");
}
public static void main(String args[])
{
B obj=new B();
obj.Adisplay();
obj.Bdisplay();
System.out.println("i value is "+obj.i);
System.out.println("j value is "+obj.j);
}
}

class A display

class B display

i value is 10

j value is 20

2.Multilevel inheritance: refers to a child and parent class relationship where a class extends the child
class. For example class C extends class B and class B extends class A.

150
Java Programming 151

Program to demonstrate Multi Level Inheritance:

class A
{
A()
{
System.out.println("A constructor");
}
void Amethod()
{
System.out.println("method of A");
}
}
class B extends A
{
B()
{
System.out.println("B constructor");
}
void Bmethod()
{
System.out.println("method of B");
}
void welcome()
{
System.out.println("class B-welcome method");
}
}
class C extends B
{
C()
{
System.out.println("C constructor");
}
void welcome()
{
System.out.println("class C- welcome method");

}
public static void main(String args[])
{
C oc=new C();
oc.Amethod();
oc.Bmethod();
oc.welcome();

151
Java Programming 152

}
}

Output:

A constructor

B constructor

C constructor

method of A

method of B

method of A

3.Hierarchical inheritance: refers to a child and parent class relationship where more than one classes
extends the same class. For example, classes B, C & D extends the same class A.

class A
{
A()
{
System.out.println("A constructor");
}
void Amethod()
{
System.out.println("method of A class");
}
}
class B extends A
{

152
Java Programming 153

B()
{
System.out.println("B constructor");
}
void Bmethod()
{
System.out.println("method of B class");
}
}
class D extends A
{
D()
{
System.out.println("D constructor");
}
void Dmethod()
{
System.out.println(" method of D class");
}
public static void main(String args[])
{
D od=new D();
od.Amethod();
od.Dmethod();
B ob=new B();
ob.Amethod();
ob.Bmethod();
}

Output:

A constructor
D constructor
method of A class
method of D class
A constructor
B constructor
method of A class
method of B class

153
Java Programming 154

4.Multiple Inheritance: refers to the concept of one class extending more than one classes, which means
a child class has two parent classes. For example class C extends both classes A and B. Java doesn’t
support multiple inheritances.

5.Hybrid inheritance: Combination of more than one types of inheritance in a single program. For
example class A & B extends class C and another class D extends class A then this is a hybrid inheritance
example because it is a combination of single and hierarchical

154
Java Programming 155

inheritance.

1. Member Access

Member Access and Inheritance

An instance variable of a class will be declared private to prevent its unauthorized use or tampering.
Inheriting a class does not overrule the private access restriction. Thus, even though a subclass includes
all of the members of its superclass, it cannot access those members of the superclass that have been
declared private. For example, if, as shown here, width and height are made private in TwoDShape,
then Triangle will not be able to access them:

//private members are not inherited

//This program does not compile….

Class PrivateAccess

155
Java Programming 156

private int a=10;

private int b=20;

int c;

void display()

c=a+b;

System.out.println(c);

Class Demo extends PrivateAccess

Void sub()

c=a-b;//error private member a and b can’t be inherited.

Java-Superclass Variable Can Reference a Subclass Object


Superclass Variable Can Reference a Subclass Object
A reference variable of a superclass can be assigned a reference to any subclass derived from that
superclass. In the following program, obj is a reference to NewData object, Since NewData is a subclass
of Data, it is permissible to assign obj a reference to the NewData object. When a reference to a subclass
object is assigned to a superclass reference variable, you will have access only to those parts of the object
defined by the superclass. This is way obj can’t access data3 and data4 even it refers to a NewData object.
Program

156
Java Programming 157

157
Java Programming 158

1. Creating Multilevel Hierarchy


Create multilevel hierarchy
It is nothing but the enhancement of the Simple Inheritance. From the type name, it is pretty much clear
that Inheritance is done at ‘n’ number of levels, where n>1.
In simple inheritance, a subclass or derived class derives the properties from its parent class, but in
multilevel inheritance, a subclass is derived from a derived class. One class inherits the only single class.
Therefore, in multilevel inheritance, every time ladder increases by one. The lowermost class will have
the properties of all the superclass.

Program to demonstrate Multi Level Inheritance/hierarchy:

class A
{
A()
{
System.out.println("A constructor");
}
void Amethod()
{
System.out.println("method of A");
}
}
class B extends A
{
B()
{
System.out.println("B constructor");
}
void Bmethod()
{
System.out.println("method of B");
}
void welcome()
{
System.out.println("class B-welcome method");

158
Java Programming 159

}
}
class C extends B
{
C()
{
System.out.println("C constructor");
}
void welcome()
{
System.out.println("class C- welcome method");

}
public static void main(String args[])
{
C oc=new C();
oc.Amethod();
oc.Bmethod();
oc.welcome();

}
}

Output:

A constructor

B constructor

C constructor

method of A

method of B

method of A

159
Java Programming 160

Note: Multilevel inheritance is not multiple inheritances where one class can inherit more than one class
at a time. Java does not support multiple inheritances.

1. Super Uses

super keyword in java

The super keyword in java is a reference variable which is used to refer immediate parent class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which is
referred by super reference variable

Usage of java super Keyword

1. super can be used to refer immediate parent class instance variable.


2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

The use of super keyword

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if parent class and
child class have same fields.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if subclass contains
the same method as parent class. In other words, it is used if method is overridden.

160
Java Programming 161

Example program to demonstrating invoking of parent class instance variable and parent class method

class A
{
int data=10;
void display()
{
System.out.println(" A class display");
}
}

class B extends A
{
int data=20;

void display()
{
System.out.println(" B class display");
}
void superdisplay()
{
System.out.println("data in A class is"+super.data);
super.display();
}
public static void main(String args[])
{
B obj=new B();
obj.display();
System.out.println(obj.data);
obj.superdisplay();
}
}

Output

B class display
20
data in A class is 10
A class display

161
Java Programming 162

3) super is used to invoke parent class constructor.

The super keyword can also be used to invoke the parent class constructor.

class Parentclass
{
Parentclass()
{
System.out.println("Constructor of parent class");
}
}
class Subclass extends Parentclass
{
Subclass()
{
//Compile implicitly adds super() here as the first statement of this
constructor.
System.out.println("Constructor of child class");
}
Subclass(int num)
{
// Even though it is a parameterized constructor The compiler still adds the super() here
System.out.println("arg constructor of child class");
}
void display()
{
System.out.println("Hello!");
}
public static void main(String args[])
{
Subclass obj= new Subclass();
//Calling sub class method
obj.display();
Subclass obj2= new Subclass(10);
obj2.display();
}
}

Output:
Constructor of parent class

162
Java Programming 163

Constructor of child class


Hello!
Constructor of parent class
arg constructor of child class
Hello!

1. Using Final with Inheritance


.

The final keyword in java is used to restrict the user. The java final keyword can be used in many context.
Final can be:
 variable
 method
 class

if a variable is made as final it cannot change its value

if a method is made as final it cannot override it.

If a class is made as final it cannot be extended by another class

Program to demonstrate using final with inheritance

final class A
{

Class B extends A //error since A is final we can’t inherit it properties


{
void display()
{
System.out.println("demo on final");
}

public static void main(String args[]){


B obj=new B();
Obj.display();
}
}

163
Java Programming 164

1. Polymorphism-ad hoc polymorphism

Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many and
"morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in Java:

1. Compile-time polymorphism or Ad hoc polymorphism


2. Runtime polymorphism. Or Pure polymorphism

We can perform polymorphism in java by method overloading and method overriding.

If you overload a static method in Java, it is the example of compile time polyymorphism.

164
Java Programming 165

1. Compile-time polymorphism or Ad hoc polymorphism:

Ad hoc polymorphism is also known as function overloading or operator overloading because a


polymorphic function can represent a number of unique and potentially different implementations
depending on the type of argument it is applied to.

The term ad hoc in this context is not intended to be pejorative; it refers simply to the fact that this type
of polymorphism is not a fundamental feature of the type system.

i)operator overloading:

Java also provide option to overload operators. For example, we can make the operator (‘+’) for string
class to concatenate two strings. We know that this is the addition operator whose task is to add two
operands. So a single operator ‘+’ when placed between integer operands, adds them and when placed
between string operands, concatenates them.

In java, Only “+” operator can be overloaded:

Example on Operator overloading

// Java program for Operator overloading

class Operatoroverloading {

void operator(String str1, String str2)


{
String s = str1 + str2;
System.out.println("Concatinated String - "+ s);
}

void operator(int a, int b)


{
int c = a + b;
System.out.println("Sum = " + c);
}
}

class Main {
public static void main(String[] args)
{
Operatoroverloading obj = new Operatoroverloading ();
obj.operator(2, 3);
obj.operator("CMR", "EC");
}
}
165
Java Programming 166

Output:

Sum = 5

Concatinated String -CMREC

ii)Method Overloading:

When there are multiple functions with same name but different parameters then these functions are said
to be overloaded. Functions can be overloaded by change in number of arguments or/and change in type
of arguments. Overloaded methods are generally used when they conceptually execute the same task but
with a slightly different set of parameters.

Example on method overloading


class MultiplyFun {

// Method with 2 parameter


static int Multiply(int a, int b)
{
return a * b;
}
// Java program for Method overloading
// Method with 3 parameter
static int Multiply(int a, int b,int c)
{
return a * b*c;
}

// Method with the same name but 2 double parameter


static double Multiply(double a, double b)
{
return a * b;
}
}

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

System.out.println(MultiplyFun.Multiply(2, 4));
System.out.println(MultiplyFun.Multiply(2, 4,2));
System.out.println(MultiplyFun.Multiply(5.5, 6.3));
}
}
166
Java Programming 167

Output:
8
16
34.65

Note:
we overload static methods
we cannot overload methods that differ only by static keyword
we overload main() in Java

2. Runtime polymorphism. Or Pure polymorphism

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden


method is resolved at runtime rather than compile-time.

In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting.

For example:

class A{}

167
Java Programming 168

class B extends A{}

A a=new B();//upcasting .

Example of Java Runtime Polymorphism

In this example, we are creating two classes A and B. B class extends A class and overrides its
display ()method. We are calling the display ()by the reference variable of Parent class. Since it refers to
the subclass object and subclass method overrides the Parent class method, the subclass method is
invoked at runtime.
Since method invocation is determined by the JVM not compiler, it is known as runtime polymorphism.

class A
{
void display ()
{
System.out.println(" A class display ");
}
}
class B extends A
{
void display ()
{
System.out.println(" B class display ");
}
public static void main(String args[])
{
A obj = new B();//upcasting
obj. display ();
}
}

Output:

B class display

Advantages of dynamic binding along with polymorphism with method overriding are.

o Less memory space

168
Java Programming 169

o Less execution time


o More performance

Difference between Static & Dynamic Polymorphism

Static Polymorphism Dynamic Polymorphism

Compile time polymorphism or static


Run time polymorphism or dynamic polymorphism or
1 polymorphism relates to method
dynamic binding relates to method overriding.
overloading.
Difference between Method overloading and Method overriding
Method overloading Method overriding

1 When a class have same method Method overriding - Method of superclass is overridden in
name with different argument, subclass to provide more specific implementation.
than it is called method
overloading.

2 Method overloading is generally Method overriding is always done in subClass in java.


done in same class but can also
be done in SubClass .

3 Both Static and instance method Only instance methods can be overridden in java.
can be overloaded in java.
Static methods can’t be overridden in java.

4 Main method can also be Main method can’t be overridden in java, because main is
overloaded in java static method and static methods can’t be overridden in java (as
mentioned in above point)

5 private methods can be private methods can’t be overridden in java, because private
overloaded in java. methods are not inherited in subClass in java.

6 final methods can be overloaded final methods can’t be overridden in java, because final
in java. methods are not inherited in subClass in java.

7 Call to overloaded method is Call to overridden method is bonded at runtime in java.


bonded at compile time in java.

8 Method overloading concept is Method overriding concept is also known as runtime time
also known as compile time polymorphism or pure polymorphism or Dynamic binding
polymorphism or ad hoc in java.

169
Java Programming 170

polymorphism or static binding


in java.

1. Method Overriding

In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.variable of the current object.

Let's first understand the upcasting before Runtime Polymorphism.

Upcasting

If the reference variable of Parent class refers to the object of Child class, it is known as upcasting

class A{}

class B extends A{}

A a=new B();//upcasting

class A
{
void display ()
{
System.out.println(" A class display ");
}
}
class B extends A
{
void display ()
{
System.out.println(" B class display ");
}
public static void main(String args[])
{
A obj = new B();//upcasting
170
obj. display ();
}
}
Java Programming 171

Output:

B class display

1. Abstract Classes

Abstract class in Java

 A class that is declared with abstract keyword, is known as abstract class in java.
 It can have abstract and non-abstract methods (method with body).
 It needs to be extended and its method implemented.
 It cannot be instantiated.

Example abstract class

abstract class A

Abstract method

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

Example abstract method

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

171
Java Programming 172

Example on abstract class and method(or)Example on multilevel inheritance using abstract

abstract class Hello


{
abstract void hai();
}
abstract class Demo extends Hello
{
}
class Welcome extends Demo
{
void hai()
{
System.out.println("hello");
}
}
public class AbstractClass {
public static void main(String args[])
{
//Hello oa=new Hello();//error because for abstract class we can't create object
//Demo ob=new Demo();//error because for abstract class we can't create object
Welcome oh=new Welcome();
oh.hai();
}
}

Output:hello

172
Java Programming 173

Difference Between Abstract and Concrete class

Abstract Class Concrete Class


Abstract class contain abstract method(i.e a Concrete class can’t contain abstract method
method without implementation)along with
concrete methods
For Abstract class object cannot be created For Concrete class object can be created.
Abstract classes need to be extended in order to Concrete class need not be extended because it is a
make it complete class complete class
Abstract methods of abstract class need to be All concrete methods contain implementations.
implemented in subclass/child class
Example: Example:
abstract class demo class demo
{ {
abstract hai(); void welcome()
void welcome() {
{ System.out.println(“welcome”);
System.out.println(“welcome”); }
} }
}

Object Class

There is one special class, Object, defined by Java.

The Object class is the parent class of all the classes in java by default.

Object is a superclass of all other classes. This means that a reference variable of type Object can refer to
an object of any other class.

The parent class reference variable can refer the child class object, know as upcasting.

173
Java Programming 174

Methods of Object class

The Object class provides many methods. They are as follows:

Method Description

public final Class getClass() returns the Class class object of this object. The Class class can
further be used to get the metadata of this class.

public int hashCode() returns the hashcode number for this object.

public boolean equals(Object obj) compares the given object to this object.

protected Object clone() throws creates and returns the exact copy (clone) of this object.
CloneNotSupportedException

public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's monitor.

public final void notifyAll() wakes up all the threads, waiting on this object's monitor.

public final void wait(long causes the current thread to wait for the specified milliseconds,
timeout)throws until another thread notifies (invokes notify() or notifyAll()
InterruptedException method).

public final void wait(long causes the current thread to wait for the specified milliseconds
timeout,int nanos)throws and nanoseconds, until another thread notifies (invokes notify()
InterruptedException or notifyAll() method).

public final void wait()throws causes the current thread to wait, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).

protected void finalize()throws is invoked by the garbage collector before object is being
Throwable garbage collected.

174
Java Programming 175

The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. So we cannot override
this methods and rest of the methods can be overridden.

Forms of Inheritance-Specialization

Forms of Inheritance :

All objects eventually inherit from Object, which provides useful methods such as equals and toString.

In general we want to satisfy substitutability: if B is a subclass of A, anywhere we expect an instance


of A we can use an instance of B.

Inheritance gets used for a number of purposes in typical object-oriented programming:

Specification inheritance:

If the parent class is abstract, we often say that it is providing a specification for the child class,
and therefore it is specification inheritance (a variety of specialization inheritance).

Specialization inheritance:

The superclass just specifies which methods should be available but doesn't give code.

This is supported in java by interfaces and abstract methods

Construction inheritance

The superclass just specifies which methods should be available but doesn't give code.

This is supported in java by interfaces and abstract methods

Extension inheritance

The superclass is just used to provide behavior, but instances of the subclass don't really act like the
superclass. Violates substitutability. Exmample: defining Stack as a subclass of Vector. This is not clean
-- better to define Stack as having a field that holds a vector

If a child class generalizes or extends the parent class by providing more functionality, but does not
override any method, we call it inheritance for generalization.

175
Java Programming 176

The child class doesn't change anything inherited from the parent, it simply adds new features.

An example is Java Properties inheriting form Hashtable. subclass adds new methods, and perhaps
redefines inherited ones as well

Inheritance for Limitation

• If a child class overrides a method inherited from the parent in a way that makes it unusable (for
example, issues an error message), then we call it inheritance for limitation.

• For example, you have an existing List data type that allows items to be inserted at either end, and
you override methods allowing insertion at one end in order to create a Stack.

• Generally not a good idea, since it breaks the idea of substitution. But again, it is sometimes found
in practice. the subclass restricts the inherited behavior. Violates substitutability. Example: defining
Queue as a subclass of Dequeue.

Combination

The child class inherits features from more than one parent class. This is multiple inheritance .

Summary of Forms of Inheritance

Specialization. The child class is a special case of the parent class; in other words, the child class is a
subtype of the parent class.

Specification. The parent class defines behavior that is implemented in the child class but not in the
parent class.

Construction. The child class makes use of the behavior provided by the parent class, but is not a
subtype of the parent class.

Generalization. The child class modifies or overrides some of the methods of the parent class.

Extension. The child class adds new functionality to the parent class, but does not change any inherited
behavior.

Limitation. The child class restricts the use of some of the behavior inherited from the parent class.

Variance. The child class and parent class are variants of each other, and the class-subclass relationship
is arbitrary.

176
Java Programming 177

Combination. The child class inherits features from more than one parent class. This is multiple
inheritance .

Benefits of Inheritance

Benefit of using inheritance:

 A code can be used again and again


 Inheritance in Java enhances the properties of the class, which means that property of the
parent class will automatically be inherited by the base class
 It can define more specialized classes by adding new details.
 In addition we have benefits such as

 Software Reuse
 Code Sharing
 Improved Reliability
 Consistency of Interface
 Rapid Prototyping
 Polymorphism
 Information Hiding

Cost of Inheritance

 Execution speed
 Program size
 Message Passing Overhead
 Program Complexity

This does not mean you should not use inheritance, but rather than you must understand the benefits, and
weigh the benefits against the costs.

177
Java Programming 178

[JNTUH-PREVIOUS QUESTION PAPERS]


UNIT WISE SHORT QUESTION

UNIT-I

1. What is data abstraction? [2M]


2. Explain the feature of Java [2M]
3. Explain the types of operators used in java [3M]
4. What is static inner class [3M]
5. List string manipulation functions of Java String class. [3M]
6. Explain the use of ‘final’ keyword. [3M]
7. Differentiate between class and object. [2M]
8. What is meant by ad-hoc polymorphism? [3M]
9. What is abstract class? Give example. [2M]
10. What is inheritance? Give example. [2M]
11. Define the basic characteristics of object oriented programming. [3M]
12. Explain the use of ‘for’ statement in Java with an example. [3M]
13. What is the significance of Java’s byte code? [2M]
14. List the applications of object oriented programming. [3M]
15. Differentiate between break and continue statement. [2M]
16. What is type casting? Explain with an example. [3M]
17. What is the use of super keyword? [2M]
18. Why is Java known as platform independent? [3M]
19. What is the size of char data type? Why does it differ from C language? [3M]
20. Differentiate between print() and println() methods in Java [2M]
21. What are symbolic constants? Explain with examples. [3M]
22. Program to convert foreign heat to centigrade [3M]
23. Program to find sum of given number [3M]
24. Program to display [3M]
25. What is the purpose of this Keyword [3 M]
26. Explain about enumerated data type . [3 M]
27. What is Anonymous inner class . [3 M]
28. what is the difference between abstract class and concrete class [2 M]
29. What are Lexical issues in java [2M]
30. Write about console. [3 M]

178
Java Programming 179

JNTUH-PREVIOUSLY ASKED _ESSAY_QUESTIONS

1.a)What are the responsibilities of an agent?


b) What is the purpose of constructor in Java programming? [5+5]
2. Define inheritance. What are the benefits of inheritance? What costs are associated with inheritance?
How to prevent a class from inheritance? [10 M]
3. Write a program to demonstrate hierarchical and multiple inheritance using interfaces [10 M]
4. a)Describe the structure of a typical Java program with an example.
b) What are the benefits of inheritance? Explain the various forms of inheritance with suitable code
segments [5+5]
5Write the significance of Java Virtual Machine. [5 M]
6.a) How do we implement polymorphism in JAVA? Explain briefly.
b) What is an array? How do you declare the array in java? Give examples. [5+5]
7.a) What is meant by byte code? Briefly explain how Java is platform independent.
b) Explain the significance of public, protected and private access specifies in Inheritance.
[5+5]
8.a) Explain different parts of a Java program with an appropriate example.
b) How does polymorphism promote extensibility? Explain with example. [5+5]
9. What are the drawbacks of procedural languages? Explain the need of object oriented
programming with suitable program. [10 mark]
10.a) Does Java support multi way selection statement? Justify your answer.
b) Describe type promotion rules of Java. [5+5]
11.a) Explain the basic concepts of object oriented programming.
b) What is the usage of enumerated data type? Give examples. [5+5]
12.a) Discuss Java jump statements.
b) Write about garbage collection in Java.
c) Explain the use of ‘this’ keyword. [3+3+4]

13.a) Explain method overriding with a suitable example program.


b) With suitable program segments describe the usage of ‘super’ keyword. [5+5]
14 What is a nested class? Differentiate between static nested classes and non-static nested classes.
15.a) What is inheritance and how does it help to create new classes quickly.
b) Describe different levels of access protection available in Java. [5+5]
16.a) List the primitive data types available in Java and explain.
b) What is polymorphism? Explain different types of polymorphisms with examples.
[5+5]

179
Java Programming 180

17.a) What are the drawbacks of procedural languages? Explain the need of object oriented
programming with suitable program.
b) Discuss the lexical issues of Java. [5+5]
18.a) What are the primitive data types in Java? Write about type conversions.
b) What is a constructor? What is its requirement in programming? Explain with program.
[5+5]

19.a) With suitable code segments illustrate various uses of ‘final’ keyword.
b) Discuss about anonymous inner classes. [5+5]
20.a) What feature of Java makes it platform independent and portable?
b) Program to find sum of given number

21. Explain about anonymous inner clas


22.a)write a java Program to display
1
12
123
1234
12345
b) Compare and cons tract overloading and overriding with an example [5+5]
23 a).Different data types in java
b.)Program to convert foreign heat to centigrade [5+5]
24 a) Explain multilevel inheritance with the help of abstract class in your programb)
b)Is Java a robust language? Justify your answer. [5+5]
25.a) Differentiate between a class and object.
b) Demonstrate constructor overloading concept. [5+5]
26 a) Write a java program to find the factorial of a given number.
b) Explain the different types of constructors with an example. [5+5]
27 a) Write a program to find the transpose of a given matrix.
b) Explain the scope and life time of the variable. [5+5]
28 a) Explain the different parameter passing mechanisms used in Java with an example.
b) Write a runtime polymorphism program in Java by using interface reference variable.
[5+5]

180

You might also like