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

Unit 1

Uploaded by

Bavithra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit 1

Uploaded by

Bavithra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

UNIT I

INTRODUCTION TO OOP AND JAVA

Overview of OOP – Object oriented programming paradigms – Features of Object Oriented


Programming – Java Buzzwords – Overview of Java – Data Types, Variables and Arrays – Operators –
Control Statements – Programming Structures in Java – Defining classes in Java – Constructors-Methods -
Access specifiers - Static members- JavaDoc comments.

1.1 Overview of OOP

OOP (Object-oriented programming) is a programming paradigm based on the concept of "objects",


which can contain data and code: data in the form of fields (often known as attributes or properties), and
code, in the form of procedures (often known as methods). It is a programming language model organized
around objects rather than actions and data. An object - oriented program can be characterized as data
controlling access to code.

The structure, or building blocks, of object-oriented programming include the following:

• Classes are user-defined data types that act as the blueprint for individual objects, attributes and
methods.
• Objects are instances of a class created with specifically defined data. Objects can correspond to
real-world objects or an abstract entity. When class is defined initially, the description is the only
object that is defined.
• Methods are functions that are defined inside a class that describe the behaviors of an object.
• Attributes are defined in the class template and represent the state of an object. Objects will have
data stored in the attributes field. Class attributes belong to the class itself.

Object-oriented programming concepts

1.2 Object oriented programming paradigms


Object-oriented programming (OOP) is a programming paradigm based upon objects (having
both data and methods) that aims to incorporate the advantages of modularity and reusability.
Objects, which are usually instances of classes, are used to interact with one another to design applications
and computer programs.

Two Paradigms

All computer programs consist of two elements: code and data. Furthermore, a program can be conceptually
organized around its code or around its data. That is, some programs are written around ―what is
happening and others are written around ―who is being affected. These are the two paradigms that govern
how a program is constructed.

• process-oriented model
• object-oriented model

Process-oriented model:

This approach characterizes a program as a series of linear steps (that is, code). The process-oriented
model can be thought of as code acting on data. Procedural languages such as C employ this model to
considerable success. However, problems with this approach appear as programs grow larger and more
complex.

Object-oriented model:

Object-oriented programming organizes a program around its data (that is, objects) and a set of well-
defined interfaces to that data. An object-oriented program can be characterized as data controlling access to
code. By switching the controlling entity to data, you can achieve several organizational benefits.

Difference between Procedure-Oriented and Object-Oriented Programming

Sl.No Procedure-Oriented Programming Object-Oriented Programming


1. In POP, program is divided into small In OOP, program is divided into parts
parts called objects.

called functions
2. In POP, Importance is not given to data In OOP, Importance is given to the data
but to functions as well as sequence of rather than procedures or functions
actions to be done. because it works as a real world.
3. POP follows Top Down approach. OOP follows Bottom Up approach.

4. POP does not have any access specifier. OOP has access specifiers named Public,
Private, Protected, etc.
5. In POP, Data can move freely from In OOP, objects can move and
function to function in the system. communicate with each other through
member functions.
6. To add new data and function in POP is OOP provides an easy way to add new
not so easy. data and function.
7. In POP, Most function uses Global data In OOP, data cannot move easily from
for sharing that can be accessed freely function to function, it can be kept public
from function to function in the system. or private so we can control the access of
data.
8. POP does not have any proper way for OOP provides Data Hiding so provides
hiding data so it is less secure. more security.
9. In POP, Overloading is not possible. In OOP, overloading is possible in the
form of Function Overloading and
Operator Overloading.
10. Example of POP are : C, VB, FORTRAN, Example of OOP is: C++, JAVA,
Pascal. VB.NET, C#.NET.

1.3 Features of Object Oriented Programming

Object - Oriented Programming(OOP) is a programming language model organized around objects


rather than actions and data. An object - oriented program can be characterized as data controlling access to
code.

Concepts of OOPS

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
• Dynamic Binding
• Message Communication

1.3.1 Object

Object means a real word entity such as pen, chair, table etc. Any entity that has state and behavior is
known as an object. Object can be defined as an instance of a class. An object contains an address and takes
up some space in memory. Objects can communicate without knowing details of each other's data or code,
the only necessary thing is that the type of message accepted and type of response returned by the objects.
An object has three characteristics:

• State: represents data (value) of an object.


• Behavior: represents the behavior (functionality) of an object such as deposit, withdraw etc.
• Identity: Object identity is typically implemented via a unique ID. The value of the ID is not visible
to the external user.

1.3.2 Class

Collection of objects is called class. It is a logical entity. Classes are user-defined data types and
behave like the built-in types of a programming language. A class defines the structure and behavior (data
and code) that will be shared by a set of objects. Each object of a given class contains the structure and
behavior defined by the class.

A class consists of data members and methods. The primary purpose of a class is to hold
data/information. The member functions determine the behavior of the class, i.e. provide a definition for
supporting various operations on data held in the form of an object. Class doesn‘t store any space.

The General Form of a Class:

A class is declared by use of the class keyword.

class classname
{
type instance-variable1;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
// ...
type methodname1(parameter-list)
{
// body of method
}
}

When you create a class, you will specify the code and data that constitute that class. Collectively, these
elements are called members of the class. Specifically, the data defined by the class are referred to as
member variables or instance variables. The code that operates on that data is referred to as member
methods or just methods.

Syntax to create an object:

classname objectname=new classname();


For example, the syntax used to create an object is no different than the syntax used to create an integer
object in C. If fruit has been defined as a class, then the statement

Fruit mango=new Fruit();

will create an object mango belonging to the class Fruit.

public class Dog


{
String breed;
int age;
String color;
void barking()
{}
void hungry()
{}
void sleeping()
{}
}

1.3.3 Data Abstraction and Encapsulation

The wrapping up of data and methods into a single unit (called class) is known as encapsulation.
Data encapsulation is the most striking feature of a class. The data is not accessible to the outside world and
only those methods, which are wrapped in the class, can access it. These methods provide the interface
between the object's data and the program. This insulation of the data from direct access by the program is
called data hiding. Encapsulation makes it possible for objects to be treated like 'black boxes', each
performing a specific task without any concern for internal implementation.

Abstraction refers to the act of representing essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract attributes
such as size, weight and cost, and methods that operate on these attributes. They encapsulate all the
essential properties of the objects that are to be created.

1.3.4 Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of another
class. When one object acquires all the properties and behaviours of another object, it is known as
inheritance. Inheritance supports the concept of hierarchical classification.

A class which inherits the properties is known as Child class(sub-class or derived class) whereas a
class whose properties are inherited is known as Parent class(super class or base class). It provides code
reusability and establishes relationships between different classes. For example, the bird robin is a part of
the class fiying bird, which is again a part of the class bird.

Types of inheritance in java: single, multilevel and hierarchical inheritance. Multiple and hybrid
inheritance is supported through interface only.

1.3.5 Polymorphism

Polymorphism plays an important role in allowing objects having different internal structures to
share the same external interface. This means that a general class of operations may be accessed in the same
manner even though specific actions associated with each operation may differ. Polymorphism is
extensively used in implementing inheritance.
Polymorphism is classified into two ways:

• Method Overloading(Compile time Polymorphism)

Method Overloading is a feature that allows a class to have two or more methods having the same
name but the arguments passed to the methods are different. Compile time polymorphism refers to
a process in which a call to an overloaded method is resolved at compile time rather than at run time.

• Method Overriding(Run time Polymorphism)

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in java. In other words, If subclass provides the specific implementation of the method
that has been provided by one of its parent class, it is known as method overriding.

1.3.6 Dynamic Binding

Binding refers to the linking of a procedure call to the code to be executed in response to the all.
Dynamic binding means that the code associated with a given procedure call is not known until the time of
the call at runtime. It is associated with polymorphism and inheritance. A procedure call associated with a
polymorphic reference depends on the dynamic type of that reference.

Consider the procedure "draw" in the above figure. By inheritance, every object will use this
procedure. Its algorithm is, however, unique to each object and so the draw procedure will be redefined 4 in
each class that defines the object. At run-time, the code matching the object under current reference will be
called.

1.3.7 Message Communication:


An object-oriented program consists of a set of objects that communicate with each other. The
process of programming in an object-oriented language, therefore, involves the following basic steps:

1. Creating classes that define objects and their behaviour.


2. Creating objects from class definitions.
3. Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the same way as
people pass messages to one another. Message passing involves specifying the name of the object, the name
of the method and the information to be sent. For example,

Employee.salary(name);

Here, Employee is the object, salary is the message and name is the parameter that contains
information.

1.4 Java Buzzwords or Features of Java

The Java programming language is a high-level language that can be characterized by all of the following
buzzwords:

1. Simple
2. Object-oriented
3. Distributed
4. Interpreted
5. Robust
6. Secure
7. Architecture neutral
8. Portable
9. High performance
10. Multithreaded
11. Dynamic

1. Simple

• Java was designed to be easy for a professional programmer to learn and use effectively.
• It‘s simple and easy to learn if you already know the basic concepts of Object Oriented
Programming.
• Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort.
Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most
programmers have little trouble learning Java.
• Java has removed many complicated and rarely-used features, for example, explicit pointers,
operator overloading, etc.
2. Object Oriented

• Java is true object-oriented language.


• Almost ―Everything is an Object‖ paradigm. All program code and data reside within objects and
classes.
• The object model in Java is simple and easy to extend.
• Java comes with an extensive set of classes, arranged in packages that can be used in our programs
through inheritance.
• Object-oriented programming (OOPs) is a methodology that simplifies software development and
maintenance by providing some rules.

Basic concepts of OOPs are:

• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation

3. Distributed

• Java is designed for distributed environment of the Internet. Its used for creating applications on
networks.
• Java applications can access remote objects on the Internet as easily as they can do in the local
system.
• Java enables multiple programmers at multiple remote locations to collaborate and work together on
a single project.
• Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols.

4. Compiled and Interpreted

• Usually, a computer language is either compiled or interpreted. Java combines both this approach
and makes it a two-stage system.
• Compiled: Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java Bytecode.
• Interpreted: Bytecode is then interpreted, which generates machine code that can be directly
executed by the machine that provides a Java Virtual machine.

5. Robust

• It provides many features that make the program execute reliably in a variety of environments.
• Java is a strictly typed language. It checks code both at compile time and runtime.
• Java takes care of all memory management problems with garbage collection.
• Java, with the help of an exception handling, captures all types of serious errors and eliminates any
risk of crashing the system.

6. Secure

• Java provides a ―firewall‖ between a networked application and your computer.


