UNIT I-Notes
UNIT I-Notes
1
type methodnameN(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.
Each method or variable in a class may be marked private or public. The public interface of a
class represents everything that external users of the class need to know, or may know. The private
methods and data can only be accessed by code that is a member of the class. Therefore, any other code
that is not a member of the class cannot access a private method or variable.
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
Thus, a class is a logical construct; an object has physical reality.
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.
Inheritance
Inheritance is the process by which objects of one class acquire the properties of objects of
another class. Inheritance supports the concept of hierarchical classification. For example, the bird robin
is a part of the class fiying bird, which is again a part of the class bird.
2
In OOP, the concept of inheritance provides the idea of reusability: This means that we can add
additional features to an existing class without modifying it. This is possible by deriving a new class
from the existing one .The new class will have the combined features of both the classes. Thus the real
appeal and power of the inheritance mechanism is that it allows the programmer to reuse a class that is
almost, but not exactly, what he wants, and to tailor the class.
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.
Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed in response to the call.
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
3
in each class that defines the object. At run-time, the code matching the object under current reference
will be called.
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 as shown in the figure below.
A message for an object is a request for execution of a procedure, and therefore will invoke a
method (procedure) in the receiving object that generates the desired result.
2. 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
4
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 are
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.
5
• 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.
6
• 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 setup procedure offers a default for the installation directory that contains the JDK version number,
such as jdk1.7.0. Here the installation directory is referred as jdk. For example, when we refer to the
jdk/bin directory, we mean the directory with a name such as /usr/local/jdk1.7.0/bin or c:\jdk1.7.0\bin.
Setting the Executable Path
After you are done installing the JDK, you need to carry out one additional step: Add the jdk/bin
directory to the executable path—the list of directories that the operating system traverses to locate
executable files. Directions for this step also vary among operating systems.
• In UNIX (including Linux, Mac OS X, and Solaris), the procedure for editing the executable path
depends on the shell you are using.
export PATH=jdk/bin:$PATH
Under Windows, log in as administrator. Start the Control Panel, switch to Classic View, and select
the System icon. In Windows XP, you immediately get the system properties dialog. In Vista and
7
Windows 7, you need to select Advanced System Settings. In the system properties dialog, click the
Advanced tab, then click on the Environment button. Scroll through the System Variables window
until you find a variable named Path. Click the Edit button. Add the jdk\bin directory to the
beginning of the path, using a semicolon to separate the new entry, like this:
jdk\bin;other stuff
Be careful to replace jdk with the actual path to your Java installation, such as c:\jdk1.7.0_02. Save your
settings. Any new console windows that you start will have the correct 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
If instead you get a message such as ―javac: command not found‖ or ―The name specified is not
recognized as an internal or external command, operable program or batch file‖, then you need to go
back and double-check your installation.
Navigating the Java Directories:
8
Using an Integrated Development Environment:
1. 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.
2. 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 :
In the Project Name field, type Hello World App.
In the Create Main Class field, type helloworldapp.HelloWorldApp.
4. Click Finish.
Documentation Section
Package Statement
Import Statements
Interface Statement
Class Definition
Main Method Class
o Main Method Definition
Section Description
Documentation You can write a comment in this section. Comments are beneficial for the
Section programmer because they help them understand the code. These are optional.
Package You can create a package with any name. A package is a group of classes that are
statement 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
9
package, use the statement
package packagename;
Import This line indicates that if you want to use a class of another package, then you can
statements do this by importing it directly into your program.
Example:
import calc.add;
Interface Interfaces are like a class that includes a group of method declarations. It's an
statement 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 Every Java stand-alone program requires the main method as the starting point of
Class 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.
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.
Example:
/**
* This is my first
* java program
*/
11
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
12
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:
13
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
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[])
14
{
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
15
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.
16
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
17
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.
18
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
{
OPERATORS
1. Arithmetic Operators:
Arithmetic operators are used in mathematical expressions.
21
Bitwise Logical Operators
The bitwise logical operators are &, |, ^, and ~. The bitwise operators are applied to each
individual bit within each operand.
c = a | b; /* 61 = 0011 1101 */
System.out.println("a | b = " + c );
c = a ^ b; /* 49 = 0011 0001 */
System.out.println("a ^ b = " + c );
22
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.
23
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
24
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);
}
}
25
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
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;
}
26
}
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
b. 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
27
}
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) {
28
// 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
29
will usually want the body of a menu loop to execute at least once.
Program:
import java.util.*;
public class Test {
}
output:
1
2
3
4
5
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++)
31
{
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");
32
}
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.
33
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
34
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.
35
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];
36
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++)
37
{
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.
38
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};
39
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};
40
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};
}
}
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)
41
{
// 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 {
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.
44
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 {
45
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:
46
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:
47
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:
48
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
50
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;
}
51
}
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
52
}
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.
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:
54
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.
56
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.
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
58
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;
59
}
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
62
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. Follow
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.
63