Unit 1
Unit 1
• 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.
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.
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.
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:
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.
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.
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 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.
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.
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.
Employee.salary(name);
Here, Employee is the object, salary is the message and name is the parameter that contains
information.
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
• 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.
• 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
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
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
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
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.
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.
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.
• 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.
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.
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
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.
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:
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);
}
}
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
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
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + 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
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
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;
}
}
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 {
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.
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.
Allocation of memory:
new is a special operator that allocates memory.
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]);
}
}
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
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
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)
{
import java.util.Arrays;
public class Main
{
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;
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
{
}
INTRODUCING CLASSES
A class is a template for an object, and an object is an instance of a class.
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()
{
Output:
Sum of 10and 10is 20
Example Program:
import java.util.*;
public class Sum {
int a,b,c;
void read()
{
void operation()
{
c=a+b;
}
void print()
{
Output:
Enter x
5
Enter y
2
Sum of 5 and 2 is 7
// 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 {
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()
{
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);
}
Output:
c1:
a is: 2
b is: 2
c2:
a is: 3
b is: 3
c3:
a is: 5
b is: 5
a=a+5;
b=b+5;
}
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;
}
Output:
Before method call
a=2
b=3
After method call
a=7
b=8
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()
{
output:
Enter x
4
Enter y
6
Sum of 4 and 6 is 10
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.
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
{
...
...
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:
name = n;
salary = s;
id = 0;
}
System.out.println("Name:"+name);
System.out.println("Id:"+id);
System.out.println("Salary:"+salary);
}
e.setId();
e.print();
}
}
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.
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
...
}
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:
/**
...
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:
/**
4. Field Comments
You only need to document public fields—generally that means static constants. For example:
/**
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.
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.