• When a Java Compatible Web browser is used, downloading can be done safely without fear of viral
infection or malicious intent.
• Java achieves this protection by confining a Java program to the Java execution environment and not
allowing it to access other parts of the computer.

7. Architecture Neutral

• Java language and Java Virtual Machine helped in achieving the goal of ―write once; run anywhere,
any time, forever.‖
• Changes and upgrades in operating systems, processors and system resources will not force any
changes in Java Programs.

8. Portable

• Java Provides a way to download programs dynamically to all the various types of platforms
connected to the Internet.
• It helps in generating Portable executable code.

9. High Performance

• Java performance is high because of the use of bytecode.


• The bytecode was used so that it was easily translated into native machine code.

10. Multithreaded

• Multithreaded Programs handled multiple tasks simultaneously, which was helpful in creating
interactive, networked programs.
• Java run-time system comes with tools that support multiprocess synchronization used to construct
smoothly interactive systems.

11. Dynamic

• Java is capable of linking in new class libraries, methods, and objects.


• Java programs carry with them substantial amounts of run-time type information that is used to
verify and resolve accesses to objects at runtime. This makes it possible to dynamically link code in
a safe and expedient manner.

1.5 Overview of Java


Java is a robust, general-purpose, high-level programming language and a powerful software platform.
It is also object-oriented, distributed, portable and multi-threaded. Java follows the 'Write - once - run -
anywhere' approach.

All Java programs must run on the Java platform that has two components, the Java Virtual Machine
(JVM) and the Java Application Programming Interface (API). With Java API, many types of Java
programs can be developed. These include
• Java stand-alone applications
• Java Applets
• Java Servlets

• Java stand-alone applications: The Java stand-alone applications are the programs written in Java to
carry out certain tasks. These applications run directly by the Java interpreter. It can have either a
Command-Line Interface (CLI) or Graphical User Interface (GUI).
• Java Applets: Java applets are the Java applications that are embedded inside HTML files and can be
downloaded into a Java-capable browser (E.g. Netscape and Hot Java). An applet can perform tasks and
interact with users on their browser's WebPages without using resources from the web server after being
downloaded.
• Java Servlets: Java servlets are the Java programs that run on a web server to generate dynamic web
contents.
CHARACTERISTICS OF JAVA

• Compiled and Interpreted

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

• Platform-Independent and Portable

The most significant contribution of Java over other languages is its portability. Java
programs can be easily moved from one computer system to another, anywhere and anytime.
Changes and upgrades in operating systems, processors and system resources will not force any
changes in Java programs. This is the reason why Java has become a popular language for
programming on Internet which interconnects different kinds of systems worldwide. We can
download a Java applet from a remote computer onto our local system via Internet and execute it
locally. This makes the Internet an extension of the user's basic system providing practically
unlimited number of accessible applets and applications.

Java ensures portability in two ways. First, Java compiler generates bytecode instructions
that can be implemented on any machine. Secondly, the size of the primitive data types is machine-
independent

• Object-Oriented
Java is a true object-oriented language. Almost everything in Java is an object. All program
code and data reside within objects and classes. Java comes with an extensive set of classes,
arranged in packages that we can use in our programs by inheritance. The object model in Java is
simple and easy to extend.

• Robust and Secure


Java is a robust language. It provides many safeguards to ensure reliable code. It has strict
compile time and run time checking for data types. It is designed as a garbage-collected language
relieving the programmers virtually all memory management problems. Java also incorporates the
concept of exception handling which captures series errors and eliminates any risk of crashing the
system.

Security becomes an important issue for a language that is used for programming on Internet.
Threat of viruses and abuse of resources is everywhere. Java systems not only verify all memory
access but also ensure that no viruses are communicated with an applet. The absence of pointers in
Java ensures that programs cannot gain access to memory locations without proper authorization.
• Distributed
Java is designed as a distributed language for creating applications on networks. It has the
ability to share both data and programs. Java applications can open and access remote objects on
Internet as easily as they can do in a local system. This enables multiple programmers at multiple
remote locations to collaborate and work together on a single project.

• Familiar, Simple. and Small


Java is a small and simple language. Many features of C and C+ + that are either redundant
or sources of unreliable code are not part of Java. For example, Java does not use pointer,
preprocessor header files, goto statement and many others. It also eliminates· operator overloading
and multiple inheritance.
Familiarity is another striking feature of Java. To make the language look familiar to the
existing programmers, it was modeled on C and C++ languages. Java uses many constructs of C and
C++ and therefore, Java code "looks like a C++" code.

• Multithreaded and Interactive


Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded
programs. This means that we need not wait for the application to finish one task before beginning
another. For example, we can listen to an audio clip while scrolling a page and at the same time
download an applet from a distant computer. This feature greatly improves the interactive
performance of graphical applications. The Java runtime comes with tools that support multiprocess
synchronization and construct smoothly running interactive systems.

• High Performance
Java performance is impressive for an interpreted language, mainly due to the use of
intermediate byte code. According to Sun, Java speed is comparable to the native C/C++. Java
architecture is also designed to reduce overheads during runtime. Further, the incorporation of
multithreading enhances the overall execution speed of Java programs.

• Dynamic and Extensible


Java is a dynamic language. Java is capable of dynamically linking in new class libraries,
methods, and objects. Java can also determine the type of class through a query, making it possible
to either dynamically link or abort the program, depending on the response.
Java programs support functions written in other languages such as C and C+ +. These
functions are known as native methods. This facility enables the programmers to use the efficient
functions available in these languages. Native methods are linked dynamically at runtime.

Differences between Java and C


Java is a lot like C but the major difference between Java and C is that Java is an object-oriented
language and has mechanism to define classes and objects. In an-effort to build a simple and safe language,
the Java team did not include some of the C features in Java.
• Java does not include the C unique statement keywords goto, sizoof, and typedef.
• Java does not contain the data types struct, union and enum .
• Java does not define the type modifiers keywords auto, extern, register, signed, and unsigned.
• Java does not support an explicit pointer type.
• Java does not have a preprocessor and therefore we cannot use # define, # include, and # ifdef
statements.
• Java does not support any mechanism for defining variable arguments to functions.
• Java: requires that the functions with no arguments must be declared with empty parenthesis and not
with the void keyword as done in C.

The Java Programming Environment:


• Installing the Java Development Kit:
The most complete and up-to-date versions of the Java Development Kit (JDK) are available
from Oracle for Linux, Mac OS X, Solaris, and Windows.

• Downloading the JDK:


To download the Java Development Kit, visit the web site at
www.oracle.com/technetwork/java/javase/downloads

• Setting the Executable Path


export PATH=jdk/bin:$PATH

Here is how you test whether you did it right: Start a shell window. Type the line
javac -version
and press the Enter key. You should get a display such as this one:
javac 1.7.0_02
• Choosing a Development Environment
o Using the Command-Line Tools
o Using an Integrated Development Environment
• Using the Command-Line Tools
o Open a shell window.
o Go to the directory into which you installed the source code.(eg. Welcome.java)
o Enter the following commands:
javac Welcome.java
java Welcome
You will see the output in the shell window.
The javac program is the Java compiler. It compiles the file Welcome.java into the file
Welcome.class. The java program launches the Java virtual machine. It executes the bytecodes that the
compiler placed in the class file.
• Using an Integrated Development Environment:
o Eclipse
Eclipse, is an integrated development environment that is freely available from
http://eclipse.org. Eclipse is written in Java, but since it uses a nonstandard windowing library, it
is not quite as portable as Java itself. Nevertheless, versions exist for Linux, Mac OS X, Solaris,
and Windows.
There are other popular IDEs, but currently, Eclipse is the most commonly used. Here are the
steps to get started:
1. After starting Eclipse, select File -> New Project from the menu.
2. Select ―Java Project‖ from the wizard dialog. These screen-shots were taken with Eclipse
3.2. Don‗t worry if your version of Eclipse looks slightly different.
3. Click the Next button. Supply the project name ―Welcome‖ and type in the full path name
of the directory that contains Welcome.java.
4. Be sure to check the option labeled ―Create project from existing source‖.
5. Click the Finish button. The project is now created.
6. Click on the triangle in the left pane next to the project window to open it, and then click on
the triangle next to ―Default package‖. Double-click on Welcome.java. You should now
see a window with the program code.
7. With the right mouse button, click on the project name (Welcome) in the leftmost pane.
Select Run -> Run As -> Java Application. An output window appears at the bottom of the
window. The program output is displayed in the output window.

o NetBeans:
1. In the NetBeans IDE, choose File | New Project....
2. In the New Project wizard, expand the Java category and select Java Application
3. In the Name and Location page of the wizard, do the following :
a. In the Project Name field, type Hello World App.
b. In the Create Main Class field, type helloworldapp.HelloWorldApp.
4. Click Finish.

STRUCTURE OF JAVA PROGRAM

A Java program involves the following sections:


• Documentation Section
• Package Statement
• Import Statements
• Interface Statement
• Class Definition
• Main Method Class
o Main Method Definition
Section Description

Documentation Section You can write a comment in this section. Comments are beneficial
for the programmer because they help them understand the code.
These are optional.

Package statement You can create a package with any name. A package is a group of
classes that are defined by a name. That is, if you want to declare
many classes within one element, then you can declare it within a
package. It is an optional. To create a
package, use the statement
package packagename;
Import statements This line indicates that if you want to use a class of another
package, then you can do this by importing it directly into your
program. Example:
import calc.add;
Interface statement Interfaces are like a class that includes a group of method
declarations. It's an optional section and can be used when
programmers want to implement multiple inheritances within a
program.
Class Definition A Java program may contain several class definitions. Classes are
the main and essential elements of any Java program
Main Method Class Every Java stand-alone program requires the main method as the
starting point of the program. This is an essential part of a Java
program. There may be many classes in a Java program, and only
one class defines the main method. Methods contain data type
declaration and executable statements.

COMPILATION AND EXECUTION OF A JAVA PROGRAM

Java, being a platform independent programming language, doesn‗t work on one-step-compilation.


Instead, it involves a two-step execution, first through an OS independent compiler; and second, in a virtual
machine (JVM) which is custom-built for every operating system. The two principle stages are explained
below:

Compilation

First, the source ‗.java‘ file is passed through the compiler, which then encodes the source code into
a machine independent encoding, known as Bytecode. The content of each class contained in the source file
is stored in a separate ‗.class‘ file.

Execution

The class files generated by the compiler are independent of the machine or the OS, which allows
them to be run on any system. To run, the main class file (the class that contains the method main) is passed
to the JVM, and then goes through three main stages before the final machine code is executed. These
stages are:

a. Class Loader

The main class is loaded into the memory by passing its ‗.class‗ file to the JVM, through invoking
the latter. All the other classes referenced in the program are loaded through the class loader.

b. Bytecode Verifier

After the bytecode of a class is loaded by the class loader, it has to be inspected by the bytecode
verifier, whose job is to check that the instructions don‗t perform damaging actions. The following are some
of the checks carried out:
• Variables are initialized before they are used.
• Method calls match the types of object references.
• Rules for accessing private data and methods are not violated.
• Local variable accesses fall within the runtime stack.
• The run time stack does not overflow.
• If any of the above checks fails, the verifier doesn‗t allow the class to be loaded.

c. Just-In-Time Compiler

This is the final stage encountered by the java program, and its job is to convert the native code, as
opposed to having the JVM interpret the same sequence of bytecode repeatedly and incurring the penalty of
a relatively lengthy translation process. This can lead to performance gains in the execution speed, unless
methods are executed less frequently. The process can be well-illustrated by the following diagram:
Due to the two-step execution process described above, a java program is independent of the target
operating system. However, because of the same, the execution time is way more than a similar program
written in a compiled platform-dependent program.

Note: Java Virtual Machine (JVM) is a virtual machine that enables a computer to run Java
programs as well as programs written in other languages and compiled to Java bytecode.

FUNDAMENTAL PROGRAMMING STRUCTURES IN JAVA

COMMENTS
Comments in Java, as in most programming languages, do not show up in the executable program.
Java has three ways of marking comments.
a. The most common form is a //. You use this for a comment that will run from the // to the end of the line.
Eg:
System.out.println("Hello, World!"); // comment
b. When longer comments are needed, you can use the /* and */ comment delimiters that let you block off a
longer comment.
c. Finally, a third kind of comment can be used to generate documentation automatically. This comment
uses a /** to start and a */ to end.

Example:
/**
* This is my first
* java program
*/
public class JavaApplication1
{
public static void main(String[] args)
{
System.out.println("welcome");
}
}

DATA TYPES
The Primitive Types
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. Also called as simple types. These can be put in four groups:

• Integers: This group includes byte, short, int, and long, which are for whole-valued signed
numbers.
• Floating-point numbers: This group includes float and double, which represent numbers
with fractional precision.
• Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
• Boolean: This group includes boolean, which is a special type for representing true/false
values.
1) Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers.

The width of an integer type should not be thought of as the amount of storage it consumes, but
rather as the behavior it defines for variables and expressions of that type. The width and ranges of
these integer types vary widely, as shown in this table:

a) byte
The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127.
Variables of type byte are especially useful when you‗re working with a stream of data from a network
or file. Byte variables are declared by use of the byte keyword.
For example, the following declares two byte variables called b and c:
byte b, c;

b) short
short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least-used
Java type. Here are some examples of short variable declarations:
short s;
short t;

c) int
The most commonly used integer type is int. It is a signed 32-bit type that has a range rom –
2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly employed
to control loops and to index arrays.
For example, the following declares two integer variables called b and c:
int b, c;

d) long
long is a signed 64-bit type and is useful for those occasions where an int type is not large
enough to hold the desired value. The range of a long is quite large. This makes it useful
when big, whole numbers are needed.
For example, the following declares two long variables called b and c:
long b, c;
For example, here is a program that computes the number of miles that light will travel in a specified
number of days.

Code:
// Compute distance light travels using long variables.
class Light
{
public static void main(String args[])
{
int lightspeed;
long days;
long seconds;
long distance;
// approximate speed of light in miles per second
lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles.");
}

Output:
In 1000 days light will travel about 16070400000000 miles.

2. Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision. There are two kinds of floating-point types, float and double, which
represent single- and double-precision numbers, respectively.

a) float
The type float specifies a single-precision value that uses 32 bits of storage. Single precision is
faster on some processors and takes half as much space as double precision, but will become imprecise
when the values are either very large or very small. Here are some example float variable declarations:
float hightemp, lowtemp;

b) double
Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double
precision is actually faster than single precision on some modern processors that have been optimized
for high-speed mathematical calculations. All transcendental math functions, such as sin( ), cos( ), and
sqrt( ), return double values.
Code:
// Compute the area of a
circle. class Area
{
public static void main(String args[])
{
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}
Output:
Area of circle is 366.2496

3. Characters
In Java, the data type used to store characters is char. However, char in Java is not the same as
char in C or C++. In C/C++, char is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode
to represent characters. Unicode defines a fully international character set that can represent all of the
characters found in all human languages. It is a unification of dozens of character sets, such as Latin,
Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more. For this purpose, it requires 16
bits. Thus, in Java char is a 16-bit type. The range of a char is 0 to 65,536.
// Demonstrate char data type.
class CharDemo
{
public static void main(String args[])
{
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
Output:
ch1 and ch2: X Y

Although char is designed to hold Unicode characters, it can also be thought of as an integer type on
which you can perform arithmetic operations.
Example:
// char variables behave like
integers. class CharDemo2
{
public static void main(String args[])
{
char ch1; ch1 = 'X';
System.out.println("ch1 contains " + ch1);
ch1++; // increment ch1
System.out.println("ch1 is now " + ch1);
}
}
Output:
ch1 contains X
ch1 is now Y
In the program, ch1 is first given the value X. Next, ch1 is incremented. This results in ch1 containing
Y, the next character in the ASCII (and Unicode) sequence.

4. Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two possible
values, true or false. This is the type returned by all relational operators, as in the case of a < b. boolean
is also the type required by the conditional expressions that govern the control statements such as if and
for.
Code:
// Demonstrate boolean values. class BoolTest
{
public static void main(String args[])
{
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
if(b)
System.out.println("This is executed.");
System.out.println("10 > 9 is " + (10 > 9));
}
}
Output:
b is false
b is true
This is executed.
10 > 9 is true
Literals
A constant value in Java is created by using a literal representation of it.
1. Integer Literals
Integers are probably the most commonly used type in the typical program. Any whole number value
is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal values, meaning they are
describing a base 10 number. There are two other bases which can be used in integer literals, octal (base
eight) and hexadecimal (base 16). Octal values are denoted in Java by a leading zero. You signify a
hexadecimal constant with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to 15, so
A through F (or a through f ) are substituted for 10 through 15. Integer literals create an int value, which
in Java is a 32-bit integer value.

2. Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component. They can be
expressed in either standard or scientific notation. Standard notation consists of a whole number
component followed by a decimal point followed by a fractional component. For example, 2.0, 3.14159,
and 0.6667 represent valid standard-notation floating-point numbers.
Scientific notation uses a standard-notation, floating-point number plus a suffix that specifies a
power of 10 by which the number is to be multiplied. The exponent is indicated by an E or e followed by
a decimal number, which can be positive or negative. Examples include 6.022E23, 314159E–05, and
2e+100. Floating-point literals in Java default to double precision. To specify a float literal, you must
append an F or f to the constant. You can also explicitly specify a double literal by appending a D or d.
The default double type consumes 64 bits of storage, while the less-accurate float type requires only 32
bits.

3. Boolean Literals
Boolean literals are simple. There are only two logical values that a boolean value can have, true
and false. The values of true and false do not convert into any numerical representation. The true literal
in Java does not equal 1, nor does the false literal equal 0.

4. Character Literals
Characters in Java are indices into the Unicode character set. They are 16-bit values that can be
converted into integers and manipulated with the integer operators, such as the addition and subtraction
operators.
A literal character is represented inside a pair of single quotes. All of the visible ASCII
characters can be directly entered inside the quotes, such as ‗a‘, ‗z‘, and ‗@‘.
For characters that are impossible to enter directly, there are several escape sequences that allow
you to enter the character you need, such as ‗\‘‘ for the single-quote character itself and ‗\n‘ for the
newline character. There is also a mechanism for directly entering the value of a character in octal or
hexadecimal. For octal notation, use the backslash followed by the three-digit number. For example,
‗\141‘ is the letter ‗a‘. For hexadecimal, you enter a backslash-u (\u), then exactly four hexadecimal
digits. For example, ‗\u0061‘ is the ISO-Latin-1 ‗a‘ because the top byte is zero. ‗\ua432‘ is a Japanese
Katakana character. Table shows the character escape sequences.
5. String Literals
String literals in Java are specified like they are in most other languages—by enclosing a
sequence of characters between a pair of double quotes.
Examples of string literals are
―Hello World”
―two\nlines”
―\”This is in quotes\””
VARIABLES
The variable is the basic unit of storage in a Java program. A variable is defined by the
combination of an identifier, a type, and an optional initializer. In addition, all variables have a scope,
which defines their visibility, and a lifetime.

Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable declaration:

type identifier [ = value][, identifier [= value] ...] ;


The type is one of Java‗s atomic types, or the name of a class or interface. The identifier is the name of the
variable. You can initialize the variable by specifying an equal sign and a value. To declare more than one
variable of the specified type, use a comma separated list.
Examples:
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing // d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.

Dynamic Initialization:
Java allows variables to be initialized dynamically.

Example:
class DynInit
{
public static void main(String args[])
{
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}

The Scope and Lifetime of Variables


Java allows variables to be declared within any block. A block is begun with an opening curly
brace and ended by a closing curly brace. A block defines a scope. Thus, each time you start a new
block, you are creating a new scope. A scope determines what objects are visible to other parts of your
program. It also determines the lifetime of those objects.
There are two general categories of scopes:
• global and
• local
However, these traditional scopes do not fit well with Java‗s strict, object-oriented model.
As a general rule, variables declared inside a scope are not visible (that is, accessible) to code
that is defined outside that scope. Thus, when you declare a variable within a scope, you are localizing
that variable and protecting it from unauthorized access and/or modification.
Scopes can be nested. For example, each time you create a block of code, you are creating a new,
nested scope. When this occurs, the outer scope encloses the inner scope. This means that objects
declared in the outer scope will be visible to code within the inner scope. However, the reverse is not
true. Objects declared within the inner scope will not be visible outside it.
Variables are created when their scope is entered, and destroyed when their scope is left. This
means that a variable will not hold its value once it has gone out of scope. Therefore, variables declared
within a method will not hold their values between calls to that method. Also, a variable declared within
a block will lose its value when the block is left. Thus, the lifetime of a variable is confined to its scope.
If a variable declaration includes an initializer, then that variable will be reinitialized each time
the block in which it is declared is entered. For example,
// Demonstrate lifetime of a variable.
class LifeTime
{
public static void main(String args[])
{
int x;
for(x = 0; x < 3; x++)
{
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " + y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
Output:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100

Type Conversion and Casting


It is common to assign a value of one type to a variable of another type. If the two types are
compatible, then Java will perform the conversion automatically. For example, it is always possible to
assign an int value to a long variable. However, not all types are compatible, and thus, not all type
conversions are implicitly allowed. For instance, there is no automatic conversion defined from double to
byte. Fortunately, it is still possible to obtain a conversion between incompatible types. To do so, you must
use a cast, which performs an explicit conversion between incompatible types.

Java’s Automatic Conversions


When one type of data is assigned to another type of variable, an automatic type conversion will
take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For example, the int type is
always large enough to hold all valid byte values, so no explicit cast statement is required.
For widening conversions, the numeric types, including integer and floating-point types, are
compatible with each other. However, there are no automatic conversions from the numeric types to
char or boolean. Also, char and boolean are not compatible with each other.
Java also performs an automatic type conversion when storing a literal integer constant into
variables of type byte, short, long, or char.

Casting Incompatible Types

Although the automatic type conversions are helpful, they will not fulfill all needs. For example,
what if you want to assign an int value to a byte variable? This conversion will not be performed
automatically, because a byte is smaller than an int. This kind of conversion is sometimes called a
narrowing conversion, since you are explicitly making the value narrower so that it will fit into the target
type.
To create a conversion between two incompatible types, you must use a cast. A cast is simply an
explicit type conversion.
General form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to. For example, the following
fragment casts an int to a byte. If the integer‗s value is larger than the range of a byte, it will be reduced
modulo (the remainder of an integer division by the) byte‗s range.
int a; byte b;
// ...

b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to an integer type:
truncation. As you know, integers do not have fractional components. Thus, when a floating-point value
is assigned to an integer type, the fractional component is lost.
For example, if the value 1.23 is assigned to an integer, the resulting value will simply be 1. The
0.23 will have been truncated. Of course, if the size of the whole number component is too large to fit into
the target integer type, then that value will be reduced modulo the target type‗s range.

Code:
// Demonstrate casts.
class Conversion
{
public static void main(String args[])
{
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
Output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67

The Type Promotion Rules


Java defines several type promotion rules that apply to expressions. They are as follows: First, all
byte, short, and char values are promoted to int, as just described. Then, if one operand is a long, the whole
expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any
of the operands is double, the result is double.
OPERATORS
1. Arithmetic Operators:
Arithmetic operators are used in mathematical expressions.

The Modulus Operator


The modulus operator, %, returns the remainder of a division operation.

Arithmetic Compound Assignment Operators


Java provides special operators that can be used to combine an arithmetic operation with an
assignment. There are compound assignment operators for all of the arithmetic, binary operators. Thus,
any statement of the form
var = var op expression;
can be rewritten as
var op= expression;

Increment and Decrement:


The increment operator increases its operand by one. The decrement operator decreases its operand
by one. These operators are unique in that they can appear both in postfix form, where they follow the
operand, and prefix form, where they precede the operand.

Example:
public class Test {
public static void main(String[] args) {
int x=10,y=5;
int a=x+y;
int b=x-y;
int c=x*y;
int d=x/y;
int e=x%y;
System.out.println("sum="+a);
System.out.println("Difference="+b);
System.out.println("Product="+c);
System.out.println("Quotient="+d);
System.out.println("Remainder="+e);
x+=y;
System.out.println("x="+x);
x-=y;
System.out.println("x="+x);
a=1;
b=2;
c = ++b;//c=3,b=3
d = a++;//d=1,a=2
c++;//c=4
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}}

output:

sum=15
Difference=5
Product=50
Quotient=2
Remainder=0
x=15
x=10
a=2
b=3
c=4
d=1

2. The Bitwise Operators


Java defines several bitwise operators that can be applied to the integer types, long, int, short,
char, and byte.
Bitwise Logical Operators
The bitwise logical operators are &, |, ^, and ~. The bitwise operators are applied to each
individual bit within each operand.

Bitwise left shift operator:


Left shift operator shift its value toward left as much number of bits as you defined and place
zeros at the right most places.

Bitwise right shift operator:


In right shift, the Bit value for given number is simply moved to right side and left most bits are
replaced with the zeros.

Bitwise Operator Compound Assignments:


All of the binary bitwise operators have a compound form similar to that of the algebraic
operators, which combines the assignment with the bitwise operation. For example, the following two
statements, which shift the value in a right by four bits, are equivalent:
a = a >> 4;
a >>= 4;
Example:
public class Test {
public static void main(String[] args) {
// TODO code application logic here
int a = 60; /* 60 = 0011 1100 */
int b = 13; /* 13 = 0000 1101 */
int c = 0;

c = a & b; /* 12 = 0000 1100 */


System.out.println("a & b = " + c );

c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );

c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );

c = ~a; /*-61 = 1100 0011 */


System.out.println("~a = " + c );

c = a << 2; /* 240 = 1111 0000 */


System.out.println("a << 2 = " + c );
c = a >> 2; /* 15 = 1111 */
System.out.println("a >> 2 = " + c );
c = a >>> 2; /* 15 = 0000 1111 */
System.out.println("a >>> 2 = " + c );
}

output:
a & b = 12
a | b = 61
a ^ b = 49
~a = -61
a << 2 = 240
a >> 2 = 15
a >>> 2 = 15

3. Relational Operators
The relational operators determine the relationship that one operand has to the other. The
outcome of these operations is a boolean value.

Example:
public class Test
{ public static void main(String[] args)
{
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
}
}
output:
a == b = false
a != b = true
a > b = false
a < b = true
4. Boolean Logical Operators
The Boolean logical operators shown here operate only on boolean operands. All of the binary
logical operators combine two boolean values to form a resultant boolean value.

The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they operate
on the bits of an integer.

Example:
public class Test
{
public static void main(String[] args)
{
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("(!a&b)|(a&!b) = " + f);
System.out.println(" !a = " + g);
} }
output:
a = true
b = false
a|b = true
a&b = false
a^b = true
(!a&b)|(a&!b) = true
!a = false

5. Short-Circuit Logical Operators


Java provides two interesting Boolean operators not found in many other computer languages.
These are secondary versions of the Boolean AND and OR operators, and are known as short-circuit
logical operators.
When short-circuit AND (&&) is used, if the first value is false, second value is not evaluated.
Similarly for short-circuit OR (||), if the first value is true, then second value is not evaluated. These
short-circuit operators will be useful when we want to control the evaluation of right hand operand.

Code:
public class Test
{
public static void main(String[] args)
{
int c = 0, d = 100, e = 50;
if( c == 1 && e++ < 100 )
{
d = 150;
}
System.out.println("e = " + e );
System.out.println("d = " + d );
}

output:
e = 50
d=100

6. The Assignment Operator:


The assignment operator is the single equal sign, =.
General form:
var = expression;
Here, the type of var must be compatible with the type of expression.

7. The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else
statements. This operator is the ?.
General form:
expression1 ? expression2 : expression3

Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true, then
expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ? operation is that of the
expression evaluated.

Code:
public class Test
{
public static void main(String[] args)
{
int a=5,b=10;
int c=(a>b)?1:0;
System.out.println("c = " + c);
}
}
output:
c=0
CONTROL STATEMENTS

Java‗s program control statements can be put into the following categories:
• Selection statements
• Iteration statements
• Jump statements
1. Selection statements
Selection statements allow your program to choose different paths of execution based upon the
outcome of an expression or the state of a variable. Java supports two selection statements:
• if
• switch
a. if
The if statement is Java‗s conditional branch statement. It can be used to route program
execution through two different paths.
General Form:
if (condition)
statement1;
else
statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly braces (that
is, a block). The condition is any expression that returns a boolean value. The else clause is optional.
If the condition is true, then statement1 is executed. Otherwise, statement2 (if it exists) is
executed. In no case will both statements be executed.

Example:
public class Test {
public static void main(String[] args) {
int n=5;
if(n%2==0)
System.out.println(n+" is even");
else
System.out.println(n+" is odd");
}

Output:
5 is odd

b.Nested ifs
A nested if is an if statement that is the target of another if or else.

Example:

if(a<100)
{
if(a<20)
{
a=1;
}
}

c.The if-else-if Ladder


General Form:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...

else
statement;
The if statements are executed from the top down. As soon as one of the conditions controlling the if is
true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the
conditions is true, then the final else statement will be executed. The final else acts as a default condition;
that is, if all other conditional tests fail, then the last else statement is performed.
Example:
public class Test {
public static void main(String[] args) {
int n=5;
if(n==0)
System.out.println(n+" is zero");
else if(n>0)
System.out.println(n+" is positive");
else
System.out.println(n+" is negative");

}
}
Output:
5 is positive

d.switch
The switch statement is Java‗s multiway branch statement. It provides a better alternative than a large
series of if-else-if statements.

General form:
switch (expression) {
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...

case valueN:
// statement sequence
break;
default:
// default statement sequence
}

The expression must be of type byte, short, int, or char; Each case value must be a unique literal (that is,
it must be a constant, not a variable). Duplicate case values are not allowed.
The switch statement works like this: The value of the expression is compared with each of the
literal values in the case statements. If a match is found, the code sequence following that case statement
is executed. If none of the constants matches the value of the expression, then the default statement is
executed. However, the default statement is optional.The break statement is used inside the switch to
terminate a statement sequence.
public class JavaApplication1 {
public static void main(String[] args) {
int a=10,b=5;
char ch='/';
switch(ch)
{

case '+':
System.out.println("sum is"+(a+b));
break;
case '-':
System.out.println("Difference is"+(a-b));
break;
case '*':
System.out.println("Product is"+(a*b));
break;
case '/':
System.out.println("Quotient is"+(a/b));
break;
}
}

Output:
Quotient is 2
Three important features of the switch statement to note:
• The switch differs from the if in that switch can only test for equality, whereas if can evaluate
any type of Boolean expression.
• No two case constants in the same switch can have identical values.
• A switch statement is usually more efficient than a set of nested ifs.
2. Iteration Statements
Java‗s iteration statements are
• for
• while
• do-while
These statements create loops. A loop repeatedly executes the same set of instructions until a
termination condition is met.
a. while
The while loop is Java‗s most fundamental loop statement. It repeats a statement or block
while its controlling expression is true.
General form:
while(condition) {
// body of loop
}

The condition can be any Boolean expression. The body of the loop will be executed as long as the
conditional expression is true. When condition becomes false, control passes to the next line of code
immediately following the loop.
Example:
public class Test {
public static void main(String[] args) {
int i=1;
while(i<=5)
{
System.out.println(i);
i++;
}
}
}
Output:
1
2
3
4
5

b. do-while
If the conditional expression controlling a while loop is initially false, then the body of the loop
will not be executed at all. However, sometimes it is desirable to execute the body of a loop at least
once, even if the conditional expression is false to begin with.
The do-while loop always executes its body at least once, because its conditional expression is at
the bottom of the loop.
General Form:
do {
// body of loop
} while (condition);
public class Test {
public static void main(String[] args) {
int i=1;
do
{
System.out.println(i);
i++;
} while(i<=5);
}
}
Output:
1
2
3
4
5
The do-while loop is especially useful when you process a menu selection, because you will usually want the
body of a menu loop to execute at least once.
Program:
import java.util.*;
public class Test {

public static void main(String[] args) {


int a=10,b=5;
int ch;
int choice;
Scanner s=new Scanner(System.in);
do
{

System.out.println("1.Add");
System.out.println("2.sub");
System.out.println("3.multiply");
System.out.println("4.divide");
System.out.println("Enter the value of ch");
ch=s.nextInt();
switch(ch)
{

case 1:
System.out.println("sum is"+(a+b));
break;
case 2:
System.out.println("Difference is"+(a-b));
break;
case 3:
System.out.println("Product is"+(a*b));
break;
case 4:
System.out.println("Quotient is"+(a/b));
break;
}

System.out.println("enter choice");
choice=s.nextInt();
}while(choice==1);
}

Output:
1.Add
2.sub
3.multiply
4.divide
Enter the value of ch
1
sum is15
enter choice
1
1. Add
2. sub
3.multiply
4.divide
Enter the value of ch
2
Difference is5
enter choice
0

c. for
General form of the traditional for statement:
for(initialization; condition; iteration) {
// body
}

The for loop operates as follows. When the loop first starts, the initialization portion of the loop is
executed. Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop
control variable against a target value. If this expression is true, then the body of the loop is executed. If
it is false, the loop terminates.
Next, the iteration portion of the loop is executed. This is usually an expression that increments
or decrements the loop control variable. The loop then iterates, first evaluating the conditional
expression, then executing the body of the loop, and then executing the iteration expression with each
pass. This process repeats until the controlling expression is false.
Program:
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
System.out.println(i);
}
}

}
output:
1
2
3
4
5

d. Nested Loops
Java allows loops to be nested. That is, one loop may be inside another.
program:
class Test
{
public static void main(String[] args)
{
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
System.out.print(j);
}
System.out.println();
}
}
}
output:

123
123
123
3. Jump Statements
Java supports three jump statements:
• break
• continue
• return
These statements transfer control to another part of your program.

a.break statement:
In Java, the break statement has three uses.
o First, it terminates a statement sequence in a switch statement.
o Second, it can be used to exit a loop.
o Third, it can be used as a ―civilized‖ form of goto.

Using break as a Form of Goto:


• Java does not have a goto statement because it provides a way to branch in an arbitrary and
unstructured manner.
• Java defines an expanded form of the break statement.
• By using this form of break, you can, for example, break out of one or more blocks of code.
• These blocks need not be part of a loop or a switch. They can be any block.
• The general form of the labeled break statement
break label;
• Most often, label is the name of a label that identifies a block of code.
• When this form of break executes, control is transferred out of the named block.
• The labeled block must enclose the break statement, but it does not need to be the immediately
enclosing block.
• A label is any valid Java identifier followed by a colon.
• Once you have labeled a block, you can then use this label as the target of a break statement.
Example:
public class Test {
public static void main(String[] args) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break first; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
Output:
Before the break.
b.continue statement:
If you want to continue running the loop but stop processing the remainder of the code in its body for this
particular iteration, use continue statement.
Example:
public class Test {
public static void main(String[] args)
{
for(int i=1; i<10; i++)
{
if (i%2 == 0)
{
System.out.print( i +" ");
continue;
}
else
System.out.print(" ");
}
}
}
Output:
2 4 6 8

c.return statement:
The return statement is used to explicitly return from a method. That is, it causes program control
to transfer back to the caller of the method. The return statement immediately terminates the method in
which it is executed.

EXAMPLE:
public class Test {
public static void main(String[] args) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}

Output:
Before the return.
ARRAYS
An array is a group of similar variables that are referred to by a common name. Arrays of any type
can be created and may have one or more dimensions. A specific element in an array is accessed by its
index. Arrays offer a convenient means of grouping related information.

One-Dimensional Arrays
A one-dimensional array is, essentially, a list of similar variables.
Creation of 1D array:
Obtaining an array is a two-step process.
1. Declare a variable of the desired array type.
2. Allocate the memory that will hold the array, using new, and assign it to the array variable.

The general form of a one-dimensional array declaration:


type var-name[ ];
Here, type declares the base type of the array. The base type determines the data type of each element in
the array. Thus, the base type for the array determines what type of data the array will hold.
For example, the following declares an array named days with the type ―array of int‖:
int days[];

Allocation of memory:
new is a special operator that allocates memory.

General form of new:


array-var = new type[size];
Here, type specifies the type of data being allocated,
size specifies the number of elements in the array, and
array-var is the array variable that is linked to the array.
That is, to use new to allocate an array, you must specify the type and number of elements to
allocate. The elements in the array allocated by new will automatically be initialized to zero.
Example:
days = new int[12];
days will refer to an array of 12 integers. Further, all elements in the array will be initialized to zero.
It is possible to combine the declaration of the array variable with the allocation of the array.

General form:
type var-name[ ]= new type[size];
Once you have allocated an array, you can access a specific element in the array by specifying its index
within square brackets. All array indexes start at zero.
Syntax to access an element in an array:
array-var [index]

Code:
public class ArrayTest
{
public static void main(String[] args)
{
int days[]=new int[5];
days[0]=1;
days[1]=2;
days[2]=3;
days[3]=4;
days[4]=5;
System.out.println("days[4]="+days[4]);
}
}

Output:
days[4]=5

Array Initialization:
Arrays can be initialized when they are declared. The process is much the same as that used to
initialize the simple types. An array initializer is a list of comma-separated expressions surrounded by
curly braces. The commas separate the values of the array elements. The array will automatically be created
large enough to hold the number of elements you specify in the array initializer. There is no need to use
new.
Code:
public class ArrayTest
{
public static void main(String[] args)
{
int days[]={1,2,3,4,5};
System.out.println("days[4]="+days[4]);
}
}

Example to perform the sum of elements in an array


public class ArrayTest
{
public static void main(String[] args)
{
int days[]={1,2,3,4,5};
int sum=0;
for(int i=0;i<5;i++)
sum+=days[i];
System.out.println("sum="+sum);
}
}
Output:
sum=15
Multidimensional Arrays
Java has no multidimensional arrays at all, only one-dimensional arrays. Multidimensional arrays
are faked as ―arrays of arrays‖.
To declare a multidimensional array variable, specify each additional index using another set of
square brackets. For example, the following declares a twodimensional array variable called twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array
of arrays of int.

public class MultiArrayTest


{
public static void main(String[] args)
{
int a[][]=new int[2][2];
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
a[i][j]=1;
}
}
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
}
}
Output:
11
11
When you allocate memory for a multidimensional array, you need only specify the memory for the
first (leftmost) dimension. You can allocate the remaining dimensions separately.

For example,
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];

Ragged Arrays:
Ragged Arrays are arrays in which different rows have different lengths.
Example:
int a[][]=new int[4][];
a[0]=new int[1];//row 1 is of length 1
a[1]=new int[2];//row 2 is of length 2
a[2]=new int[3];//row 3 is of length 3
a[3]=new int[4];//row 4 is of length 4

Code:
public class MultiTest {
public static void main(String[] args) {
int a[][]=new int[4][];
a[0]=new int[1];
a[1]=new int[2];
a[2]=new int[3];
a[3]=new int[4];
int i,j;
for(i=0;i<4;i++)
{
for(j=0;j<i+1;j++)
{
a[i][j]=j+1;
}
}
for(i=0;i<4;i++)
{
for(j=0;j<i+1;j++)
{
System.out.println(a[i][j]);
}
System.out.println();
}
}
}
Output:
1
12
123
1234

Matrix Addition:
public class Matrix {
public static void main(String[] args) {
int a[][]={{1,1},{1,1}};
int b[][]={{2,2},{2,2}};
System.out.println("Matrix 1");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(a[i][j]);
}
System.out.println();
}
System.out.println("Matrix 2");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(b[i][j]);
}
System.out.println();
}
System.out.println("Sum");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(a[i][j]+b[i][j]);
}
System.out.println();
}
}
}

Output:
Matrix 1
11
11
Matrix 2
22
22
Sum
33
33

Alternative Array Declaration Syntax


There is a second form that may be used to declare an array:
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable. For
example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This alternative declaration form offers convenience when declaring several arrays at the same
time. For example,
int[] nums, nums2, nums3; // create three arrays creates three array variables of type int.

The “for each” Loop


Java has a powerful looping construct that allows you to loop through each element in an array (or any
other collection of elements) without having to worry with index values.

The enhanced for loop


for (variable : collection) statement
sets the given variable to each element of the collection and then executes the statement.The collection
expression must be an array or an object of a class that implements the Iterable interface, such as
ArrayList.

For example,
for (int element : a)
System.out.println(element); prints each element of the array a on a separate line.

The loop variable of the ―for each‖ loop traverses the elements of the array, not the index values.
Anonymous array:
It is possible to initialize an anonymous
array: new int[] { 17, 19, 23, 29, 31, 37 }
This expression allocates a new array and fills it with the values inside the braces. It counts the number of
initial values and sets the array size accordingly. You can use this syntax to reinitialize an array without
creating a new variable. For example,
a = new int[] { 17, 19, 23, 29, 31, 37 };
Program:
class Test
{
public static void main(String[] args)
{
int[] a=new int[]{1,2,3,4,5};
for(int i=0;i<5;i++)
System.out.println(a[i]);
}
}
Output:
1
2
3
4
5

Arrays class in Java


The Arrays class of the java.util package contains several static methods that we can use to fill, sort,
search, etc in arrays. This class is a member of the Java Collections Framework and is present in
java.util.arrays.
1. public static String toString(int[] a)
The string representation consists of a list of the array‗s elements, enclosed in square brackets (―[]‖).
Adjacent elements are separated by the characters a comma followed by a space.
Example:
import java.util.Arrays;
public class Main
{

public static void main(String[] args)


{

int ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};

// To print the elements in one line


System.out.println(Arrays.toString(ar));
}

