Chapter 1 Problem Solving Part 1 Basics
Chapter 1 Problem Solving Part 1 Basics
Figure 1
Figure 2
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 you use a pad of paper for.
Figure 3
Windows Notepad
Notepad is a basic text editor that you can use to create simple documents.
Figure 4
Facebook Application
A social utility that connects people with friends and others who work, study and live around
them.
Figure 6
IRCTC Portal
Online Passenger Reservation System provides booking facility of Railway tickets online.
Figure 7
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.
Figure 8
Figure 9
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 possibilities. Here are a few examples of mobile applications:
Figure 10
Figure 11
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.
Figure 13
Presentation Layer / User Interface layer - 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 it easier to create a design that supports re-
usability of components.
Benefits of layers:
Simplicity: easy to design once layers and their interaction are defined clearly
Tier – When the logical groups of components are physically separated in different machines, it
is known as Tier. The communication between the different tiers of an application is through
network.
Single/One Tier Architecture – All layers (Presentation, Business and Resource) are at same
place. The application doesnot require network connection to work. It is easy to install in a
system and use it.
Figure 15
Presentation Layer in one machine and Business & Resource Layer is available in
different machine
Presentation & Business layer in one machine and Resource layer in another machine.
Figure 16
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.
Figure 17
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 distributed in three different machines.
The Presentation layer is at the client tier and from there request is sent to the Business layer
and after processing the request its again sent to Storage/Resource tier for storing.
Figure 18
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.
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 depend purely on the application.
Delete – There should be a way to remove the data created. Again like Update, who can perform
delete operation will vary depending on the application.
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 is one of the example for CREATE operation.
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. Old information gets overwritten by the new information in
the database.
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 the account. This is also an example of the delete operation.
Now a day most of the websites do not provide direct deletion, they allow you to just deactivate
the account. Few websites even have facility to delete the account.
Delete is basically, deleting the information from the database of the website or making the
information inaccessible.
1.2. Introduction to Problem Solving Approach
Most people spend most of their time, at work or at home, solving problems. Most problems we
face are small, some are large and complex, but they all need to be solved in a satisfactory way.
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.
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.
2. Identifying possible solutions and Making Decisions (Design the best possible solution)
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.
Once the solution is designed, before implementation, we need to confirm if the solution meets the
requirement. Hence we should go for dry run with some input data and analyse each step of the
designed solution based on that data. Finally, we need to check the output of the solution which
should meet the requirements. Dry run is basically walk- through in mind for every step of the
designed solution.
4. 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.
The outcome of our implementation needs to be tested before it is actually deployed. Similarly, all
code needs to be thoroughly tested to make sure that bugs are not present in it. If any bugs are
identified, they need to be removed and the system needs to be checked again for consistency.
Hence testing is a very important phase of problem solving.
The developed and tested outcome is finally given to the customer. The deployment phase makes
sure that the software that has been developed works fine in the customer's environment as per the
customer’s requirements. Maintenance phase deals with the periodic updates that might be
required for the application.
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
i) Declarative knowledge is factual knowledge or the knowledge of the solution. For example
knowing that "A pen is used for writing" is a declarative knowledge. Declarative knowledge is
knowledge or the possession of information that is either true or false. It describes objects and
events by specifying the properties which characterize them; it does not pay attention to the actions
needed to obtain a result
Continuing with the above example, although we know the result, we also need to know how to
reach the result. This 'how-to' knowledge is called as imperative knowledge. Let us consider the
steps
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
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.
Eg: English as a language has got a certain syntax. We have predefined syllables and words like 'a' or
'cup' or 'welcome'. These words convey a meaning to the language.
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.
Eg: Continuing the same example, English language has got a certain semantics. 'An elephant is
white and has got two legs' is syntactically , grammatically correct. But it doesn’t make any sense.
Hence it is semantically wrong.
Superior coding techniques and programming practices are hallmarks of a professional programmer.
The coding techniques are primarily those that improve the readability and maintainability of
code,whereas the programming practices are mostly performance enhancements.
ii) Readability
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
Poor readability
Non-maintainable
Reduced reusability
Elements of 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).
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.).
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.
Characteristics of an object
The five characteristics of an Object are explained below:
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:
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
Communication between Objects: In a typical problem scenario, several objects communicate
with each other to perform operations, send messages and return data.
Example: Employee object has a salary account in a bank. So both objects communicate with
each other to perform all bank related transactions of the employee.
Identity of Objects: Identity of objects as explained earlier relates to the distinctness of the
object. We identify the objects in a problem scenario based on all nouns of the project. The
behaviours are identified using the verbs operated upon by the nouns
To enable understand the characteristics of an object, let us consider the following example
Answers:
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).
Computer Memory.
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.
Classes are generic representations of Objects in problem scenarios. They help in generalization
of the object as a template. Each object becomes an instance or photocopy of this template.
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.,.
1. Functional/procedural programming:
Program is a list of instructions to the computer
2. Object-oriented programming:
Program is composed of a collection objects that communicate with each other
Sun Microsystems was acquired by the Oracle Corporation in 2010. Now oracle is owning Java.
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. Java
manages the memory automatically by using an automatic garbage collector. all the above
features makes Java language robust.
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:
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".
Step 2: Compile the Source Code: Compile the source code "Hello.java" into portable bytecode
"HelloWorld.class" using JDK compiler "javac". Start a CMD Shell (Windows) or Terminal
(UNIX/Linux/Mac) and issue this command:
before run java file you should set the path and classpath
See the below screen shots in order to run any java program in command prompt mode
Summary:
History of Java
Java is released in 1995 as a core component of Sun Micro system's Java platform. In year 1991
they make a platform independent software called it Oak. and in early 1995 Java 1.0 is officially
released. This is the first version of Java as JDK1.0. After the first version, many classes,
packages are added in Java in future and new version's are released .
Diamond Syntax
Java Platform
Base Libraries
Integration Libraries
Java Deployment
Tool Specifications
Platforms
A Java virtual machine (JVM), an implementation of the Java Virtual Machine Specification,
interprets compiled Java binary code (called bytecode) for a computer's processor(or "hardware
platform") so that it can perform a Java program's instructions. Java was designed to allow
application programs to be built that could be run on any platform without having to be rewritten
or recompiled by the programmer for each separate platform. A Java virtual machine makes this
possible because it is aware of the specific instruction lengths and other particularities of the
platform.
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.
Runtime Instance Whenever you write java command on the command prompt to run the java
class, and instance of JVM is created.
Loads code
Verifies code
Executes code
The below diagram will explain in details how JVM converts java file into class and byte code.
JVM Architecture:
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.
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 installation and environment variable setup steps are clearly described in chapter 3b.
Follow the instructions given in that chapter 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.
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.
Steps to run a java program is described in chapter 3b. 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.
Oracle.com hosts the latest JDK installer and also the archives of older versions of JDK installer.
The latest installer could be downloaded from the link:
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.
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.
Click on OK to save changes.
Example:
Create a folder javaproject in your D: drive. Create a file MyFirstJavaProgram.java with following
contents.
Compile the file MyFirstJavaProgram.java with the help of the compiler – javac. The sytanx to
compile a file with java extension is – javac FileName.java
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 url http://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.
2.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.
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.
Right click anywhere in the Project Explorer area. Select New → Project.
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.
5. Create Java Class
Reconfirm the location where you want the class to be created – its is in the src folder.
Enter the package name – tcs.ilp
Enter the class name - MyFirstJavaProgram
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.
Compileonline:
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.
This application also helps us to execute multiple class files let us also see a small demo on how
to execute multiple class files using compile online.
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
Step 4: Click Compile & Execute.
A variable is a container that holds values that are used in a Java program.
All variables should be declared before they are used in the program.
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.
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
• They are visible only within the declared method, constructor or block.
• There is no default value for local variables. So local variables should be declared and an
initialized before its first use.
Example:
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.
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
That means, if a static method need to access a non-static variable or method, then first create
an object and using that object you need to access the method or variable.
This is because; static members which are related directly to class cannot see instance variable
state and behaviour.
Numbers are so important in Java that 6 of the 8 primitive data types are numeric types which
are shown in tabular format below.
There are both integer and floating point primitive types. Integer types have no fractional part
whereas floating point types have a fractional part.
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:
• short data type is a 16-bit signed two's complement integer.
• Minimum value is -32,768 (-2^15)
• Maximum value is 32,767 (inclusive) (2^15 -1)
• short data type can also be used to save memory as byte data type. A short is 2 times smaller
than an int.
• Default value is 0.
• Example: short s = 10000, short r = -20000
3] int:
• int data type is a 32-bit signed two's complement integer.
• Minimum value is - 2,147,483,648.(-2^31)
• Maximum value is 2,147,483,647(inclusive).(2^31 -1)
• int is generally used as the default data type for integral values unless there is a concern about
memory.
• The default value is 0.
• Example: int a = 100000, int b = -200000
4] long:
• long data type is a 64 bit signed two's complement integer.
• Minimum value is -9,223,372,036,854,775,808.(-2^63)
• Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
• This type is used when a wider range than int is needed.
• Default value is 0L.
• Example: long a = 100000L, int b = -200000L
5] float:
• float data type is a single-precision 32-bit IEEE 754 floating point.
• float is mainly used to save memory in large arrays of floating point numbers.
• Default value is 0.0
• float data type is never used for precise values such as currency.
• Example: float f1 = 234.5f
6] double:
• double data type is a double-precision 64-bit IEEE 754 floating point.
• This data type is generally used as the default data type for decimal values, generally the
default choice.
• double data type should never be used for precise values such as currency.
• Default value is 0.0d.
• Example: double d1 = 123.4
The result has fractional value, so we are using float variable to store it.
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
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
1. Logical operators return a true or false value based on the state of the Variables.
2. There are six logical, or boolean, operators. They are AND, conditional AND, OR, conditional
OR, exclusive OR, and NOT.
3. Each argument to a logical operator must be a boolean data type, and the result is always a
boolean data type.
4. An example program is shown below that demonstrates the different Logical operators in Java.
Example:
In this example you can see the use of logical operators.
4] The Assignment Operator:
The variable are always on the left-hand side of the assignment operator and the value
to be assigned is always on the right-hand side of the assignment operator.
i = i + 2; // same as i=10+2
Here we say that we are assigning i's value to the new value which is i+2.
A short cut way to write assignments like this is to use the += operator. It's one operator
symbol so don't put blanks between the + and =. So it is also called as short hand
operator.
i += 2; // Same as "i = i + 2
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.
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.
Since it is static method we can access it without creating object of that class, directly with the
classname.
Points to remember
This is because; static members which are related directly to class cannot see instance variable
state and behaviour.
Numbers are so important in Java that 6 of the 8 primitive data types are numeric types which
are shown in tabular format below.
There are both integer and floating point primitive types. Integer types have no fractional part
whereas floating point types have a fractional part.
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:
• short data type is a 16-bit signed two's complement integer.
• Minimum value is -32,768 (-2^15)
• Maximum value is 32,767 (inclusive) (2^15 -1)
• short data type can also be used to save memory as byte data type. A short is 2 times smaller
than an int.
• Default value is 0.
• Example: short s = 10000, short r = -20000
3] int:
• int data type is a 32-bit signed two's complement integer.
• Minimum value is - 2,147,483,648.(-2^31)
• Maximum value is 2,147,483,647(inclusive).(2^31 -1)
• int is generally used as the default data type for integral values unless there is a concern about
memory.
• The default value is 0.
• Example: int a = 100000, int b = -200000
4] long:
• long data type is a 64 bit signed two's complement integer.
• Minimum value is -9,223,372,036,854,775,808.(-2^63)
• Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
• This type is used when a wider range than int is needed.
• Default value is 0L.
• Example: long a = 100000L, int b = -200000L
5] float:
• float data type is a single-precision 32-bit IEEE 754 floating point.
• float is mainly used to save memory in large arrays of floating point numbers.
• Default value is 0.0
• float data type is never used for precise values such as currency.
• Example: float f1 = 234.5f
6] double:
• double data type is a double-precision 64-bit IEEE 754 floating point.
• This data type is generally used as the default data type for decimal values, generally the
default choice.
• double data type should never be used for precise values such as currency.
• Default value is 0.0d.
• Example: double d1 = 123.4
The result has fractional value, so we are using float variable to store it.
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
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists the arithmetic operators:
1. Logical operators return a true or false value based on the state of the Variables.
2. There are six logical, or boolean, operators. They are AND, conditional AND, OR, conditional
OR, exclusive OR, and NOT.
3. Each argument to a logical operator must be a boolean data type, and the result is always a
boolean data type.
4. An example program is shown below that demonstrates the different Logical operators in Java.
Example:
In this example you can see the use of logical operators.
4] The Assignment Operator:
The variable are always on the left-hand side of the assignment operator and the value
to be assigned is always on the right-hand side of the assignment operator.
i = i + 2; // same as i=10+2
Here we say that we are assigning i's value to the new value which is i+2.
A short cut way to write assignments like this is to use the += operator. It's one operator
symbol so don't put blanks between the + and =. So it is also called as short hand
operator.
i += 2; // Same as "i = i + 2
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.
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
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.
Methods:
Result:
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 )
will result as
Combining charAt() with another String method, we can get the final character of any
String, regardless of length:
will result as
seeing if a character or string exists within a string -- indexOf()
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:
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.
Example: