Java - Httpilpintcs - Blogspot.in
Java - Httpilpintcs - Blogspot.in
If you manage your work without any mess with the help of alarms in a smart phone
An application is a type of software that allows you to perform specific tasks which otherwise is very difficult to
perform manually.
Before we go any further think about few computer applications you are familiar with.
Sticky Notes
You can use Sticky Notes to write a to-do list, jot down a phone number, or to do anything else that you would
Notepad is a basic text editor that you can use to create simple documents.
WhatsApp Messenger is a proprietary, cross-platform instant messaging subscription service for smart phones.
Facebook Application
A social utility that connects people with friends and others who work, study and live around them
IRCTC Portal
Online Passenger Reservation System provides booking facility of Railway tickets online
By giving a closer look to these applications you will find that few of the applications are specially designed for
Desktop/Personal computer while few others only work on mobile devices. Similarly you will find that in order
to run certain other applications you need a web browser like Internet Explorer, Chrome etc.
i. Desktop Applications
ii. Mobile Applications
iii. Web Applications
Desktop Applications – Desktop Applications are applications that runs stand alone in a desktop or laptop
computer.
Mobile Applications
Desktop and laptop computers aren't the only devices that can run applications. You can also download
applications for mobile devices like smart phones and tablet computers, which opens up a lot of new
Web Applications - are applications that are accessed over a network such as the Internet or an Intranet.
Passport Seva Portal to deliver passport services to citizens in a timely transparent manner.
1.3. Basic Application Architecture
At the highest and most abstract level, the logical architecture view of any system can be considered as a set of
The top most layer of the application through which end-user interacts with the system. The main
function of this layer is to translate the tasks and results to something which the end user can understand.
Business layer. This layer implements the core functionality of the system, and encapsulates the relevant
business logic.
Data/Resource layer. This layer stores and retrieves information from the storage systems (databases/file
systems). The information is then passed to the Business layer for processing and then eventually back to the
user.
Layer
Irrespective of the type of application that you are designing, and whether it has a user interface or it is a
services application that only exposes services (not to be confused with services layer of an application), you
can decompose the design into logical groupings of software components. These logical groupings are called
layers. Layers help to differentiate between the different kinds of tasks performed by the components, making
Benefits of layers:
Simplicity: easy to design once layers and their interaction are defined clearly
Flexibility: easy to modify and develop networks by separate layers modifications
Incremental changes: add new layers, add new functions to a layer
Tier
When the logical groups of components are physically separated in different machines, it is known as Tier. The
Single/One Tier Architecture – All layers (Presentation, Business and Resource) are at same place. The
application does not require network connection to work. It is easy to install in a system and use it.
Eg: MS Access, MS Excel
1. Presentation Layer in one machine and Business & Resource Layer is available in different machine
2. Presentation & Business layer in one machine and Resource layer in another machine.
3 – Tier Architecture – In this all three layers of an application are physically separated in different machines.
Eg : Most of the web applications which involves data storage are 3 -tier architecture applications.
The below figure will help you in visualizing the communication in a web application.
In this example a 3-tier web application system is represented where all three layers of the application is
processing the request its again sent to Storage/Resource tier for storing.
Multi-tier/ N-tier Architecture: All the 3 -tiered applications can be again physically separated by breaking it
into different tiers and establishing a communication between all those tiers.
The terms tier and layer are often used interchangeably. When I use tier, I am referencing a physical layer.
When I use layer, I am referencing a distinct software layer. Layers must exist on a tier, and thus tiers contain
layers.
Each application gives the CRUD feature in its own way. CRUD is the acronym for Create, Read, Update and
Delete.
Read - There should be a feature where by the data added can be read
Update – There should be a facility to update the data created. Which user can perform this operation will
Delete – There should be a way to remove the data created. Again like Update, who can perform delete
ie, Create will happen first, Update and Delete should happen only after the data is Read.
Create
Let’s take example of well-known website Google. When you first time register or create an account in this
website, you have to fill certain details and click on register or sign up button. On clicking on the button,
information entered by you will be verified and added into the database and your account will be created. This
Similarly, adding a contact in gmail application of your Google account is also an example of create operation.
You can find these kind of options in many other websites. Creating your Facebook, twitter, IRCTC account,
registering in naukary.com, even creating an event in your Facebook account are all examples of create
operation.
Whenever a new set of information is added into the database of the system, then it is a create operation.
It results in creation of new entry into the database of that web application.
Read
Let’s take the example of Google again. When you log in to your Google account, a home page appears. It is a
read operation. In this, the web application retrieves the information from the application's database,
corresponding to the log in credentials which you have provided and displays it.
Viewing your profile by clicking on view profile is also an example of read operation.
When you are searching a person by their name, it is also a read operation. In this the web application will
search for various user profiles with that particular name and displays the list.
You can relate these examples with options being provided by many other social networks and web
applications.
It shows that, read is basically, retrieving data from the database and displaying it to the user.
Update
Think, you want to change some of your basic information in your Google account, then, you will click on the
edit button, which will take you to the edit profile page. It will display all the information which you have
already added. You can enter the new information and by clicking on save, the information will get updated.
Editing the contact details in gmail account is another example of update operation.
First time while filling the information, you might have left few non-mandatory fields blank. Filling those
information later is also an example of update operation. Even removing few information (not all) like, phone
number from your profile is also an example of update. Here the particular information will be set to blank.
Basically, update is, first a read operation, which displays the information which is already present in the
database of the web application and then overwrites it with a new information.
Delete
Let us take the example of contacts in gmail. If you want to delete a contact from the contacts list, you can
select the particular contact and click on the delete button. It will delete the contact from the contacts list.
If in future, you do not wish to use the account which you have created, then you can go for deactivation of
Now a day most of the websites do not provide direct deletion, they allow you to just deactivate the account.
Delete is basically, deleting the information from the database of the website or making the information
inaccessible.
Need of programming and Introduction to OOP
Approach
let's take a few moments to understand what we mean by a problem and problem solving.
Driving a car to office, Making a cup of tea, Solving a crossword puzzle . all these are
examples of problems that we face every day.
i) Problem Identification
This stage involves detecting and recognizing that there is a problem; identifying the
nature of the problem; defining the problem. This phase also involves , structuring the
problem. Structuring the problem is all about gaining more information about the problem
and increasing understanding. By spending some time defining the problem will helps to
understand it more clearly and it will leads you to the next phase.
Once you complete the information gathering in the first phase, the next step is to
identify all possible solutions. Once the requirements have been finalized, we design a
solution(s) to the issue. We might note the steps on a piece of paper or we might take a
print out of it. Referring to these artifacts makes our work simpler and gives us a clear
idea of how to proceed with a task .Hence design becomes a very important task as far as
any system development is concerned.
iii) Implementation
Implementation means acting on the chosen solution .This phase deals with the actual
process of implementation of our design. In terms of programming, the code would follow
the design and then write code to translate the human-understandable design to a machine
understandable language. During implementation more problems may arise especially
if identification of the original problem was not carried out fully.
Example
Let us take an example of making a cup of tea. This is a minor problem but a
problem nevertheless. As a human being , we normally follow the established process of
making tea. Let us assume that we need to automate the system of making tea and we are
building a tea-vending machine. In the beginning, the tea-vending machine does not know
what it needs to do and what will be the outcome of its actions. Hence we program the
machine to understand our requirements and work accordingly. Assume that we are going to
instruct the machine to make tea. We need to think of the following things
Ingredients of tea will normally be milk,water, sugar and tea-leaves. Hence we instruct the
machine to take milk, sugar and tea-leaves as the input.
Now once we have the inputs, we need to take the following steps
1. Boil water
2. Add tea-leaves
3. Add sugar
4. Add milk
We will instruct the machine to perform these steps sequentially. The machine understands
this and using the inputs that were provided to it, will solve the problem.
Finally the outcome of these steps will be tea and in the machines terms, this is called as the
output.
Analytical skills are the ability to imagine, collect information, arrange it, analyse, solve
complex problems, and make decisions. The ability to organise data and draw proper
correlations and then interpreting these trends in terms that are meaningful to others is
called Analytical skill.
iii) Output
Make reasonable predictions about the extent of rain next year.
As we can see, if this order is followed, the puzzle would be solved. Hence
the knowledge of the steps to reach the solution is called as Imperative knowledge.
Abstraction
As a user, we just need to know that a fridge can be used to preserve food materials by
freezing them. Hence the user just needs to open the fridge and put the items inside.
User does not need to know the internal functioning of the fridge, hence the
wiring,electronics and other details are hidden behind the body of the fridge. This process of
hiding the irrelevant data is called as Abstraction.
Abstraction types
i) Functional Abstraction
Let see the above refrigerator example, all refrigerator contains a freezer box which can
preserves the food material below zero degree Celsius temperature. As a user we need to
get the food material to be preserved but we don't need how it will be get preserved , this
way of hiding
irrelevant details or process and getting the functionality of preservation to be done is an
example of functional abstraction.
Let see the above refrigerator example,the inner temperature of the refrigerator is an
essential data which is sensed by the sensor and refrigerator monitors and controls the inner
temperature. Here inner temperature is the internal data which is used by the refrigerator to
maintain the temperature of the fridge, which is not controlled or altered by external
mechanism and is used by the functionalities of the refrigerator is an example of data
abstraction.
Programming languages can be used to create programs that control the behaviour of a
machine and/or to express algorithms precisely.
Thousands of different programming languages have been created, mainly in the computer
field, with many more being created every year.
ii) Grammar: defines how syntactical elements need to be combined to form programs
Eg: Continuing the same example, English language has got a certain grammar. The
grammar has to be followed to construct a proper sentence. 'I is a boy' is grammatically
wrong although syntactically correct.'I am a boy' is syntactically and grammatically correct.
The readability of source code has a direct impact on how well a developer comprehends a
software system.
iii) Maintainability
Code maintainability refers to how easily that software system can be changed to add new
features, modify existing features, fix bugs, or improve performance
Although readability and maintainability are the result of many factors, one
particular facet of software development upon which all developers have an influence is
coding technique. The easiest method to ensure that a team of developers will yield quality
code is to establish a coding standard, which is then enforced at routine code reviews.
The following are the different programming approaches which evolved were:
Unstructured Programming
Structured Programming
Procedural Programming
Modular Programming
Object Oriented Programming
Example: C language
The way of structured programming doesn't relate to real world problem scenarios. The
current problem scenarios doesn't call for functions that operate on data, rather the
scenarios have data and their associated behaviour. In such cases, the structured way of
programming becomes very huge and cumbersome. Information has to be manipulated
across all functions and an association of varied information in a problem scenario is not
possible.
We write programs that make up software to solve a problem in real world. In real world
problem domains we do not find any functions that work on data. We find objects that are
described by some state (data) and having some behaviour (functions or routines).
In OO programming, the program basic entity is object. An object is any real world entity that
has a well-defined structure and behaviour.
Forget programming for a while. Think about the Real World and the things that are in it.
What things are objects? What things are not objects?
Look around you. You may try to list five objects and list five non-objects.
It is easier to list things that are objects than to list things that are not objects. Just to talk
about something seems to make it an object, somehow. When we observe, the humans view
the world in object-oriented terms. The human brain wants to think about objects, and our
thoughts and memories are organized into objects and their relationships. Perhaps non-
human brains work differently.
One of the ideas of object-oriented software is to organize software in a way that matches
the thinking style of our object-oriented brains.
Look at my list of objects and your own list and try to describe what all objects have in
common. What makes an object?
• An object is made of tangible material (the pen is made of plastic, metal, ink).
• An object holds together as a single whole (the whole pen, not a fog).
• An object has properties (the color of the pen, where it is, how thick it writes.).
• An object can do things and can have things done to it.
The first item in this list is too restrictive. For example, you can think of your bank account as
an object, but it is not made of material. (Although you and the bank may use paper and
other material in keeping track of your account, your account exists independently of this
material.) Although it is not material, your account has properties (a balance, an interest rate,
an owner) and you can do things to it (deposit money, cancel it) and it can do things (charge
for transactions, accumulate interest).
The last three items on the list seem clear enough. In fact, they have names:
i. An object has identity (each object is a distinct individual).
ii. An object has state (it has various properties, which might change).
iii. An object has behavior (it can do things and can have things done to it).
iv. This is a somewhat ordinary description of what an object is like. (This list comes from
the book Object-oriented Analysis and Design, by Grady Booch, Addison-Wesley, 1994.) Do
not be surprised if other notes and books have a different list. When you start writing object-
oriented software you will find that this list will help you decide what your objects should be.
Every object has its own characteristics. Every object has 5 sets of characteristics Viz. State,
Behaviour, Responsibility, Communication and Identity.
States of an Object: The states of an object are known by the various attributes that
describe the Object. Example: If Human is an Object, colour of Hair, number of Teeth, skin
tone, etc., describe the object. These form the states of the Object, Human
More Examples:
i. Make of Tyres, Colour, Engine Type, Mileage of a Car Object.
ii. Account Number, Account Holder Name, Deposit Amount, Transaction Details in a Bank
Account Object.
iii. Employee ID, Employee Name, Date of Birth, Date of Joining, Number of Dependants in
an Employee Object.
Examples:
Examples:
The knowledge of the states like knowing the dependant details, retrieving date of birth of an
employee are knowing responsibility.
All operational logic performed on the states of the object through its behaviours constitutes
the Doing responsibility. Example: Calculate performance of the car
To enable understand the characteristics of an object, let us consider the following example
Answers:
Is the tube of tennis balls an object?
Yes. It has identity (my tube of balls is different than yours), it has state (opened, unopened,
brand name, location), and behavior (although not much).
Is each tennis ball an object?
Yes. It is OK for objects to be part of other objects. Although each ball has nearly the same
state and behavior as the others, each has its own identity.
Could the top two balls be considered a single object?
Not ordinarily. Each has its own identity independent of the other. If they were joined
together with a stick you might consider them as one object.
Is the color of the balls an object?
No. It is a property of each ball.
Is your understanding of tennis balls an object?
Probably not, although it is unclear what it is. Perhaps it is a property of the object called
"your brain."
Software Objects:
Many programs are written to do things that are concerned with the real world. It is
convenient to have "software objects" that are similar to "real world objects". This makes the
program and what it does easier to think about. Software objects have identity, state, and
behavior just as do real world objects. Of course, software objects exist entirely within a
computer system and don't directly interact with real world objects.
An object stores its state in fields (variables in some programming languages) and exposes
its behavior through methods (functions in some programming languages).
What are software objects made out of?
Computer Memory.
Its important to ask yourself :
Think your table lamp may have only two possible states (on and off) and two possible
behaviors (turn on, turn off), but your table radio might have additional states (on, off, current
volume, current station) and behavior (turn on, turn off, increase volume, decrease volume,
seek, scan, and tune).These real-world observations all translate into the world of object-
oriented programming.
class Car {
int speed = 0; //state
int gear = 1; //state
// Behaviour
void changeGear(int newValue) {
gear = newValue;
}
// Behaviour
void speedUp(int increment) {
speed = speed + increment;
}
void applyBrakes(int decrement) {
speed = speed - decrement;
}
void printStates() {
System.out.println("cadence:" + cadence + " speed:" + speed + "
gear:" + gear);
}
}
All various types of Cars which follow the generalization become Objects. Example: Maruti,
Volkswagen, Audi, etc.,.
Object-oriented programming:
Program is composed of a collection objects that communicate with each other
Introduction to Java
History of Java
Brief to Java Platform, JVM, JDK, JRE
Installation of JDK and its configurations
Run a sample program
Java is Simple:There are various features that makes the java as a simple language.
because Java is easy to learn and developed by taking the best features from other
languages mainly like C and C++.
Java is Platform Independent-Java provides the facility to "Write once -Run any
where"(Known as platform independent).
Java is Robust-Java has the strong memory allocation and automatic garbage collection
mechanism. It carries out type checking at both compile and runtime making sure that every
data structure has been clearly defined and typed. compiler checks the program for any error
and interpreter checks any run time error that every data structure is clearly defined and
typed.
In a network, two very broad categories of objects are transmitted between the server and
your personal computer: passive information and dynamic, active programs. For example,
when you read your e-mail, you are viewing passive data. Even when you download a
program, the program’s code is still only passive data. Even when you download a second
type of object can be transmitted to your computer: a dynamic, self-executing program. Such
a program is and the server yet initiates active agent on the client computer. For example,
the server to display properly the data that the server is sending might provide a program.
As desirable as dynamic, networked programs are, they also present serious problems in the
areas of security and portability
Let us begin by writing our first Java program that prints a message "Hello, world!" to the
display console, as follows:
? Hello World program in java
Step 1: Write the Source Code: Enter the following source codes using a programming text
editor (such as TextPad or NotePad++ for Windows or gedit for UNIX/Linux/Mac) or an
Interactive Development Environment (IDE) (such as Eclipse or NetBeans - Read the
respective "How-To" article on how to install and get started with these IDEs – to see more
about IDE refer the Glossary).
Save the source file as "Hello.java". A Java source file should be saved with a file extension
of ".java". The filename shall be the same as the classname - in this case "Hello".
before run java file you should set the path and classpath
path: to instruct compiler that where your JDK is installed
How to set the path:
set PATH=.;C:\Program Files\Java\jdk1.5.0\bin(for example:
C:\Program Files\Java\jdk1.5.0\bin (Provided your jdk installed in the given path)
See the below screen shots in order to run any java program in command prompt mode
Summary:
Java is platform Independent and Portable.
Java is Robust and secured.
Java is pure object oriented language.
Java does compilation as well Interpretation.
Java latest version of JDK 7(Current version is being used in Industry)
JDK and JRK has to be installed in order to Java program.
JVM is:
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.
An implementation Its implementation is known as JRE (Java Runtime Environment).
Runtime Instance Whenever you write java command on the command prompt to run the
java class, and instance of JVM is created.
The JVM performs following operation:
Loads code
Verifies code
Executes code
Provides runtime environment.
JDK - Java Development Kit
A Java Development Kit (JDK) is a program development environment for writing Java
applications. It consists of a run time environment that sits on top of the operating system
layer and also the tools and programming that developers need to compile, debug, and run
applications written in the Java language.
The JDK (Java Development Kit) is used for developing java applications. The JDK includes
JRE, set of API classes, Java compiler, Webstart and additional files needed to write Java
applications. The JDK (Java Development Kit) contains software development tools which
are used to compile and run the Java program. Both JDK and JRE contains the JVM
3.4. JRE- Java Runtime Environment
Java Runtime Environment (JRE), also known as Java Runtime, is part of the JDK. JRE
provides the minimum requirements for executing a Java application; it consists of the Java
Virtual Machine (JVM), core classes, and supporting files. Thus it covers most end-users
needs and contains everything required to run Java applications on our system.
Java Environment Setup
Java installation and environment variable setup steps are clearly described in Video 6.
Follow the instructions given in the video and set up the Java environment.
Download JDK 5 or above setup for installation. Link to download latest version of java, jdk 7
is given below.
http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html
Set the environment variables CLASSPATH and JAVA_HOME after JDK installation.
Command Prompt is a feature of Windows that provides an entry point for typing MS-DOS
(Microsoft Disk Operating System) commands and other computer commands. The most
important thing to know is that by typing commands, you can perform tasks on your
computer without using the Windows graphical interface.
When you're using Command Prompt, the term command prompt also refers to the right
angle bracket (>, also known as the greater than character) that indicates the command line
interface can accept commands. Other important information, such as the current working
directory (or location) where the command will be run, can be included as part of the
command prompt.
For example, if you open the Command Prompt window and see the C:\> command prompt
with a blinking cursor to the right of the right angle bracket character (>), you know that the
command you enter will be run on the entire C drive of your computer.
2. How do I get to a command prompt?
Open the Command Prompt window by clicking the Start button Picture of the Start button,
clicking All Programs, clicking Accessories, and then clicking Command Prompt.
Execute a Sample Java Program using Command Prompt
Steps to run a java program is described in Video 6. We will provide you a sample Java
program for execution.
Create a java file “TestClass.java” and put the sample code given below in it. We will study
more on how to write a Java class later in this course. This is just to understand how to
compile a Java program file and how to execute it using command prompt.
class TestClass {
public static void main(String args[])
{
System.out.println("TestClass is running fine.");
}
}
After execution of TestClass, you should get the message on the command prompt as
"TestClass is running fine". Have you got the output on command prompt / console.
Reference links
http://www.devmanuals.com/tutorials/java/corejava/JavaHistory.html
http://www.freejavaguide.com/history.html
http://www.devmanuals.com/tutorials/java/corejava/IntroductionJava.html
http://www.w3resource.com/java-tutorial/download-and-Install-JDK-Eclipse-IDE.php
http://docs.oracle.com/javase/tutorial/getStarted/application/index.html
http://www.devmanuals.com/tutorials/java/corejava/JavaEclipseHelloWorld.html
http://www.devmanuals.com/tutorials/java/corejava/JavaVirtualMachine.html
http://viralpatel.net/blogs/java-virtual-machine-an-inside-story/
http://www.javatpoint.com/internal-details-of-jvm#jvminternalarch
http://docs.oracle.com/javase/tutorial/getStarted/intro/definition.html
http://en.wikipedia.org/wiki/Java_Development_Kit
http://www.javatpoint.com/difference-between-jdk-jre-and-jvm
http://www.oracle.com/technetwork/java/javase/downloads/index.html
http://www.oracle.com/technetwork/java/javase/archive-139210.html
After the download is complete, double click the installer and follow the installation process.
Follow the recommended settings during installation.
Depending on the location that was chosen to install the JDK, you would see the following
contents.
The outer most folder that has all the installed contents is generally referred to as Java
Home.
So, as the per the below installation, the Java Home directory is C:\jdk1.5.0
The developer frequently needs an access to the java compiler (javac) and java interpreter
(java). These tools come along with JDK and you will find them under the bin folder in Java
installation folder.
To enable to developer to use these tools from any directory in the command prompt, we set
these values in the operating system environment variable.
Configure JDK:
Environment variables are key and value pair. PATH is one of the environment variable
(key). It's value is a collection of more than 1 directory path. Operating system uses the
PATH variable to scan all the directory when a user want to execute a tool without
mentioning the installation path.
As you can see, the delimeter (;) is used to separate multiple directory mentioned as a value
to the PATH environment variable.
To set and environment variable, right click on Computer icon, and select Properties.
It will open Control Panel Home as shown below:
Right click on the Advanced system setting, it will open System Properties as shown below.
Go to the Advanced tab, and click on the Environment Variables button available at the
bottom. This is would open a small window that will list all the existing environment variables.
It has 3 button – New (to add a new environment variable), Edit (to edit the value of existing
environment variable) and Delete (to delete and existing environment variable)
Click on the button – New. It will open a new window with 2 empty text boxes. Enter the
variable name as PATH. In variable value, enter the path to the bin folder in java installation
directory.
Example:
Create a folder javaproject in your D: drive. Create a file MyFirstJavaProgram.java with
following contents.
3.7. Eclipse
Good as of now we have learnt how to install JDK on our systems. We also learnt how to
write a java program, compile it and run the java program. Let us now learn another way of
writing Java program. That is using an IDE. IDE means Integrated Development
Environment. There are many IDE’s available in the market but we will be using
Eclipse. Eclipse is an Integrated Environment which provides programmers perform a lot of
activities required during development at one place. Some of the activities that can be done
using Eclipse are writing code, making code more readable, like indentation, providing
spacing, compiling, running, debugging etc. There are many tools available in the market
which helps in doing each of the activity mentioned above in separate windows, but IDE
integrates all the above windows into one environment. Using Eclipse we can write programs
in many languages like C, CPP and Java, html, Perl etc. But we will only be focused on
learning how to use Eclipse to develop Java programs. First of all let us learn how to get
eclipse installed in our system.
Install Eclipse:
Eclipse has been evolving and there are many versions available and you may choose any
of the existing versions for java development but we would recommend use of Galileo. You
can download the same using the following
urlhttp://www.eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/galileor . You
may download the appropriate version depending upon your Operating System. Please
refer the below diagram for the same.
Make sure you download the right installation file based on your OS (winodws, linux or Mac)
and architecture (32 or 64 bit). You may download and place the archive (zip, tar.gz) at any
location of the hard disk of your system. Then the archive needs to be extracted using any of
the archiving tools provided by your OS. The installation of eclipse is done just by unzipping
the downloaded zip file.
Configure Eclipse:
Before starting eclipse, make sure that you have downloaded Java Development Kit(JDK).
We recommend you to download version 1.5. Refer to the download, install & configure JDK
section present in this document for details.
Start eclipse from the eclipse installation directory. The eclipse installation directory will have
an eclipse application as highlighted below.
1. Start Eclipse
When eclipse starts up for the first time it prompts you for the location of the workspace
folder. All your data will be stored in the workspace folder. You can accept the default or
choose a new location.
If you check "Use this as the default and do not ask again", this dialog box will not come up
again.
After selecting workspace, you will see a welcome screen. Close the welcome screen.
Setting up eclipse
Now we need to make sure of certain things before proceeding with the creation of Java
Project. We should set up environment for running programs in eclipse.
2.1 Compiler compliance level
Right click Window and select Preferences.
Preferences window is opened. Now select Compiler from Java
Compiler compliance level can be changed here. Select the appropriate version from drop
down and click OK.
In the above scenario previous version was 1.6 which is now changed to 1.5
2.2 Installed JREs
You can also add/remove JRE definitions using Installed JREs from Java of Preferences tab.
Now the default JRE is already checked in the Installed JREs, you can add new JRE using
Add button and to remove, select the existing JRE and click Remove button.
On clicking Add a window is opened where you need to select JRE Type
Select the type of JRE and click Next. Now you need to add JRE definition, for this you need
to click on Directory.
Choose the appropriate folder from the respective location and click OK
Now the library files related to the new definition are added. Click Finish to add it.
Select default JRE and click OK.
A wizard to create new project will appear. Select Java Project from the list of options
available. Click Next.
It opens a wizard to configure few setting for the new project. Enter the project name of your
choice – eg. FirstJavaProject. Make sure your have select the below highlighted options.
Click Finish.
Eclipse may ask you to open the associate perspective. Click Yes.
4. Project Directory.
Eclipse created a package tcs.ilp under the src folder. It also creates a java file
MyFristJavaProgram.java. Double click on the MyFristJavaProgram.java and eclipse opens
the contents of the file in a window.
Add the main method and a simple print statement.
3.8. Compileonline.com
Compileonline.com is a web application which is used to compile and execute programming
languages online. You can compile java programs as well. Here is the quick guide to compile
and execute your program.
Step1:
Open browser and type www.compileonline.com in the address bar.
Step 2:
Click on “Java” in the Programming Languages section.
Now a window appears something like this:
The left hand area is where the source code is written and the right side “Result” tab is
where the output is displayed. Steps to compile and execute the programs are given on the
right hand area. We will now execute a sample code.
Step 3: Write a program on the left hand area in “Main class file” tab
Step 4: Finally click the following button [ Ctrl+E on Windows & Command+E on Mac ]
to see the result.
Step 5: The result is displayed on the right hand side
Step 2: Click “Support class file” and write the program in the area provided
In the above program, we have created a Dog class which has a method bark(). Now to
execute the above program, we need a Test class which contains main() method and a call
to bark() method.
Step 3: Click Main class file tab and create a class with main() method
Variable declaration
Example:
Note:Product.java example which is been given that can not be executed as main method is
not there.
Types of Variables
Instance variables are declared in a class, but outside a method, constructor or any block.
Access modifiers such as private, public, protected can be specified for instance variables.
They are visible for all methods, constructors and blocks in the class.
Values can be assigned during the declaration or within the constructor.
Example 1:
In this example we can see how to declare and assign initial value to the variables. We can
also see the access modifiers used with the variable declaration. Here we have used private
access modifier.
Note:Product.java example which is been given that can not be executed as main method is
not there.
Example 2:
Note:Employee.java example which is been given that can not be executed as main method
is not there.
The default initial values of the data members of Employee class are as shown below:
name is null (as it is a String object reference)
id is 0(as it is primitive type : integer)
basicSalary is 0.0 (as it is primitive type : float)
Local variables
Example:
This example demonstrates how to declare and use local variables.
Note:Calculator.java example which is been given that can not be executed as main method
is not there.
Here "d" is the local variable created inside the calculation method.
Parameters
Parameters are the list of arguments that come into the function. Parameters are used to
pass values to functions and to receive values in a function.
Here we are using int a, int b as parameters to receive values sent to add method.
Note:Calculator.java example which is been given that can not be executed as main method
is not there.
Example 2:
This example demonstrates to how to use parameters to send values to functions.
In c.add(a,b) a and b act as parameters, which are used to send values to add method.
Note: Until, you will not include import statement or if both programs (Tester.java,
Calculator.java)
are not in same package that program will not run.
i. Class variables also known as static variables, are declared with the static keyword in a
class.
ii. These are declared outside a method or constructor.
iii. The basic concept behind static is, there would only be one copy of each class variable
per class, regardless of how many objects are created from it.
iv. That means, for a static field, regardless of the number of instances created, will hold the
same data across all objects.
v. If the value in static variable is changed, it is reflected in all objects. On the other hand,
non-static fields of objects store their individual state. The value of a non-static field (also
called instance variables) is unique for every instance / object.
vi. Static variables are created when the program starts and destroyed when the program
stops.
vii. Default values are same as instance variables. For numbers, the default value is 0; for
boolean, it is false; and for object references, it is null.
viii. Values can be assigned during the declaration or within the constructor.
ix. Static variables in a class can be accessed from a second class by calling with the class
name of the first. ClassName.variableName. Thus we can see that the static variables are
not called by objects. It is directly called with class name.
Example 1:
Following example demonstrates how to declare and use static variables.
Note: StaticExample.java example which is been given that can not be executed as main
method is not there.
In StaticExample class we have declared a static variable called num.
We have created object of StaticExample class in TestStatic class to access the attributes
and methods of StaticExample class.
Since num is a static variable, we can access it directly with the class name, before
creating object of that class.
Static Functions
Through these courses we have already come across a static function. Can you guess? Yes,
it’s nothing but the main method which we used to test the classes and functions which we
write.
Static methods are conceptually the same as static variables, thus the reasons to use or not
use them are similar. They belong to the class, not specific objects of that class. There is no
need of a logical instance variable to call these methods. That is, if a method needs to be in
a class, but not tied to an object, then it make it static. If the method is more logically part of
an object, then it should not be static.
Main is static because JVM can call main without creating an object first. It probably
simplified the design of the JVM.
Static methods are also accessed by calling the method with the class name.
ClassName.methodname.
Note: Calculator.java example which is been given that can not be executed as main
method is not there.
Here add is a static method written in calculator class. We are accessing that in
TestCalculator class.
Since it is static method we can access it without creating object of that class, directly with
the classname.
Points to remember
Each of these types uses a fixed number of bits. i.e. same number of bits will be used no
matter what value is represented.
For example, all values represented using the short data type use 16 bits. The value zero
(as a short) uses 16 bits and the value thirty thousand also uses 16 bits.
1] byte:
byte data type is an 8-bit signed two's complement integer.
Minimum value is -128 (-2^7)
Maximum value is 127 (inclusive)(2^7 -1)
Default value is 0
byte data type is used to save space in large arrays, mainly in place of integers,
since a byte is four times smaller than an int.
Example: byte a = 100 , byte b = -50
2] short:
3] int:
4] long:
5] float:
6] double:
4.4. 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
Logical Operators
Assignment Operators
Misc Operators
Logical operators return a true or false value based on the state of the Variables.
There are six logical, or boolean, operators. They are AND, conditional AND, OR,
conditional OR, exclusive OR, and NOT.
Each argument to a logical operator must be a boolean data type, and the result is
always a boolean data type.
An example program is shown below that demonstrates the different Logical
operators in Java.
Example:
The Conditional operator is the only ternary (operator takes three arguments)
operator in Java. The operator evaluates the first argument and, if true, evaluates the
second argument. If the first argument evaluates to false, then the third argument is
evaluated.
The conditional operator is the expression equivalent of the if-else statement.
An example program is shown below that demonstrates the Ternary operator in Java.
This example demonstrates how conditional operator can be used to find grater of 2
numbers.
Unary Operators
The unary operators require only one operand. They work with single operands.
Example:
count ++; // Existing value in variable count is incremented by 1.
count --; // Existing value in variable count is decremented by 1.
Binary Operators
Binary operators work with two operands or variables.
Example:
int age = 35; // value 35 assigned to variable age.
int x = 5; int y = 3;
int z = x + y; // adding values of two variables and assigning result to another variable.
Ternary Operators
In ternary operator, takes 3 components: condition, true result, false result. This operator is
having a ? and :. It looks like result = condition ? value 1 : value 2
Example:
int a = 10;
int x = a > 0 ? 1: 0; // checking a > 0, if yes returns 1, if no returns 0.
Precedence of Operators
Java has well-defined rules for specifying the order in which the operators in an expression
are evaluated when the expression has several operators. For example, multiplication and
division have a higher precedence than addition and subtraction. Precedence rules can be
overridden by explicit parentheses.
Precedence Order:
When two operators share an operand the operator with the higher precedence goes first.
For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3
since multiplication has a higher precedence than addition.
Associativity:
When two operators with the same precedence the expression is evaluated according to its
associativity. For example x = y = z = 17 is treated as x = (y = (z = 17)), leaving all three
variables with the value 17, since the = operator has right-to-left associativity (and an
assignment statement evaluates to the value on the right hand side). On the other hand, 72 /
2 / 3 is treated as (72 / 2) / 3 since the / operator has left-to-right associativity.
The table below shows all Java operators from highest to lowest precedence, along with
their associativity. 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.
For more information on precedence and associativity you can visit the following link.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
expression are evaluated when the expression has several operators. For
example, multiplication and division have a higher precedence than addition and
Precedence Order:
Associativity:
When two operators with the same precedence the expression is evaluated
= 17)), leaving all three variables with the value 17, since the = operator has
the right hand side). On the other hand, 72 / 2 / 3 is treated as (72 / 2) / 3 since
The table below shows all Java operators from highest to lowest precedence,
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
For more information on precedence and associativity you can visit the following link.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
4.6. String
Strings are an incredibly common type of data in computers. Strings, which are widely used
in Java programming, are a sequence of characters. In the Java programming language,
strings are objects.
Java string is a series of characters gathered together, like the word "Hello", or the phrase
"practice makes perfect". Create a string in the code by writing its chars out between double
quotes.
getting the character at a given position within the string -- charAt() .By using indexOf()
method you get get the position of the sepcified string or char from the given string. You can
also get the index strting from a specified position of the string.
ex:
charAt( int index )
@Returns the char value at the specified index
will result as
Combining charAt() with another String method, we can get the final character of any String,
regardless of length:
will result as
By using indexOf() method you get get the position of the sepcified string or char from
the given string. We can also get the index strting from a specified position of the string.
Output is
Example:
Output:
extracting a substring from a string – substring()
The substring begins with the character at the specified index and extends to the end of
this string or up to endIndex - 1 if second argument is given.
Note:
Example:
Output:
4.7. Practice Problems
1. Write a program to find the difference between sum of the squares and the square of the
sums of 2 numbers?
2. Develop a program that accepts the area of a square and will calculate its perimeter.
3. Utopias tax accountants always use programs that compute income taxes even though
the tax rate is a solid, never-changing 15%. Write a program that calculates net pay of an
employee based on number of hours the employee has worked. Assume an hourly rate of
$12.
4. An old-style movie theater has a simple profit program. Each customer pays $5 per
ticket. Every performance costs the theater $20, plus $.50 per attendee. Develop the
program that accepts the number of attendees (of a show) and calculates how much income
the show earns.
5. Develop the program which computes the height that a rocket reaches in a given
amount of time. If the rocket accelerates at a constant rate g, it reaches a speed of g • t in t
time units and a height of 1/2 * v * t where v is the speed at t.
6. Develop a program that accepts the length and width of a rectangular floor and the edge
length of a square tile and will compute the whole number of tiles needed to cover the floor
completely.
5.Introduction to class in java,access specifiers, this and
static in Java
Objective
Introduction to Classes
Declaration of Classes
Declaration of instance variables
Declaration of methods
Object and Object creation
Access Modifiers
Constructors
Use of this Keyword
Examples for “this” keyword
static keyword
Declaration of Classes
A class is declared by the use of the “class” keyword. Class body is enclosed between
curly braces { and }. The data or variables defined within the class are called instance
variables. The code is contained within methods. Collectively, the methods and variables
defined in a class are called members of the class.
Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable will
be destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any method.
These variables are instantiated when the class is loaded. Instance variables can be
accessed from inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any method,
with the static keyword.
Declaration of Instance Variables
Variables defined within a class are called instance variables because each instance of the
class (ie, each object of the class) contains its own copy of these variables. Thus, the data
for one object is seperate and unique from the data of another. Instance variables can be
declared public or private or default (no modifier). When we do not want our variables value
to be changed outside our class we should declare them private. Public variables can be
accessed and changed from outside the class. We will have more information about this on
OOP tutorial.
Declaration of Methods
A method is a program module that contains a series of statements that carry out a task. To
execute a method, you invoke or call it from another method; the calling method makes a
method call, which invokes the called method. Any class can contain an unlimited number of
methods, and each method can be called an unlimited number of times.
The syntax for method declaration is as given below. Java main method is given as an
example.
5.2. Objects or Instances
Objects need not be physical objects. It can be any entity. It can be account,an
organization etc.
Consider the above start operation for a Car. When the car is started ,it is affecting the
state of the engine.
Creating an Object:
As mentioned previously, a class provides the blueprints for objects. So basically an object is
created from a class. In Java, the new key word is used to create new objects.
We are creating three objects truck, bike and a car from Vehicle class.
Accessing Instance Variables and Methods using Objects:
ObjectReference.variableName;
Java constructors are special methods which are used to initialize objects. Constructor
method has the same name as that of class, they are called or invoked when an object of
class is created and can't be called explicitly. They are designed to perform initializing
actions such as initializing the data fields or objects.
A java constructor has the same name as the name of the class to which it belongs.
Constructor’s syntax does not include a return type, since constructors never return a value.
Constructors can be classified into two types, default constructors and parametrized
constructors.
If you don't define a constructor, then the compiler creates a default constructor. Default
constructors do not contain any parameters. Default constructors are created only if there
are no constructors defined by us. Java provides a default constructor which takes no
arguments, when no explicit constructors are provided. Parametrized constructors are
required to pass parameters on creation of objects.
Access Specifiers
Each object has members (members can be variables or methods) which can be declared to
have specific access.
Access Modifier - private:
Methods, Variables and Constructors that are declared private can only be accessed
within the declared class itself. Private access modifier is the most restrictive access level.
Variables that are declared private can be accessed outside the class if public getter
methods are present in the class. Using the private modifier is the main way that an object
encapsulates itself and hide data from the outside world.
If there is ambiguity between the instance variable and parameter, this keyword resolves the
problem of ambiguity.
Let's understand the problem if we don't use this keyword by the example given below:
In the above example, parameter (formal arguments) and instance variables are same that is
why we are using this keyword to distinguish between local variable and instance variable.
There would only be one copy of each class variable per class, regardless of how many
objects are created from it.Static variables are stored in static memory.
Static variables are created when the program starts and destroyed when the program
stops.
Visibility is similar to instance variables. However, most static variables are declared public
since they must be available for users of the class.
Default values are same as instance variables. For numbers, the default value is 0; for
Booleans, it is false; and for object references, it is null. Values can be assigned during the
declaration or within the constructor.
Static variables can be accessed by calling with the class name . ClassName.VariableName.
Consider the below class Vehicle, here manufacturteName is declared as static and
getManufactureName() method also declared as static.
OUTPUT is:
customerId, accountId,balance
6.1. Packages
A package is a namespace that organizes a set of related classes and interfaces, providing
access protection and name space management. Conceptually packages can be thought of
as similar to different folders on the computer. Packages are used in Java to prevent naming
conflicts, to control access, and to make searching/locating and usage of classes easier.
Java platform provides a very large library of classes and interfaces organized into different
packages known as “Application Programming Interface” or API. Some of the packages in
Java API Library are:
java.io - classes for input, output functions are bundled in this package
Since the package creates a new namespace there won't be any class name conflicts with
other class names in other packages.
Eg: Both java.awt and java.util packages have a class called “List”. There is no naming
conflict because the two “List” classes are part of two different packages.
Using packages, it is easier to provide access control and it is also easier to locate the
related classes.
Eg: Consider a scenario where a bank has many employees. New employees are added,
some may resign from bank, so those employees need to be removed from bank. Many
customers come to the bank to get services. Customers open account, deposit money to
account, withdraw money from account etc.
Here we have different objects and so different classes need to be created. If it is going to be
a large application, it will be difficult to manage all the files without using packages. Also if
we want to set different visibility, like Customer should not see the details of Employee,
packages can be used to organize and set visibility using access modifiers.
The package statement should be the first line in the source file. There can be only one
package statement in each source file, and it applies to all types in the file.
Step1: Create a package in eclipse and provide a name for the package as shown below.
Package name can be a one word name or multiple words separated by a dot.
Eg: com.tcs.employees (or) employee
Step 2: Create classe(s) inside the employee package. The java class file should have
package statement as the first line. In the screenshot below you can see the employee
package. The classes Employee.java and TestEmployee.java are created under this
package. You can see that the first line in Employee.java is the package statement.
6.2. Import Statement
A package is to group related classes or other type of files together. The classes and other
types under a package are called as package members. So as we saw above, we have
grouped all files into different packages.
If a class wants to access/use another class/member from the same package, the class
need not be imported. Classes/members within the same package can access each other
without importing them.
But in the scenario where the classes belonging to different packages need to access each
other, the class belonging to the other package must be imported into the class that wants to
use it.
The classes are imported using import statements. Import keyword is used to import the
classes from different packages. Import keyword is followed by the fully qualified name of the
class which includes the package name under which the class is present.
Eg: import java.util.Date ;
In the example below the Employee class is imported into the TestEmployee class.
You can see in the above example, the TestEmployee class is under the test package. You
can also see the import statement to import Employee in TestEmployee class. This is there
because TestEmployee is using Employee class, which is part of a different package
employee. However even after the Employee class is imported into TestEmployee there are
still errors in Testemployee class. This is because the Employee class is not visible to
classes outside its package. Earlier when the TestEmployee class was inside employee
package, it knew the Employee class. But when it was moved into a different package, and
even after Employee class was imported the Employee class and its constructor are not
visible. This is because only public members of a package/class are visible to classes from
other packages. So specify public access specifier to the class, constructor and method
which need to be accessed from outside.
In the below screen, you can see the changes made to access specifiers of Employee class
and its constructor and methods. They are all declared with public access modifier.
To use a public package member from outside its package any one of the following can be
used
a) Refer to the class/member by its fully qualified name
b) Import specific class/member in a package
c) Import all members/classes in a package
If a class in a package has same name as another class in another package and both
packages are imported then you must refer to each class by its qualified name to resolve
any name ambiguities.
Variables that are declared private can be accessed outside the class if public getter
methods are present in the class. Using the private modifier is the main way that an object
encapsulates itself and hide data from the outside world.
A variable or method declared without any access control modifier is available to any other
class in the same package. Such members can be considered as package private.
We have already seen such a scenario when we discussed about import statements.
Eg: The constructor method in the following Java class is in default access.
class Employee {
// Constructor
Employee(String name, String empNo, int age) {
this.name = name;
this.empNo = empNo;
this.age = age;
}
}
Protected Access Modifier – protected
Protected is related to inheritance (a parent child relation). Protected members in a class can
be accessed only by its child classes from same/different package as well as by any other
classes in the same package.
The child class can be anywhere, in other package or within the same package of the parent
class.
The protected access modifier can be applied only to methods or fields, not to class. We can
see more on it when we go through inheritance.
Java Libraries
Java differs from most other languages in that the number of classes and interfaces in its
standard libraries is very large. Many common tasks have already been implemented by
these libraries.
They are generally of high quality and are widely used. Implementing something which
already exists in the libraries is probably wasted effort. Significant changes and additions to
the standard libraries occur in each major release of Java, and it pays to keep current.
The most widely used packages are java.lang and java.util. There are other packages used
for working with data such as java.sql, javax.sql, java.io etc.
For graphical applications, see the Swing classes (javax.swing, and so on).
You should go through JDK documentation just to get an idea of what is available. Later,
when a specific need arises, you will often know which packages might be helpful.
7.Conditional operations
Objective
1. if – This statement is the most basic of all control flow statements. “if” statement has a
certain condition expression. It executes a certain section of code only if that particular
condition is true. If the condition is false, control jumps to the end of the if statement.
if(condition)
{
/* statement(s) will execute if the condition is true.
For example, a=5
Checking condition -
if(a>3)
{
This code will be executed because 'a' is greater than 5.
}
*/
}
2. If ... else – This statement provides a secondary path of execution when the condition
becomes false. There can be nested if then else statement also.
if(condition)
{
/* statement(s) will execute if the condition is true.*/
}
else
{
/* statement(s) will execute if the boolean condition is
false */
}
In the above example, if a=5 and condition is to check if a>6 then it will go to else block.
Flow Diagram:
3. switch – A switch statement allows a variable to be tested for equality against a list of
values. Each value is called a case, and the variable being given as input is checked for
each case.
This statement helps to select one out of the many choices based on an integer or String
value. The conditions will accept only integer, character or String. The syntax is different
from if else statements. Here we are comparing the input value with different cases. We can
set a default case for inputs which does not satisfy any case.
The syntax of the switch statement is as follows.
switch (expression) {
case value_1 :
statement(s);
break;
case value_2 :
statement(s);
break;
.
.
.
case value_n :
statement(s);
break;
default:
statement(s);
}
Failure to add a break statement after a case will not generate a compile error but may have
more serious consequences because the statements on the next case will be executed.
1. The variable used in a switch statement can only be a byte, short, int, char or String(It is
allowed from jdk 1.7 version.).
2. You can have any number of case statements within a switch. Each case is followed by
the value to be compared to and a colon.
3. The value for a case must be the same data type as the variable in the switch and it must
be a constant or a literal.
4. When the variable is found equal to a case, the statements following that case will
execute until a break statement is reached. When a break statement is reached, the switch
terminates, and the flow of control jumps to the next line following the switch statement. Not
every case needs to contain a break. If no break appears, the flow of control will fall through
to subsequent cases until a break is reached.
A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
No break is needed in the default case.
The "?:" operator evaluates an expression which may also be an operand and returns
operand1 if the expression is true; otherwise returns operand2, if the expression is false. We
can understand this thing with the help of a diagram shown as:
If we analyze this diagram then we find that, operand1 is returned, if the expression is true;
otherwise operand2 is returned in case of false expression.
Lets have an example implementing some Logical operators:
Thus we can conclude the ternary operator can be considered as the short hand of if then
else statement.
Conditional operators return a true or a false value based on the state of the variables i.e.
the operations using conditional operators are performed between the two boolean
expressions.
If we analyze the table we find that result is always true only in case of first condition where
both operands(or expressions) are true. On the other hand result is always false in other
conditions. Note that this table works alike for & and && operators.
In case of "&" operator,if both operands or expressions are true,the result is always true,
otherwise it is false if either left-hand or right-hand operand is false.
In case of "&&" operator, the result is also true, if both operands or expressions are true.
But this operator evaluates only the left-hand operand. It doesn't evaluate the right-hand
operand if the left-hand operand is false then it will not jump to the right-hand operand to
evaluate it, and will come out from that statement and read the next statement. That's why
this mechanism is known as short-circuiting. Consider the following statements where the
second expression returns false after evaluating only the left-hand operand.
But the "&" operator always evaluates both of its operands whether the first operand is true
or false. Consider the following statements where the second expression returns false after
evaluating the right-hand operand.
Likewise, the OR operator(|) is similar to the Conditional-OR operator (||) and returns true, if
one or another of its operand is true.
Lets use a Truth Table to know the status of an output that works alike for"|" and "||"
operators.
If we analyze the table then we find that, result is always false only if both operands or
expression are false. On the other hand, result is always true in rest of the other conditions.
Still these exists a major difference in their mode of use:
The "|" operator always evaluates both of its operands and returns true if one or other of its
operand is true. Otherwise false if both the conditions are false. Consider the following
statements where the second expression returns false after evaluating the right-hand
operand.
In case of "||" the result is also true, if one of the both operands is true. Otherwise it
evaluates to falseif both operands are false. But this operator conditionally evaluates the
right-hand operand only if the left-hand operands is false. Like the Conditional-AND
operator, this mechanism is also known as short-circuiting. Consider the following
statements where the first expression returns true after evaluating the right-hand operand.
8.1. Arrays
We have seen how to declare variable in the previous section. int x; Here x is a variable of
type int, so x will be capable of storing an integer value. At any point of time a variable can
hold only a single value.
int age=20;
int score=70;
Say, I need to store scores of last 5 matches. What kind of data type do I take? May be
I will take 5 variables of type int.
int scoreMatch1;
int scoreMatch2;
int scoreMatch3;
int scoreMatch4;
int scoreMatch5;
Similarly, I need to record no. of kms I drove each day in last 5 days.
int kmsDay1;
int kmsDay2;
int kmsDay3;
int kmsDay4;
int kmsDay5;
Similarly, I need to record the amount spent for each day in last 5 days.
double expenseDay1;
double expenseDay2;
double expenseDay3;
double expenseDay4;
double expenseDay5;
The above approach will not be efficient if the requirement(of recording data for a
specific period) changes from just last 5 days to last 30 days.
Array:
It is a single variable, capable of storing multiple values (of same data type). But an
array does not store the multiple values directly. It is a collection of more than one variable,
of same data type.
Declaring arrays:
The general syntax to declare an array is : data type variable name[]; The square
brackets indicate that the variable is an array of the data type declared.
Example:
Also, all the above arrays are just declared, and have not yet been initialized(not
defined the size).
Here scores is not just an int type variable. scores is an array of type int i.e. It is
capable of storing more than one int value.
int score = 70; Here the variable score holds a value 70.
Arrays
Here the array scores do not hold the values directly. It is just a reference (pointing to) to
the 5 variables score1 … score5. Hence arrays are called references or objects in Java.
If we do not initialize an int variable, its default value is 0. In case of array (as it does
not store value directly), if we do not initialize(do not say to which list of variables it refers to)
it, the default value is null. i.e. it does not point to any list of variables.
Similarly, expenses is not just a double type variable. expenses is an array of type
double i.e. it is capable of storing more than one double value.
Similarly, grades is not just a char type variable. grades is an array of type char i.e. it is
capable of storing more than one char value.
Once an array is declared, you can think of multiple variables being generated automatically
in a sequential order i.e. if an array double[] expense is declared, the variable that stores the
first value will be expense[0], the variable that stores the second value will be expense[1]
and so on.
Note: While talking about arrays, always remember two key things. One, about the array
itself, whether it is initialized or not. Two, about the element inside the array – whether it is
initialized or not.
Arrays have a specific length(or size). The length of the array cannot be changed after
it has been initialized. The elements in the array are put at index of the array. The first
element in the array is at index 0, and the last element is at the index length-1.
To declare and initialize an array at the same time, refer to the below syntax:
Example 1:
The above statement declares an array, initializes an array (of size 5) and also puts
elements into the array. The value of first element is 55, the value of second element is 15,
the value of third element is 92, the value of fourth element is 107 and the value of fifth
element is 67.
Once the array is initialized, the length(or size) of an array can be known by the length
property. It is used after the dot operator on the array variable. Refer the syntax below:
array.length;
eg.
int scores[] = new int[]{55,15, 92,107,67};
System.out.println(scores.length);
You could either store it in an int variable eg. int size = scores.length;
Step 1:
int scores[] = new int[5];
The above statement will declare an int array of length 5. The values in the array will be
initialized to the default values as per their data type.
Step 2:
The first value in the array is accessed by the code : scores[0]. To assign values to the
first element, use the assignment operator (=). The below statement assigns a value 55 to
the first element in the array. The remaining elements still have the default value.
scores[0] = 55;
Assuming that the above array is initialized with the given values. The elements of the array
are accessed by their index. The first element of the array is stored at index 0 and the last
element is stored at index which is length-1.
To retrieve the value of the elements at index 0, use scores[0] which will return the value 55.
Similarly,
We can use a variable to store the value we retrieve from the array,
int x = scores[0]; as scores is an int array, scores[0] is going to return an int.
Consider the case of library where it has list of books as inventory. So library will have
attributes like library name, address. It will also have list of books as an attribute. We could
model the Book class and Library class as follow.
The library class has an array of Book, i.e. the array will have multiple objects of Book
representing the real books in the library.
Book[] listOfBooks;
The above statement just declares the array variable. It is not initialized so the
listOfBooks is still null. Let us initialize the array.
listOfBooks = new Book[3];
The above statement just initialized the array itself, the elements have not yet been
initialized. Let us initialize the elements of the array by assigning the book object value.
listOfBooks[0] = b1;
listOfBooks[1] = b2;
listOfBooks[2] = b3;
The above 3 statement, initializes all the 3 elements to the value of objects b1, b2 and b3
respectively.
We can use a variable to store the value we retrieve from the array.
One of the things computers are often used for is the automation of repetitive tasks.
Repeating identical or similar tasks without making errors is something that computers do
well and humans do poorly. In this chapter, we shall study in detail how the repeated tasks
can be automated using Java programming.
Program:
Output:
12345678910
In the above program, we wrote the same line of code 10 times to obtain output. This is
nothing but code redundancy(repetition) which makes our program an inefficient one. To
eliminate this we use loops and iterations in Java.
Loop is a block of code executed repeatedly until some condition is satisfied and one
pass through(execution of) the loop is called iteration.
Here condition is a boolean expression. A boolean expression is an expression written
using conditional operators(<, >, ==, <=,>= etc) and the result of it will always be either true
or false.
1. 'while' loop
2. 'do while' loop
3. 'for' loop
While loop:
A while loop is a control structure that allows you to repeat a task certain number of
times. In simple words, using while loop we can execute a set of statements several times
based on a condition.
Syntax:
while(condition)
{
//Statements
}
Here, “while” is a keyword and “condition” is a boolean expression and as long as this
condition yields true, the statements within the braces({}) are executed. You can almost read
a while statement as if it were English- “while condition is true, continue executing the
Statements”.
Let us now write the same program(print first 10 natural numbers) using while loop.
Program:
Output:
12345678910
In the above code snippet, we eliminated those 9 repeated lines, clubbed them into a
single line and obtained the output using while. Here n is also called counter variable and it
is used to iterate through the loop.
Example:
/*Program to automate the grade generation of five students based on their percentage
using while loop */
Output:
Roll no 1: Grade is B
Roll no 2: Grade is B
Roll no 3: Grade is C
Roll no 4: Grade is A
Roll no 5: Grade is A
Flow of the above program:
1. Initialize an integer array of percentage.
2. Initialize an integer variable rollNo=0; which is used to iterate through the array.
3. Since we need to generate grades for only those students whose percentage is given, we
are specifying the condition in while as rollNo<percentage.length. We have learned in the
previous topic that .length property gives the size of array which is 4 in the above program.
rollNo points to the index of the array. So before entering while loop, the value of rollNo is
checked.
4. If the condition is satisfied(if rollNo<percentage.length) go to step 5 else go to step 6.
5. Now control is sent to the body of loop
• In the body of while loop, if-else conditions are specified to check the percentage of
student marks. Based on those conditions respective grade is printed.
• Increment rollNo.
• Go to Step 4.
6. End.
Syntax:
do
{
//statements
}while(condition);
Here, “while” and “do” are keywords and “condition” is a boolean expression. Each
iteration of the do-while loop first executes the statements and then evaluates the condition.
If the result of this condition is true, the loop will repeat. Otherwise, the loop
terminates. Notice, there is semicolon at the end of while(); in do... while loop.
Let us now write the same program(print first 10 natural numbers) using do... while loop.
Program:
Now you may get a question as why “do.. while” when we already have “while” and when
both are giving the same output? We shall study about it in detail.
Fortunately, Java supplies a loop that does just that: the do-while. The do-while loop
always executes its body at least once, because its condition is at the bottom of the loop.
Therefore, while is called entry-called loop whereas do...while is called exit-controlled loop.
The difference is best illustrated using the programs below:
Do-while example:
Output:
do-while: 11
While example:
Output:(no output)
Example:
/*Program to generate the grade for five students of a class based on their percentage using
do... while loop */
Output:
Roll no 1: Grade is B
Roll no 2: Grade is B
Roll no 3: Grade is C
Roll no 4: Grade is A
Roll no 5: Grade is A
For loop:
A for loop is a repetition control structure that allows you to efficiently write a loop that
needs to execute a specific number of times. A for loop is useful when you know how many
times a task is to be repeated.
Syntax:
Here,the initialization step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. Next, the condition is evaluated. If it is true,
the statements are executed, else control comes out of for loop and the next statement after
the loop is executed.
Program:
Output:
12345678910
4. If the result is true, execute the set of statements within the curly braces, and then go to
increment/decrement statement.
5. Go to step 2.
Example:
/*Program to generate the grades for five students based on their percentage using for loop
*/
Output:
Roll no 1: Grade is B
Roll no 2: Grade is B
Roll no 3: Grade is C
Roll no 4: Grade is A
Roll no 5: Grade is A
This is an enhanced for loop which mainly used for arrays. Advanced for loop is also
called 'for each' loop.
Syntax:
for(declaration : expression)
{
//Statements
}
Declaration: The newly declared block variable, which is of a type compatible with the
elements of the array you are accessing. The variable will be available within the for block
and its value would be the same as the current array element.
Expression: This evaluates to the array you need to loop through. The expression can be
an array variable or method call that returns an array.
Let us take the same example of grade generation and see how it works in advanced for
loop.
Example:
/*Program to generate the grades of 5 students based on their percentage using advanced
for loop */
Output:
Percentage is 50: Grade is B
Percentage is 46: Grade is B
Percentage is 32: Grade is C
Percentage is 98: Grade is A
Percentage is 75: Grade is A
In the above program, eachPercentage is a variable that is of the same data type as
array of percentage. In the previous program rollNo takes the index value whereas here
eachPercentage takes value at index. Therefore, initially the value of eachPercentage is
percentage[0] which is 50 and in the second iteration eachPercentage will take the value
percentage[1] which is 46 and so on.
Nested loops:
We have seen the advantages of using various methods of iteration, or looping. Now
let's take a look at what happens when we combine looping procedures. The placing of one
loop inside the body of another loop is called nesting.
When you "nest" two loops, the outer loop takes control of the number of complete
repetitions of the inner loop. While all types of loops may be nested, the most commonly
nested loops are for loops.
Output:
12
123
1234
12345
In the above program, outer loop is used to determine the no.of digits to be
printed in a line whereas the inner loop is used to print the digits. We have used print() within
the body of inner loop because we want the digits to be displayed in the same line and after
the inner loop is executed, we go to the next line using println() statement.
Output:
Tata Consultancy Services
Tata Consultancy Services
Tata Consultancy Services
.
.
.
.
This goes on printing until we forcefully stop the execution. The above program is an
example of implementing infinite loop using for loop. Similarly, you can implement an infinite
loop using while and do... while as follows.
do{
} while(true);
Syntax:
break;
Program:
Output:
x is 1
x is 2
Break the loop
Exit
In the above example if the value of x is 3 then the control enters into the loop and
when break statement is encountered, it comes out of the for loop and executes the first
statement after the for loop. The break statement can be used in terminating all three loops
for, while and do...while.
The continue keyword can be used in any of the loop control structures. Continue
statement skips the current iteration of a for, while or do while loop. It causes the loop to
immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes flow of control to immediately jump to the
increment/decrement statement.
In a while loop or do/while loop, flow of control immediately jumps to the condition.
Syntax:
continue;
In the above example if the value of x is 3 then the control enters into the loop and
when continue statement is encountered, it jumps to the next iteration without executing the
rest of the statements within the loop.