2. public static void sort(int[] a) – Sorts the specified array into ascending numerical order.
public static void sort(int[] a, int fromIndex, int toIndex)
If we wish to sort a specified range of the array into ascending order. we can use this. The range
to be sorted extends from the index fromIndex, inclusive, to the index toIndex, exclusive. If
fromIndex == toIndex, the range to be sorted is empty.
Program:
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{

int ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};


Arrays.sort(ar, 0, 4);
System.out.println("Sorted array in range" + " of 0-4 =>\n" + Arrays.toString(ar));
Arrays.sort(ar);
System.out.println("Completely sorted order =>\n" + Arrays.toString(ar));
}

3. public static int[] copyOf(int[] original, int newLength)


Copies the specified array and length. It truncates the array if provided length is smaller and pads
if provided .

public static int[] copyOfRange(int[] original, int from, int to)


Copies the specified range of the specified array into a new array. The initial index of the
range (from) must lie between zero and original.length, inclusive.

import java.util.Arrays;
public class Main
{

public static void main(String[] args)


{

int ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};


// Copy the whole array
int[] copy = Arrays.copyOf(ar, ar.length);
System.out.println("Copied array => \n" + Arrays.toString(copy));
// Copy a specified range into a new array.
int[] rcopy = Arrays.copyOfRange(ar, 1, 5);
System.out.println("Copied subarray => \n" + Arrays.toString(rcopy));
}

4. public static void fill(int[] a, int val)


Fills all elements of the specified array with the specified value.

public static void fill(int[] a, int fromIndex, int toIndex, int val)
– Fills elements of the specified array with the specified value from the fromIndex element, but
not including the toIndex element.
// Java program to fill a subarray or complete
// array with given value.
import java.util.Arrays;

public class Main


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

int ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};

// To fill a range with a particular value


Arrays.fill(ar, 0, 3, 0); System.out.println("Array filled with 0 "+ "from 0 to 3 => \n" +
Arrays.toString(ar));
// To fill complete array with a particular // value
Arrays.fill(ar, 10);
System.out.println("Array completely filled"+" with 10=>\n"+Arrays.toString(ar));
}

5. public static int binarySearch(int[] a, int key) Returns an int value for the index of the specified
key in the specified array. Returns a negative number if the specified key is not found in the array.
For this method to work properly, the array must first be sorted by the sort method.
import java.util.Arrays;
public class Main
{

public static void main(String[] args)


{

int ar[] = {4, 6, 1, 8, 3, 9, 7, 4, 2};

// Sort the complete array in ascending order


// so that Binary Search can be applied
Arrays.sort(ar);
// To search for a particular value(for eg 9)
// use binarysearch method of arrays
int index = Arrays.binarySearch(ar,9);
System.out.println("Position of 9 in sorted"+ " arrays is => \n" + index);

}
INTRODUCING CLASSES
A class is a template for an object, and an object is an instance of a class.

The General Form of a Class:


A class is declared by use of the class keyword.
class classname
{

type instance-variable1;
type instance-variable2;
// ...

type instance-variableN;
type methodname1(parameter-list)
{

// body of method
}

type methodname2(parameter-list)
{

// body of method
}

// ...

type methodnameN(parameter-list)
{

// body of method
}

The data, or variables, defined within a class are called instance variables. The code is contained
within methods. Collectively, the methods and variables defined within a class are called members of the
class.
Variables defined within a class are called instance variables because each instance of the class
(that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is
separate and unique from the data for another.

Declaring Objects
When you create a class, you are creating a new data type. You can use this type to declare objects
of that type. However, obtaining objects of a class is a two-step process.
• First, you must declare a variable of the class type. This variable does not define an
object. Instead, it is simply a variable that can refer to an object.
• Second, you must acquire an actual physical copy of the object and assign it to that
variable. You can do this using the new operator.
The new operator dynamically allocates (that is, allocates at run time) memory for an object and
returns a reference to it. This reference is, more or less, the address in memory of the object allocated by
new. This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically
allocated.
General form:
class name class-var = new classname( );
Here,
class-var is a variable of the class type being created.
classname is the name of the class that is being instantiated.
classname( ) specifies the constructor for the class.
A constructor is a special method to initialize an object. Classes can explicitly define their own
constructors within their class definition. However, if no explicit constructor is specified, then Java will
automatically supply a default constructor.

Example code:
//Accessing instance variables and methods
public class Sum {
int a,b,c;
void operation()
{

c=a+b;
}

void print()
{

System.out.println("Sum of "+a+"and "+b+"is "+c);


}

public class Test {

public static void main(String[] args) {


Sum s1=new Sum();
s1.a=10;
s1.b=10;
s1.operation();
s1.print();
}

Output:
Sum of 10and 10is 20
Example Program:
import java.util.*;
public class Sum {
int a,b,c;
void read()
{

Scanner s=new Scanner(System.in);


System.out.println("Enter x");
a=s.nextInt();
System.out.println("Enter y");
b=s.nextInt();
}

void operation()
{

c=a+b;
}

void print()
{

System.out.println("Sum of "+a+" and "+b+" is "+c);


}

public class JavaApplication1 {

public static void main(String[] args) {


Sum s1=new Sum();
s1.read();
s1.operation();
s1.print();
}

Output:
Enter x
5
Enter y
2
Sum of 5 and 2 is 7

Assigning Object Reference Variables


When you assign one object reference variable to another object reference variable, you are not
creating a copy of the object; you are only making a copy of the reference.
Example:
Sum s1=new Sum(x,y);
Sum s2=s1;
After this fragment executes, b1 and b2 will both refer to the same object. The assignment of b1 to b2 did
not allocate any memory or copy any part of the original object. It simply makes b2 refer to the same
object as does b1. Thus, any changes made to the object through b2 will affect the object to which b1 is
referring, since they are the same object.

JAVA ACCESS SPECIFIERS


The access to classes, constructors, methods and fields are regulated using access modifiers i.e. a
class can control what information or data can be accessible by other classes. To take advantage of
encapsulation, you should minimize access whenever possible.
Java provides a number of access modifiers to help you set the level of access you want for classes
as well as the fields, methods and constructors in your classes. A member has package or default
accessibility when no accessibility modifier is specified.
Access Modifiers
1. private
2. protected
3. default
4. public
• public access modifier
Fields, methods and constructors declared public (least restrictive) within a public class are
visible to any class in the Java program, whether these classes are in the same package or in
another package.
• private access modifier
The private (most restrictive) fields or methods cannot be used for classes and Interfaces. It
also cannot be used for fields and methods within an interface. Fields, methods or constructors
declared private are strictly controlled, which means they cannot be accesses by anywhere outside
the enclosing class. A standard design strategy is to make all fields private and provide public
getter methods for them.
• protected access modifier
The protected fields or methods cannot be used for classes and Interfaces. It also cannot be
used for fields and methods within an interface. Fields, methods and constructors declared
protected in a superclass can be accessed only by subclasses in other packages. Classes in the same
package can also access protected fields, methods and constructors as well, even if they are not a
subclass of the protected member‗s class.
• default access modifier
Java provides a default specifier which is used when no access modifier is present. Any
class, field, method or constructor that has no declared access modifier is accessible only by classes
in the same package. The default modifier is not used for fields and methods within an interface.
METHODS
General form of a method:
returntype name(parameter-list)
{

// body of method
}

Here, returntype specifies the type of data returned by the method. This can be any valid type,
including class types that you create.If the method does not return a value, its return type must be void.
The name of the method is specified by name. This can be any legal identifier.
The parameter-list is a sequence of type and identifier pairs separated by commas. Parameters are
essentially variables that receive the value of the arguments passed to the method when it is called. If the
method has no parameters, then the parameter list will be empty.
Methods that have a return type other than void return a value to the calling routine using
the following form of the return statement:
return value;
Here, value is the value returned.

Example code:
public class Sum {
int a,b,c;
public Sum()
{
a=0;
b=0;
}
public Sum(int x,int y)
{
a=x;
b=y;
}
int operation()
{
return (a+b);
}
}
public class Test {

public static void main(String[] args) {


int x,y;
Scanner s=new Scanner(System.in);
System.out.println("Enter x");
x=s.nextInt();
System.out.println("Enter y");
y=s.nextInt();
Sum s1=new Sum(x,y);
System.out.println("Sum of "+x+" and "+y+" is "+s1.operation());
}
}
Output:
Enter x
5
Enter y
4
Sum of 5 and 4 is 9

TYPES OF METHODS
• Mutator methods
Methods that change instance fields are called mutator methods. A common convention is
to prefix mutator methods with the prefix set.
• Accessor Methods
Methods that only access instance fields without modifying them are called accessor
methods. A common convention is to prefix accessor methods with the prefix get.

EXAMPLE:
public class Student {
String name;
int rollno;
String getName()
{
return name;
}
int getRollno()
{
return rollno;
}
void setName(String s)
{
name=s;
}
void setRollno(int a)
{
rollno=a;
}
}
//Main class
public class Example {
public static void main(String[] args) {
Student s1=new Student();
s1.setName("Danica");
s1.setRollno(21);
System.out.println("Name is: "+s1.getName());
System.out.println("Rollno is: "+s1.getRollno());
}
}
Output:
Name is: Danica
Rollno is: 21

METHOD OVERLOADING
In Java it is possible to define two or more methods within the same class that share the same name, as
long as their parameter declarations are different. When this is the case, the methods are said to be
overloaded, and the process is referred to as method overloading.
Method overloading is one of the ways that Java supports polymorphism. When an overloaded
method is invoked, Java uses the type and/or number of arguments as its guide to determine which version
of the overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number
of their parameters. When Java encounters a call to an overloaded method, it simply executes the version
of the method whose parameters match the arguments used in the call.
Example:
public class Test {
int sum(int a,int b)
{
return(a+b);
}
double sum(double a,double b)
{
return(a+b);
}
String sum(String a,String b)
{
return(a+b);
}
}
public class Example {
public static void main(String[] args) {
Test t1=new Test();
System.out.println("Sum of two int "+t1.sum(2,3));
System.out.println("Sum of two double "+t1.sum(2.5,3.8));
System.out.println("Sum of two string "+t1.sum("wel","come"));
}
}
Output:
Sum of two int 5
Sum of two double 6.3
Sum of two string welcome
CONSTRUCTORS
Java allows objects to initialize themselves when they are created. This automatic initialization is performed
through the use of a constructor.
• A constructor initializes an object immediately upon creation.
• It has the same name as the class in which it resides and is syntactically similar to a method.
• Once defined, the constructor is automatically called immediately after the object is created,
before the new operator completes.
• Constructors look a little strange because they have no return type, not even void. This is because
the implicit return type of a class‗ constructor is the class type itself.
• It is the constructor‗s job to initialize the internal state of an object so that the code creating an
instance will have a fully initialized, usable object immediately.

Default Constructors
A default constructor is a constructor with no parameters. This default constructor sets all the instance
fields to their default values. So, all numeric data contained in the instance fields would be 0, all boolean
values would be false, and all object variables would be set to null.
General Form:
public ClassName()
{

Syntax to create object:


class name class-var = new classname( );

Parameterized Constructors:
A paramaterized constructor is a constructor with parameters. This parameterized constructor
sets all the instance fields to specific values.
public class Sum
{
int a,b,c;
public Sum()
{
a=0;
b=0;
}
public Sum(int x,int y)
{
a=x;
b=y;
}
void operation()
{
c=a+b;
}
void print()
{
System.out.println("Sum of "+a+" and "+b+" is "+c);
}
}
public class Test {
public static void main(String[] args) {
int x,y;
Scanner s=new Scanner(System.in);
System.out.println("Enter x");
x=s.nextInt();
System.out.println("Enter y");
y=s.nextInt();
Sum s1=new Sum(x,y);
s1.operation();
s1.print();
}
}
Sample output:
Enter x
2
Enter y
3
Sum of 2 and 3 is 5

OVERLOADING CONSTRUCTORS
In addition to overloading normal methods,we can also overload constructor methods.
Example:
public class Student {
String name;
int rollno;
Student()
{

name="";
rollno=0;
}

Student(String a,int b)
{

name=a;
rollno=b;
}

void print()
{
System.out.println("Name is: "+name);
System.out.println("Rollno is: "+rollno);
}

public class Example {


public static void main(String[] args) {
Student s1=new Student();
s1.print();
Student s2=new Student("Danica",19);
s2.print();
}
}
Output:
Name is:
Rollno is: 0
Name is: Danica
Rollno is: 19

USING OBJECTS AS PARAMETERS


It is possible to pass objects as parameters to methods. Also a method can return any type of
data, including class types that you create.
EXAMPLE:
public class complex {
int x,y;
public complex()
{
x=0;
y=0;
}
public complex(int a,int b)
{
x=a;
y=b;
}
complex add(complex c1,complex c2)
{
complex t=new complex();
t.x=c1.x+c2.x;
t.y=c1.y+c2.y;
return t;
}
void print()
{
System.out.println("a is: "+x);
System.out.println("b is: "+y);
}
}
public class Example {
public static void main(String[] args) {
complex c1=new complex(2,2);
complex c2=new complex(3,3);
complex c3=new complex();
c3=c3.add(c1, c2);
System.out.println("c1:");
c1.print();
System.out.println("c2:");
c2.print();
System.out.println("c3:");
c3.print();
}
}

Output:
c1:
a is: 2
b is: 2
c2:
a is: 3
b is: 3
c3:
a is: 5
b is: 5

ARGUMENT PASSING METHODS


In general, there are two ways that a computer language can pass an argument to a subroutine.
• Call by value
This approach copies the value of an argument into the formal parameter of the
subroutine. Therefore, changes made to the parameter of the subroutine have no effect on
the argument.
• Call by Reference
In this approach, a reference to an argument (not the value of the argument) is passed to
the parameter. Inside the subroutine, this reference is used to access the actual argument
specified in the call. This means that changes made to the parameter will affect the
argument used to call the subroutine.

Java uses both approaches, depending upon what is passed.


In Java, when you pass a primitive type to a method, it is passed by value. Thus, what occurs to the
parameter that receives the argument has no effect outside the method.
Example:
public class Test {
void add(int a,int b)
{

a=a+5;
b=b+5;
}

public class Example {


public static void main(String[] args) {
Test t1=new Test();
int x=5,y=10;
System.out.println("Before method call");
System.out.println("x="+x);
System.out.println("y="+y);
t1.add(x,y);
System.out.println("After method call");
System.out.println("x="+x);
System.out.println("y="+y);
}

Output:
Before method call
x=5
y=10
After method call
x=5
y=10

When you pass an object to a method, it is passed by call-by-reference. Keep in mind that when
you create a variable of a class type, you are only creating a reference to an object. Thus, when you pass
this reference to a method, the parameter that receives it will refer to the same object as that referred to
by the argument. This effectively means that objects are passed to methods by use of call-by-reference.
Changes to the object inside the method affects the object used as an argument.
Example:
public class Test {
int a,b;
Test(int x,int y)
{

a=x;
b=y;
}

void add(Test t)
{

t.a=t.a+5;
t.b=t.b+5;
}

public class Example {


public static void main(String[] args) {
Test t1=new Test(2,3);
System.out.println("Before method call");
System.out.println("a="+t1.a);
System.out.println("b="+t1.b);
t1.add(t1);
System.out.println("After method call");
System.out.println("a="+t1.a);
System.out.println("b="+t1.b);
}

Output:
Before method call
a=2
b=3
After method call
a=7
b=8

The this Keyword


Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines
the this keyword. this can be used inside any method to refer to the current object. That is, this is
always a reference to the object on which the method was invoked.
public Sum(int x,int y)
{
this.a=x;
this.b=y;
}
Program:
import java.util.*;
class Sum
{

int a,b,c;
public Sum()
{

this.a=0;
this.b=0;
}
public Sum(int x,int y)
{

this.a=x;
this.b=y;
}

void operation()
{

c=a+b;
}

void print()
{

System.out.println("Sum of "+a+" and "+b+" is "+c);


}

public class Test {


public static void main(String[] args) {
int x,y;
Scanner s=new Scanner(System.in);
System.out.println("Enter x");
x=s.nextInt();
System.out.println("Enter y");
y=s.nextInt();
Sum s1=new Sum(x,y);
s1.operation();
s1.print();
}
}

output:
Enter x
4
Enter y
6
Sum of 4 and 6 is 10

Instance Variable Hiding


It is illegal in Java to declare two local variables with the same name inside the same or
enclosing scopes. But we can have local variables, including formal parameters to methods, which
overlap with the names of the class‗ instance variables. However, when a local variable has the same
name as an instance variable, the local variable hides the instance variable.
Example:
public Sum(int a,int b)
{

this.a=a;
this.b=b;
}

Garbage Collection
In Java,objects are dynamically allocated by using the new operator. In some languages, such as
C++, dynamically allocated objects must be manually released by use of a delete operator. Java takes a
different approach; it handles de-allocation automatically. The technique that accomplishes this is
called garbage collection.
When no references to an object exist, that object is assumed to be no longer needed, and the
memory occupied by the object can be reclaimed. Garbage collection only occurs periodically (if at all)
during the execution of your program.

The finalize( ) Method


Sometimes an object will need to perform some action when it is destroyed. For example, if an
object is holding some non-Java resource such as a file handle, then you might want to make sure these
resources are freed before an object is destroyed. To handle such situations, Java provides a mechanism
called finalization.
To add a finalizer to a class, you simply define the finalize( ) method. The Java run time calls
that method whenever it is about to recycle an object of that class. Inside the finalize( ) method, you will
specify those actions that must be performed before an object is destroyed. The garbage collector runs
periodically, checking for objects that are no longer referenced by any running state or indirectly
through other referenced objects. Right before an asset is freed, the Java run time calls the finalize( )
method on the object.

The finalize( ) method has this general form:


protected void finalize( )
{

// finalization code here


}

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
STATIC FIELDS AND METHODS
a. Static Fields
If you define a field as static, then there is only one such field per class. In contrast, each object
has its own copy of all instance fields.
General form:
Static datatype varname;
For example, let‗s suppose we want to assign a unique identification number to each employee.
We add an instance field id and a static field nextId to the Employee class:
class Employee
{
private static int nextId = 1;
private int id;
...

Every employee object now has its own id field, but there is only one nextId field that is shared among
all instances of the class.
Let‗s put it another way. If there are 1,000 objects of the Employee class, then there are 1,000
instance fields id, one for each object. But there is a single static field nextId. Even if there are no
employee objects, the static field nextId is present. It belongs to the class, not to any individual
object.

b. Static Constants
Static variables are quite rare. However, static constants are more common. For example, the
Math class defines a static constant:
public class Math
{

...

public static final double PI = 3.14159265358979323846;


...

You can access this constant in your programs as Math.PI.


Another static constant that you have used many times is System.out. It is declared in the System
class as follows:
public class System
{

...

public static final PrintStream out = . . .;


...
}

c. Static Methods
Static methods are methods that do not operate on objects. For example, the pow method of the
Math class is a static method.

The expression
Math.pow(x, a)
computes the power xa. It does not use any Math object to carry out its task. In other words, it has no
implicit parameter.
General form:
public static methodname()
{

//statements
}

You can think of static methods as methods that don’t have a this parameter. (In a nonstatic
method, the this parameter refers to the implicit parameter of the method.

Since static methods don‗t operate on objects, you cannot access instance fields from a static
method. However, static methods can access the static fields in their class. Here is an example of such a
static method:

public static int getNextId()


{

return nextId; // returns static field


}

General form to invoke a static method:


Classname.methodname(arguments);
Example:
To call the method NextId(), you supply the name of the class:
int n = Employee.getNextId();
Use static methods in two situations:
• When a method doesn‗t need to access the object state because all needed parameters are
supplied as explicit parameters (example: Math.pow).
• When a method only needs to access static fields of the class (example: Employee.getNextId).
Factory Methods- Use of static methods
Here is another common use for static methods. Factory method is a static method that returns an
instance of the class.

Advantage of static factory methods:


• have names, unlike constructors, which can clarify code.
• do not need to create a new object upon each invocation - objects can be cached and reused, if
necessary.
• can return a subtype of their return type - in particular, can return an object whose
implementation class is unknown to the caller.
Example:
public class complex
{
int a,b;
public static complex newObject(int x,int y)
{
return new complex(x,y);
}
complex(int x,int y)
{
a=x;
b=y;
}
void print()
{
System.out.println(a);
System.out.println(b);
}
}
class Test
{
public static void main(String[] args)
{
complex c1=complex.newObject(2,3);
c1.print();
}
}
Output:
2
3

The main Method


The main method does not operate on any objects. In fact, when a program starts, there aren‗t
any objects yet. The static main method executes, and constructs the objects that the program needs.
Example:
public class Employee {
private static int nextId = 1;
private String name;
private double salary;
private int id;
public Employee(String n, double s)
{

name = n;
salary = s;
id = 0;
}

public void setId()


{

id = nextId; // set id to next available id


nextId++;
}

public static int getNextId()


{

return nextId; // returns static field


}

public void print()


{

System.out.println("Name:"+name);
System.out.println("Id:"+id);
System.out.println("Salary:"+salary);
}

public class Test{


public static void main(String[] args) {
Employee[] staff = new Employee[3];
staff[0] = new Employee("Tom", 40000);
staff[1] = new Employee("Dick", 60000);
staff[2] = new Employee("Harry", 65000);
for (Employee e : staff)
{

e.setId();
e.print();
}

int n = Employee.getNextId(); // calls static method


System.out.println("Next available id=" + n);
}

}
Output:
Name:Tom
Id:1
Salary:40000.0
Name:Dick
Id:2
Salary:60000.0
Name:Harry
Id:3
Salary:65000.0
Next available id=4
PACKAGES
Java allows you to group classes in a collection called a package. Packages are convenient for
organizing your work and for separating your work from code libraries provided by others.

The standard Java library is distributed over a number of packages, including java.lang, java.util,
java.net, and so on. The standard Java packages are examples of hierarchical packages. Just as you have
nested subdirectories on your hard disk, you can organize packages by using levels of nesting. All
standard Java packages are inside the java and javax package hierarchies.

The main reason for using packages is


• To guarantee the uniqueness of class names. The package can then be further subdivided
into subpackages.
Defining a package:
To create a package is quite easy: simply include a package command as the first statement in a
Java source file. Any classes declared within that file will belong to the specified package.
The package statement defines a name space in which classes are stored. If you omit the package
statement, the class names are put into the default package, which has no name.
This is the general form of the package statement:
package pkg;
Here, pkg is the name of the package.

Java uses file system directories to store packages. More than one file can include the same package
statement. The package statement simply specifies to which package the classes defined in a file belong.
It does not exclude other classes in other files from being part of that same package.
You can create a hierarchy of packages. To do so, simply separate each package name
from the one above it by use of a period. The general form of a multileveled package statement
is shown here:
package pkg1[.pkg2[.pkg3]];
A package hierarchy must be reflected in the file system of your Java development system. For example,
a package declared as
package java.awt.image;
needs to be stored in java\awt\image in a Windows environment

For example, the file Employee.java in


package p1;
public class Employee
{

...

}
If you don‗t put a package statement in the source file, then the classes in that source file belong to the
default package. The default package has no package name.
Place source files into a subdirectory that matches the full package name. For example, all source files in
the package p1 package should be in a subdirectory p1 on Windows). The compiler places the class files
into the same directory structure.
package p1.p2;
public class Employee
{

...

All source files in the package p1 package should be in a subdirectory p1/p2 on Windows.
To compile this program, simply change to the base directory and run the command
javac PackageTest.java
The compiler automatically finds the file p1/Employee.java and compiles it.

Class Importation
A class can use all classes from its own package and all public classes from other packages. You
can access the public classes in another package in two ways.
1. Simply to add the full package name in front of every class name
For example:
java.util.Date today = new java.util.Date();
This is obviously tedious.
2. Use the import statement
Once you use import, you no longer have to give the classes their full names. You can
import a specific class or the whole package. You place import statements at the top of your
source files (but below any package statements). For example, you can import all classes in the
java.util package with the statement
import java.util.*;
Then you can use
Date today = new Date();
without a package prefix.
You can also import a specific class inside a package:
import java.util.Date;
Example:
package p1;
public class Sum
{
int a,b;
public Sum()
{
a=0;b=0;
}
public Sum(int x,int y)
{
a=x;
b=y;
}
public void add()
{
System.out.println("sum="+(a+b));
}
}
//Main Program
import p1.*;
class Test
{
public static void main(String[] args)
{
Sum a1=new Sum(3,5);
a1.add();
}
}
Output:
sum=8
Example of program with subpackages:
package p1.p2;
public class Sum
{
int a,b;
public Sum()
{
a=0;b=0;
}
public Sum(int x,int y)
{
a=x;
b=y;
}
public void add()
{
System.out.println("sum="+(a+b));
}
}
//Main Program
import p1.p2.*;
class Test
{
public static void main(String[] args)
{
Sum a1=new Sum(3,5);
a1.add();
}
}
Output:
sum=8
JAVA DOCUMENTATION COMMENTS
The JDK contains a very useful tool, called javadoc, that generates HTML documentation from
your source files. If you add comments that start with the special delimiter /** to your source code, you
too can easily produce professional looking documentation. This is a very nice approach because it lets
you keep your code and documentation in one place. If you put your documentation into a separate file,
then, as you probably know, the code and comments will tend to diverge over time. When
documentation comments are in the same file as the source code, it is an easy matter to update both and
run javadoc again.

1. Comment Insertion
The javadoc utility extracts information for the following items:
• Packages
• Public classes and interfaces
• Public and protected fields
• Public and protected constructors and methods
You can supply a comment for each of these features. Each comment is placed immediately above the
feature it describes. A comment starts with a /** and ends with a */. Each /** . . . */ documentation
comment contains free-form text followed by tags. A tag starts with an @, such as @author or @param.
The first sentence of the free-form text should be a summary statement. The javadoc utility
automatically generates summary pages that extract these sentences.
In the free-form text, you can use HTML modifiers such as <em>...</em> for emphasis,
<code>...</code> for a monospaced ―typewriter” font, <strong>...</strong> for strong emphasis, and
even <img ...> to include an image. You should, however, stay away from headings <h1> or rules <hr>
because they can interfere with the formatting of the document.

2. Class Comments
The class comment must be placed after any import statements, directly before the class definition.
Example:
/**

* A <code>Card</code> object represents a playing card, such


* as "Queen of Hearts". A card has a suit (Diamond, Heart,
* Spade or Club) and a value (1 = Ace, 2 . . . 10, 11 = Jack,
* 12 = Queen, 13 = King)
*/

public class Card


{

...

3. Method Comments
Each method comment must immediately precede the method that it describes. In addition to the
general-purpose tags, you can use the following tags:
@param variable description
This tag adds an entry to the ―parameters” section of the current method. The description can
span multiple lines and can use HTML tags. All @param tags for one method must be kept together.
@return description
This tag adds a ―returns” section to the current method. The description can span multiple lines
and can use HTML tags.
@throws class description
This tag adds a note that this method may throw an exception.
Example:
/**

* Raises the salary of an employee.


* @param byPercent the percentage by which to raise the salary (e.g. 10
means 10%)
* @return the amount of the raise
*/

public double raiseSalary(double byPercent)


{

double raise = salary * byPercent / 100;


salary += raise;
return raise;
}

4. Field Comments
You only need to document public fields—generally that means static constants. For example:
/**

* The "Hearts" card suit


*/

public static final int HEARTS = 1;

5. General Comments
The following tags can be used in class documentation comments:

@author name
This tag makes an ―author” entry. You can have multiple @author tags, one for each author.

@version text
This tag makes a ―version‖ entry. The text can be any description of the current version.

The following tags can be used in all documentation comments:


@since text
This tag makes a ―since” entry. The text can be any description of the version that introduced
this feature. For example, @since version 1.7.1
@deprecated text
This tag adds a comment that the class, method, or variable should no longer be used. The text
should suggest a replacement. For example:
@deprecated Use <code>setVisible(true)</code> instead
You can use hyperlinks to other relevant parts of the javadoc documentation, or to external documents,
with the @see and @link tags.
@see reference
This tag adds a hyperlink in the ―see also‖ section. It can be used with both classes and methods.
Here, reference can be one of the following:
package.class#feature label
<a href="...">label</a>
"text"
The first case is the most useful. You supply the name of a class, method, or variable, and
javadoc inserts a hyperlink to the documentation. For example,
@see com.horstmann.corejava.Employee#raiseSalary(double)
makes a link to the raiseSalary(double) method in the com.horstmann.corejava.Employee class.
You can omit the name of the package, or both the package and class name. Then, the feature will be
located in the current package or class.
Note that you must use a #, not a period, to separate the class from the method or variable name.
The Java compiler itself is highly skilled in guessing the various meanings of the period
character as separator between packages, subpackages, classes, inner classes, and methods and variables.
But the javadoc utility isn‗t quite as clever, so you have to help it along.
If the @see tag is followed by a < character, then you need to specify a hyperlink. You can link
to any URL you like. For example:
@see <a href="www.horstmann.com/corejava.html">The Core Java home page</a>
In each of these cases, you can specify an optional label that will appear as the link anchor. If
you omit the label, the user will see the target code name or URL as the anchor. If the @see tag is
followed by a " character, then the text is displayed in the ―see also” section.
For example:
@see "Core Java 2 volume 2"
You can add multiple @see tags for one feature, but you must keep them all together.
• If you like, you can place hyperlinks to other classes or methods anywhere in any of your
documentation comments. Insert a special tag of the form
{@link package.class#feature label}
anywhere in a comment. The feature description follows the same rules as for the @see tag.

6. Package and Overview Comments


You place the class, method, and variable comments directly into the Java source files, delimited
by /** . . . */ documentation comments. However, to generate package comments, you need to add a
separate file in each package directory.
You have two choices:
1. Supply an HTML file named package.html. All text between the tags <body>...</body> is
extracted.
2. Supply a Java file named package-info.java. The file must contain an initial Javadoc comment,
delimited with /** and */, followed by a package statement. It should contain no further code or
comments.
You can also supply an overview comment for all source files. Place it in a file called
overview.html, located in the parent directory that contains all the source files. All text
between the tags
<body>...</body> is extracted. This comment is displayed when the user selects ―Overview‖ from the
navigation bar.

7. Comment Extraction
Here, docDirectory is the name of the directory where you want the HTML files to go. ollow
these steps:
1. Change to the directory that contains the source files you want to document. If you have nested
packages to document, such as com.horstmann.corejava, you must be working in the directory that
contains the subdirectory com. (This is the directory that contains the overview.html file, if you
supplied one.)
2. Run the command
javadoc -d docDirectory
nameOfPackage for a single package. Or, run
javadoc -d docDirectory nameOfPackage1 nameOfPackage2...
to document multiple packages. If your files are in the default package, run
instead javadoc -d docDirectory *.java
If you omit the -d docDirectory option, the HTML files are extracted to the current directory. That
can get messy, and we don‗t recommend it. The javadoc program can be fine-tuned by numerous
command- line options. For example, you can use the -author and -version options to include the
@author and @version tags in the documentation. (By default, they are omitted.)
Another useful option is -link, to include hyperlinks to standard classes. For example, if you
use the command
javadoc -link http://docs.oracle.com/javase/7/docs/api *.java
all standard library classes are automatically linked to the documentation on the Oracle web site.
If you use the -linksource option, each source file is converted to HTML (without color coding, but
with line numbers), and each class and method name turns into a hyperlink to the source.

You might also like