0% found this document useful (0 votes)
10 views64 pages

Java U1

The document provides an introduction to Java programming, covering key concepts of object-oriented programming such as objects, classes, inheritance, polymorphism, and encapsulation. It also outlines the features of Java, including its simplicity, security, portability, and robustness, along with a list of Java keywords and their functionalities. Additionally, a simple Java program is presented to illustrate basic syntax.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views64 pages

Java U1

The document provides an introduction to Java programming, covering key concepts of object-oriented programming such as objects, classes, inheritance, polymorphism, and encapsulation. It also outlines the features of Java, including its simplicity, security, portability, and robustness, along with a list of Java keywords and their functionalities. Additionally, a simple Java program is presented to illustrate basic syntax.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

JAVA PROGRAMMING

UNIT I
INTRODUCTION TO JAVA:
THE KEY ATTRIBUTES OF OBJECT ORIENTED PROGRAMMING:
 Object
 Class
 Data Abstraction and Encapsulation
 Dynamic Binding
 Message Passing
 Inheritance
 Polymorphism
Object:
Object is a collection of number of entities. Object take up space in the memory.
Objects are instances of classes. When a program is executed, the objects interact by
sending messages to one another. Each object contains data and code to manipulate the
data. Objects can interact without having no details of each other’s data or code.
Class:
Class is a collection of objects of similar type. Objects are variables of the type
class. Once a class has been defined, we can create any number of objects belonging to
that class.
Ex: banana, orange are the objects of class Fruit.
Fruit mango;
By above mango object is created for class Fruit.
Data Abstraction and Encapsulation:
Combining data and functions into a single unit called class and the process is
known as Encapsulation. Data encapsulation is important feature of a class. Class contains
both data and functions. Data is not accessible from the outside world and only those
functions which are present in the class can access the data. The insulation of the data
from direct access by the program is called data hiding or data abstraction. Hiding the
complexity of program is called abstraction only essential features are represented. In
short we can say that internal working is hidden.
Dynamic Binding:
Refers to linking of function call with function defination is called binding and when
it is take place at run time called dynamic binding.

1
JAVA PROGRAMMING

Message Passing:
The process by which one object can interact with other object is called message
passing.
Inheritance:
It is the process by which object of one class aquire the properties or features of
objects of another class. The concept of inheritance provide the idea of reusability means
we can add additional features to an existing class without Modifying it. This is possible by
driving a new class from the existing one. The new class will have the combined features
of both the classes.
Example: Parrot is a part of the class flying bird which is again a part of the class bird.
Polymorphism:
A Greek term means ability to take more than one form. An operation may exhibit
different behaviors in different instances. The behavior depends upon the types of data
used in the operation.
Example:
 Operator Overloading
You can redefine or overload most of the built in operators.
 Function Overloading
You can have multiple definitions for the same function name in the same scope. The
definition of the function must differ from each other by the type and/or the number of
arguments in the argument list but not only by return type.

SIMPLE JAVA PROGRAM:


import java.io.*;
class Example
{
public static void main(String args[])
{
System.out.println(“This is a simple java program”);
}
}

2
JAVA PROGRAMMING

JAVA FEATURES OR JAVA BUZZWORDS


Following are the features or buzzwords of Java language which made it popular:
1.Simple
2.Secure
3.Portable
4.Object-Oriented
5.Robust
6.Multithreaded
7.Architecture neutral
8.Interpreted
9.High Performance
10.Distributed
11.Dynamic
Simple:
•Java easy to learn
•It is easy to write programs using Java
•Expressiveness is more in Java.
•Most of the complex or confusing features in C++ are removed in Java like pointers etc..
Secure:
•Java provides data security through encapsulation.
•Also we can write applets in Java which provides security.
•An applet is a small program which can be downloaded from one computer to another
automatically.
•There is no need to worry about applets accessing the system resources which may
compromise security.
•Applets are run within the JVM which protects from unauthorized or illegal access to
system resources.
Portable:
•Applications written using Java are portable in the sense that they can be executed on
any kind of computer containing any CPU or any operating system.
•When an application written in Java is compiled, it generates an intermediate code file
called as “bytecode”.
•Bytecode helps Java to achieve portability.
•This bytecode can be taken to any computer and executed directly.

3
JAVA PROGRAMMING

Object - Oriented:
•Java follows object oriented model.
•So, it supports all the features of object oriented model like:
Encapsulation
Inheritance
Polymorphism
Abstraction
Robust:
•A program or an application is said to be robust(reliable) when it is able to give some
response in any kind of context.
•Java’s features help to make the programs robust. Some of those features are:
1. Type checking
2. Exception handling
Multithreaded:
•Java supports multithreading which is not supported by C and C++.
•A thread is a light weight process.
•Multithreading increases CPU efficiency.
•A program can be divided into several threads and each thread can be executed
concurrently or in parallel with the other threads.
•Real world example for multithreading is computer. While we are listening to music, at
the same time we can write in a word document or play a game.
Architecture - Neutral:
•Byte code helps Java to achieve portability.
•Byte code can be executed on computers having any kind of operating system or any
kind of CPU.
•Since Java applications can run on any kind of CPU, Java is architecture – neutral.
Interpreted and High Performance:
•In Java 1.0 version there is an interpreter for executing the byte code. As interpreter is
quite slow when compared to a compiler, java programs used to execute slowly.
•After Java 1.0 version the interpreter was replaced with JIT(Just-In-Time) compiler.
•JIT compiler uses Sun Micro system’s Hot Spot technology.
•JIT compiler converts the byte code into machine code piece by piece and caches them
for future use.
•This enhances the program performance means it executes rapidly.
Distributed:
4
JAVA PROGRAMMING

•Java supports distributed computation using Remote Method Invocation (RMI) concept.
•The server and client(s) can communicate with another and the computations can be
divided among several computers which makes the programs to execute rapidly.
•In distributed systems, resources are shared.
Dynamic:
•The Java Virtual Machine(JVM) maintains a lot of runtime information about the program
and the objects in the program.
•Libraries are dynamically linked during runtime.
•So, even if you make dynamic changes to pieces of code, the program is not effected.
THE JAVA KEYWORDS:
Here is a list of keywords in the Java programming language. You cannot use any of
the following as identifiers in your programs. The keywords const and goto are reserved,
even though they are not currently used. true, false, and null might seem like keywords,
but they are actually literals; you cannot use them as identifiers in your programs.
1. abstract 17. extends 34. protected
2. assert (since Java 18. final 35. public
1.4) 19. finally 36. return
3. boolean 20. float 37. short
4. break 21. for 38. static
5. byte 22. goto (not used) 39. strictfp (since Java 1.2)
6. case 23. if 40. super
7. catch 24. implements 41. switch
8. char 25. import 42. synchronized
9. class 26. instanceof 43. this
10. const (not used) 27. int 44. throw
11. continue 28. interface 45. throws
12. default 29. long 46. transient
13. do 30. native 47. try
14. double 31. new 48. void
15. else 32. package 49. volatile
16. enum (since Java 33. private 50. while
5.0)
1.abstract: -

5
JAVA PROGRAMMING

Java provides abstract keyword to signify something empty. By empty we mean that it
has no definition or implementation. Keyword abstract is used before the classes and
methods. At the time of declaring a class we mark it as abstract. An abstract class cannot
be instantiated. It means an abstract class cannot have Objects. By abstract method, we
mean that method doesn't have any body. An abstract method doesn't have any
statements to execute. Classes that contain abstract method must also be assigned as
abstract class and implementation to their abstract method must be provided by
extending those classes. If subclasses fail to provide implementation to super-class
abstract methods, than they are also marked as abstract.
2. assert: -
Java provides us with a debugging keyword called as assert. In Java, assert is a normal
Java statement which a programmer puts in the code, that he/she thinks will always be
true. Generally, assert statements are being used by the programmer for the debugging
purpose. Assertion statements can be turned on or off. While running a program if we
enable assertion then wherever our assert statement gets failed Assertion Error is thrown
by the program and whole program gets terminated. Generally, assertions are placed by
programmer in the code where he believes that statement will be true. After enabling
assertion if there is a failure, programmer gets an idea that in code there is some bug. The
code fails with an Assertion Error.
3. boolean: -
A boolean keyword in Java is a data type for a variable which can store two values, true
or false. Generally, boolean keyword is a data type which has size of 1 bit. In Java I am not
sure about the size that whether it store 1 bit or not.
4. break: -
In Java, 'break' keyword is of quite high importance. As the name suggest, break
statement breaks code from one point and transfer flow to other part of program to
execute. Generally let say in if block you have placed a break statement. If your code
enters if statement an encounters break statement it will stop executing further if block
and come out of if block and continue to execute.
5. byte :-
In Java, byte keyword is used as a data type for storing 8 bits of information for an
integer. If it’s used before a method definition than that method, when called will always
return a byte value.
6. case :-

6
JAVA PROGRAMMING

In Java, case keyword is used within switch statements. A condition in switch


statement is compared with the cases in switch statement. Whatever case matches with
the switch expression that case is executed.
7. catch :-
In Java, catch keyword has a group of statements that catches exception, if there is
any exception in try block proceeding to it. The statements have a way to deal with the
exception or have a way to let programmer know that something is needed to be correct.
8. char :-
In Java, char keyword is used as a data type which can store 16 bit Unicode
character. If the keyword is placed before method declaration than the method upon
execution returns a value which is a char.
9. class :-
In Java, class keyword is used to define a class. Generally a class acts as a blue print
for an object. It defines implementation for the object. It has statements defining
variables, methods, inner classes etc. An Object when instantiated for a particular class
has all the physical implementation of what is defined in the class.
10. const :-
It is a reserved keyword in Java but it has no use in Java and Java has provided it no
function to perform.
11. continue :-
In Java, the continue keyword is used when we want rest of the statement after
continue keyword to get skipped and want program to continue with the next iteration.
12. default :-
In Java, default keyword is used within switch statement. It is used their optionally,
if no Java case matches with the expression than the default case is executed by the
program.
13. do :-
In Java, do keyword is used to implement do-while loop. Generally, do keyword is
used when we want to loop a block of statement once. After that the boolean condition
gets evaluated, if condition is yes the loop execute again, but if condition comes out to be
false the loop exits.
14. double :-
In Java, double keyword is used as a data type for storing 64 bits of information for
a float type. If it’s used before a method definition than that method when called will

7
JAVA PROGRAMMING

always return a double value.


15. else :-
In Java, else keyword is used along with if keyword to create an if-else statement.
Generally, a condition is evaluated in if block brackets. If the condition evaluates to true if
block body gets executed. If the condition is evaluated to false else block body gets
executed.
16. enum :-
It is used in Java language to declare a data type consisting of a set of named
values. They are constants.
17. extends :-
In Java, extends keyword is used specify the super class of a subclass, also in
interface declaration to specify one or more super interfaces. If we take an example say
let say class A extends class B, here class A adds functionality to class B by adding fields
or methods. It goes same with interfaces.
18. final :-
Generally, final keyword is used to make elements constant. That is once assigned
cannot be changed. A final class cannot be sub-classed. A final variable cannot be
assigned a new value after it has been assigned to a value. A final method cannot be
overridden.

19. finally :-
In Java, finally keyword is used to define a block of statements after try to catch
blocks. This block executes after try block, or after catch block, or before any return
statement.
20. float :-
In Java, float keyword is used as a data type for storing 32 bits of information for a
float type. If it’s used before a method definition than that method when called will always
return a float value.
21. for :-
In Java, for keyword is used to create looping statement that is for loop. In this for
loop a counter variable is initialized, than a boolean condition is evaluated and compared
with counter variable or any expression which turns out to either true or false. If the
condition comes out to be true a block of statements following for keyword executes, if

8
JAVA PROGRAMMING

condition comes out to be false for loop terminates.


22. goto :-
In Java, a goto keyword is a reserved keyword which is not used in the Java
language and has no function provided to it.
23. if :-
In Java, if keyword is used (optionally) along with else keyword to create an if-else
statement. Generally, a condition is evaluated in if block brackets. If the condition
evaluates to true if block body gets executed. If the condition is evaluated to false else
block body gets executed.
24. implements :-
In Java, implements keywords is used in class declaration. Generally, implements
keyword implements functionality of interfaces. Interfaces are abstract in nature; their
functionality is implemented in the class which implements it.
25. import :-
In Java, import statement is used at the start of a Java file, just after package
declaration. Generally, import statement gets those classes in a program whose
functionality we want to use in the program. It is also used in importing static members.
26. instanceof :-
In Java, instanceof operator is a binary operator which is used to test an IS-A
relationship between a class and object. Object is first operand and Class or Interface is a
second operand.
27. int :-
In Java, int keyword is used as a data type for storing 32 bits of information for an
integer type. If it’s used before a method definition than that method when called will
always return an int value.

28. interface :-
In Java, interface is a special type of structure which contains abstract methods,
constant fields which are generally static or final.
29. long :-
In Java, long keyword is used as a data type for storing 64 bits of information for an
integer type. If it’s used before a method definition than that method when called will
always return a long value.
30. native :-

9
JAVA PROGRAMMING

This keyword is generally used in declaring method signifying that method's


implementation is not in the same source file but in different source file and in different
language too.
31. new :-
Java has a keyword called as new, which has been used to create a new instance of
a class on heap. It is used is object creation and providing memory to it.
32. package :-
Packages have been created by the package keyword. In the package classes are
kept which constitute a relation between each other.
33. private :-
In Java, private keyword can be used in declaration of methods, fields, inner class.
This makes the methods, fields and inner class access to own class members.
34. protected :-
In Java, protected keyword can be used in declaration of methods, fields, inner
class. This makes the methods, fields and inner class access to own class members, to sub
class and classes of same package.
35. public :-
In Java, public keyword can be used before class, methods, fields. This makes the
class , methods and fields accessible from any other class.
36. return :-
In Java, return keyword is used to pass a value from a method to caller method. It
also signifies end of execution of a method.
37. short :-
In Java, short keyword is mainly used when we want to declare a field that can hold
16 bit of integer data. It is also placed before method declaration which signifies that
method will return only short integer.

38. static :-
In Java, static keyword is used when you want to declare method, fields and inner
class as class members rather object members, generally static members belong to a
class rather than instance of that class. Therefore only one copy is made for them and
used by the class as its own implementation.
39. strictfp :-

10
JAVA PROGRAMMING

To ensure portability of floating point we ensure that they are platform


independent.
40. super :-
In Java, super keywords is used to access overridden methods and hidden members
of super class by its subclass. It is also used in constructor of a subclass to pass control
over super class constructor.
41. switch :-
In Java switch keyword is used to have multi-decision making statements. Generally
switch is mostly used with keywords case, break and default. This decision making block
evaluates an expression first. After the expression is evaluated the value is compared with
various case statements. Any value that matches with the expression, case associated
with it gets executed. If no expression matches the default case gets executed.
42. synchronized :-
In java, synchronized keyword is used before the method declaration and before
block of code to get mutual lock for an object. It means that the method or block of code
gets locked by the object till it gets fully unlocked or gets fully executed by that object.
Generally classes, fields and interfaces cannot be declared as synchronized. The static
method gets code synchronization by class itself.
43. this :-
In Java, this keyword is used as a reference to currently executable object.
Generally if we want to access class members we can use this keyword to access them. If
we want to refer to a current object we use this keyword. We also use this keyword to
transfer control from one constructor to another in the same class.
44. throw :-
In Java, when we want to throw a declared exception, the execution points to the
catch block which has provided statements to overcome the exception. If no catch block is
declared in the current method than the exception is passed to the calling method. It
continues till it found exception handler. If no exception handler is found over the stack
that exception is then transferred to the Uncaught Exception handler.

45. throws :-
In Java, we use throws keyword in the method declarations. If we get an exception
in a method and method has no implementation for that exception, than method throws

11
JAVA PROGRAMMING

an exception. The exception thrown has been handled by the method who has called to
current method in execution.
46. transient :-
Whenever we declare a variable as transient, that variable is not the part of Object
serialization. When an object gets saved through default serialization all the non-transient
variable retain their value after deserialization. If you want the variable should have
default value after deserialization than make it transient.
47. try :-
In Java, whenever we want to do exception handling we use try keyword. Generally
try block is used where we are sure that exception can occur. In try block statements are
executed normally and as soon as exception occur it is handled my catch keyword
following try block. It must have at least one catch or finally block.
48. void :-
In Java, when we use void before any method declaration, we make sure that
method doesn't return any value.
49. volatile :-
In Java, volatile keyword provides a lock free mechanism. If a variable is assigned as
volatile than all the threads accessing it can modify its current value without keeping a
separate copy. A volatile keyword is accessed by all threads simultaneously. They operate
on current value of variable rather than cached value.
50. while :-
In Java, while keyword is used to create looping statement that is while loop. In this
while loop a boolean condition is evaluated and compared with counter variable or any
expression which turns out to either true or false. If the condition comes out to be true a
block of statements following while keyword executes, if condition comes out to be false
the while loop terminates.
51. false :-
In Java, false keyword is the literal for the data type Boolean. Expressions are
compared by this literal value.

52. null :-

12
JAVA PROGRAMMING

In Java, null keyword is the literal for the reference variable. Expressions are
compared by this literal value. It is a reserved keyword.
53. true :-
In Java, true keyword is the literal for the data type Boolean. Expressions are
compared by this literal value. - See more at: http://www.hubberspot.com/2012/03/top-50-
java-keywords-complete-reference.html#sthash.Fwpuhrxd.dpuf
IDENTIFIERS IN JAVA:
Identifiers are the names of variables, methods, classes, packages and interfaces.
Unlike literals they are not the things themselves, just ways of referring to them. In the
HelloWorld program, HelloWorld, String, args, main and println are identifiers.
Identifiers must be composed of letters, numbers, the underscore _ and the dollar
sign $. Identifiers may only begin with a letter, the underscore or a dollar sign.
Each variable has a name by which it is identified in the program. It's a good idea to
give your variables mnemonic names that are closely related to the values they hold.
Variable names can include any alphabetic character or digit and the underscore _. The
main restriction on the names you can give your variables is that they cannot contain any
white space. You cannot begin a variable name with a number. It is important to note that
as in C but not as in Fortran or Basic, all variable names are case-sensitive. MyVariable is
not the same as myVariable. There is no limit to the length of a Java variable name. The
following are legal variable names:
 MyVariable
 myvariable
 MYVARIABLE
 x
 i
 _myvariable
 $myvariable
 _9pins
 andros
DATA TYPES:
As with all modern programming languages, Java supports several types of data.
You may use these types to declare variables and to create arrays. As you will see, Java’s
approach to these items is clean, efficient, and cohesive.
Java Is a Strongly Typed Language

13
JAVA PROGRAMMING

It is important to state at the outset that Java is a strongly typed language. Indeed,
part of Java’s safety and robustness comes from this fact. Let’s see what this means. First,
every variable has a type, every expression has a type, and every type is strictly defined.
Second, all assignments, whether explicit or via parameter passing in method calls, are
checked for type compatibility. There are no automatic coercions or conversions of
conflicting types as in some languages. The Java compiler checks all expressions and
parameters to ensure that the types are compatible. Any type mismatches are errors that
must be corrected before the compiler will finish compiling the class.
The Primitive Types:
Java defines eight primitive types of data: byte, short, int, long, char, float, double,
and boolean.
The primitive types are also commonly referred to as simple types, and both terms will be
used in this book. 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.
You can use these types as-is, or to construct arrays or your own class types. Thus, they
form the basis for all other types of data that you can create.
The primitive types represent single values—not complex objects. Although Java
isotherwise completely object-oriented, the primitive types are not. They are analogous to
the simple types found in most other non–object-oriented languages. The reason for this is
efficiency.Making the primitive types into objects would have degraded performance too
much.
The primitive types are defined to have an explicit range and mathematical
behavior. Languages such as C and C++ allow the size of an integer to vary based upon
the dictates of the execution environment. However, Java is different. Because of Java’s
portability requirement, all data types have a strictly defined range.
For example, an int is always 32 bits,

14
JAVA PROGRAMMING

Regardless of the particular platform. This allows programs to be written that are
guaranteed to run without porting on any machine architecture. While strictly specifying
the size of an integer may cause a small loss of performance in some environments, it is
necessary in order to achieve portability.
Let’s look at each type of data in turn.

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. Many other computer languages support both signed and
unsigned integers. However, Java’s designers felt that unsigned integers were
unnecessary. Specifically, they felt that the concept of unsigned was used mostly to
specify the behavior of the high-order bit, which defines the sign of an integer value. Java
manages the meaning of the high-order bit differently, by adding a special “unsigned right
shift” operator. Thus, the need for an unsigned integer type was eliminated.
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 Java run-time environment is free to use whatever size it wants, as long as the types
behave as you declared them. The width and ranges of these integer types vary widely, as
shown in this table:

Let’s look at each type of integer.


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. They are also useful when you’re working with raw binary data that
may not be directly compatible with Java’s other built-in types.
Byte variables are declared by use of the byte keyword.
For example, the following declares two byte variables called b and c:

15
JAVA PROGRAMMING

byte b, c;
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;
int:
The most commonly used integer type is int. It is a signed 32-bit type that has a
range from 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. Although you might think
that using a byte or short would be more efficient than using an int in situations in which
the larger range of an int is not needed, this may not be the case. The reason is that when
byte and short values are used in an expression they are promoted to int when the
expression is evaluated. Therefore, int is often the best choice when an integer is needed.
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, here is a program that
computes the number of miles that light will travel in a specified number of days.
// 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.");
16
JAVA PROGRAMMING

}
}
This program generates the following output:
In 1000 days light will travel about 16070400000000 miles.
Clearly, the result could not have been held in an int variable.
Floating-Point Types:
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. For example, calculations such as square
root, or transcendental such as sine and cosine, result in a value whose precision requires
a floating-point type.
Java implements the standard (IEEE–754) set of floating-point types and operators. There
are two kinds of floating-point types, float and double, which represent single- and double-
precision numbers, respectively. Their width and ranges are shown here:

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. Variables of
type float are useful when you need a fractional component, but don’t require a large
degree of precision.
For example, float can be useful when representing dollars and cents.
Here are some example float variable declarations:
float hightemp, lowtemp;
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.
When you need to maintain accuracy many iterative calculations, or are manipulating
large-valued numbers, double is the best choice.
Here is a short program that uses double variables to compute the area of a circle:

17
JAVA PROGRAMMING

// 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);
}
}

Characters
In Java, the data type used to store characters is char.
Note: 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. There are
no negative chars.
The standard set of characters known as ASCII still ranges from 0 to 127 as always,
and the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255. Since Java is
designed to allow programs to be written for worldwide use, it makes sense that it would
use Unicode to represent characters. Of course, the use of Unicode is somewhat inefficient
for languages such as English, German, Spanish, or French, whose characters can easily
be contained within 8 bits.
But such is the price that must be paid for global portability.
Here is a program that demonstrates char variables:
// Demonstrate char data type.
class CharDemo {
public static void main(String args[]) {
char ch1, ch2;
18
JAVA PROGRAMMING

ch1 = 88; // code for X


ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
This program displays the following
output:
ch1 and ch2: X Y
Notice that ch1 is assigned the value 88, which is the ASCII (and Unicode) value that
corresponds to the letter X. As mentioned, the ASCII character set occupies the first 127
values in the Unicode character set. For this reason, all the “old tricks” that you may have
used with characters in other languages will work in Java, too.
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. For example, you can
add two characters together, or increment the value of a character variable. Consider the
following program:
// 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);
}
}
The output generated by this program is shown here:
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.
Booleans

19
JAVA PROGRAMMING

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.
Here is a program that demonstrates the boolean type:
// 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);
// a boolean value can control the if statementChapter 3: Data Types, Variables, and
Arrays 39
if(b) System.out.println("This is executed.");
b = false;
if(b) System.out.println("This is not executed.");
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}
The output generated by this program is shown here:
b is false
b is true
This is executed.
10 > 9 is true
There are three interesting things to notice about this program.
First, as you can see, when a boolean value is output by println( ), “true” or “false” is
displayed. Second, the value of a boolean variable is sufficient, by itself, to control the if
statement. There is no need to write an if statement like this:
if(b == true) ...

20
JAVA PROGRAMMING

Third, the outcome of a relational operator, such as <,isa boolean value. This is why the
expression 10>9 displays the value “true.” Further, the extra set of parentheses around
10>9 is necessary because the + operator has a higher precedence than the >.
Escape Sequence: Java supports all escape sequence which is supported by C/ C++. A
character preceded by a backslash (\) is an escape sequence and has special
meaning to the compiler. When an escape sequence is encountered in a print
statement, the compiler interprets it accordingly.

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. These elements are
examined next.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a
variable
declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java’s atomic types, or the name of a class or interface. (Class and
interface types are discussed later in Part I of this book.) The identifier is the name of the
variable. You can initialize the variable by specifying an equal sign and a value. Keep in
mind that the initialization expression must result in a value of the same (or compatible)
type as that specified for the variable. To declare more than one variable of the specified
type, use a comma-separated list.
21
JAVA PROGRAMMING

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'.
The identifiers that you choose have nothing intrinsic in their names that indicates their
type. Java allows any properly formed identifier to have any declared type.
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java
allows variables to be initialized dynamically, using any expression valid at the time the
variable is declared.
For example, here is a short program that computes the length of the hypotenuse of a
right triangle given the lengths of its two opposing sides:
// Demonstrate dynamic initialization.
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);
}
}
Here, three local variables—a, b, and c—are declared. The first two, a and b, are
initialized by constants. However, c is initialized dynamically to the length of the
hypotenuse (using the Pythagorean theorem). The program uses another of Java’s built-in
methods, sqrt( ), which is a member of theMath class, to compute the square root of its
argument. The key point here is that the initialization expression may use any element
valid at the time of the initialization, including calls to methods, other variables, or literals.
The Scope and Lifetime of Variables
So far, all of the variables used have been declared at the start of
themain( )method. However, 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
22
JAVA PROGRAMMING

scope determines what objects are visible to other parts of your program. It also
determines the lifetime of those objects.
Many other computer languages define two general categories of scopes: global and
local.
However, these traditional scopes do not fit well with Java’s strict, object-oriented model.
In Java, the two major scopes are those defined by a class and those defined by a method.
Even this distinction is somewhat artificial. However, since the class scope has several
unique properties and attributes that do not apply to the scope defined by a method, this
distinction makes some sense. Because of the differences, a discussion of class scope (and
variables declared within it) is deferred, when classes are described.
For now, we will only examine the scopes defined by or within a method.
The scope defined by a method begins with its opening curly brace. However, if that
method has parameters, they too are included within the method’s scope.
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.
Indeed, the scope rules provide the foundation for encapsulation.
Scopes can be nested.
For example, each time you create a block of code, you are creating a new, nested
scope. When this occurs, the outer scope encloses the inner scope. This means that
objects declared in the outer scope will be visible to code within the inner scope. However,
the reverse is not true. Objects declared within the inner scope will not be visible outside
it.
To understand the effect of nested scopes, consider the following program:
// Demonstrate block scope.
class Scope {
public static void main(String args[]) {
int x; // known to all code within main
x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here.
System.out.println("x and y: " + x + " " + y);

23
JAVA PROGRAMMING

x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
System.out.println("x is " + x);
}
}
As the comments indicate, the variable x is declared at the start of main( )’s scope
and is accessible to all subsequent code within main( ). Within the if block, y is declared.
Since a block defines a scope, y is only visible to other code within its block. This is why
outside of its block, the line y = 100; is commented out.
Within a block, variables can be declared at any point, but are valid only after they
are declared. Thus, if you define a variable at the start of a method, it is available to all of
the code within that method. Conversely, if you declare a variable at the end of a block, it
is effectively useless, because no code will have access to it.
For example, this fragment is invalid because count cannot be used prior to its
declaration:
// This fragment is wrong!
count = 100; // oops! cannot use count before it is declared!
int count;
Here is another important point to remember:
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, consider the next program.
// 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

24
JAVA PROGRAMMING

System.out.println("y is: " + y); // this always prints -1


y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program is shown here:
y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100
As you can see, y is reinitialized to –1 each time the inner for loop is entered. Even though
it is subsequently assigned the value 100, this value is lost.
One last point: Although blocks can be nested, you cannot declare a variable to have the
same name as one in an outer scope. For example, the following program is illegal:
// This program will not compile
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{ // creates a new scope
int bar = 2; // Compile-time error – bar already defined!
}
}
}

Type Conversion and Casting:


If you have previous programming experience, then you already know that it is
fairly 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
25
JAVA PROGRAMMING

instance, there is no automatic conversion defined from double to byte. Fortunately, it is


still possible to obtain a conversion between in compatible types. To do so, you must use a
cast, which performs an explicit conversion between incompatible types.
Let’s look at both automatic type conversions and casting.
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.
As mentioned earlier, Java also performs an automatic type conversion when storing a
literal integer constant into variables of type byte, short, long,or char.
Casting Incompatible Types
Although the automatic type conversions are helpful, they will not fulfill all needs.
For example, what if you want to assign an int value to a byte variable? This conversion
will not be performed automatically, because a byte is smaller than an int. This kind of
conversion is sometimes called a narrowing conversion, since you are explicitly making
the value narrower so that it will fit into the target type.
To create a conversion between two incompatible types, you must use a cast. A
cast is simply an explicit type conversion. It has this 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;
// ...

26
JAVA PROGRAMMING

b = (byte) a;
Adifferent 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.
The following program demonstrates some type conversions that require casts:
// 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);
}
}
This program generates the following 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.

27
JAVA PROGRAMMING

d and b 323.142 67Let’s look at each conversion. When the value 257 is cast into a byte
variable, the result is the remainder of the division of 257 by 256 (the range of a byte),
which is 1 in this case.
When the d is converted to an int, its fractional component is lost. When d is converted to
a byte, its fractional component is lost, and the value is reduced modulo 256, which in this
case is 67.
Conclusion of Type Conversion:
• Size Direction of Data Type
– Widening Type Conversion (Casting down)
• Smaller Data Type à Larger Data Type
– Narrowing Type Conversion (Casting up)
• Larger Data Type à Smaller Data Type
• Conversion done in two ways
– Implicit type conversion
• Carried out by compiler automatically
– Explicit type conversion
• Carried out by programmer using casting

byte
byte ->

– -> short,
short, int,
int, long,
long, float,
Widening Type Converstion
float, double
double
Implicit conversion by compiler automatically

short
short -> -> int,
int, long,
long, float,
float, double
double
char
char -> -> int,
int, long,
long, float,
float, double
double
int
int ->
-> long,
long, float,
float, double
double

long
long ->-> float,
float, double
Narrowing Type Conversion
double
– float
float ->-> double
double
Programmer should describe the conversion explicitly

28
byte
JAVA ->
byte -> char
char
PROGRAMMING

short
short ->-> byte,
byte, char
char
char
char ->-> byte,
byte, short
short
int
int ->
-> byte,
byte, short,
short, char
char
long
long ->-> byte,
byte, short,
short, char,
char, intint

float
float ->
-> byte,
byte, short,
short, char,
char, int,
int, long
byte and short are always promoted to int long
double
double ->

-> byte,
byte, short,
short, char,
char, int,
int, long,
long, float
float
if one operand is long, the whole expression is promoted to long
• if one operand is float, the entire expression is promoted to float
• if any operand is double, the result is double
• General form: (targetType) value
• Examples:
• 1) integer value will be reduced module bytes range:
int i;
byte b = (byte) i;
• 2) floating-point value will be truncated to integer value:
float f;
int i = (int) f;
OPERATORS:
Java provides a rich set of operators to manipulate variables. We can divide all the
Java operators into the following groups:
 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Assignment Operators
 Misc Operators
The Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that
they are used in algebra. The following table lists the arithmetic operators:
Assume integer variable A holds 10 and variable B holds 20, then:
Operator Description Example

29
JAVA PROGRAMMING

+ Addition - Adds values on either side of the operator A + B will give 30


Subtraction - Subtracts right hand operand from left hand
- A - B will give -10
operand
A * B will give
* Multiplication - Multiplies values on either side of the operator
200
/ Division - Divides left hand operand by right hand operand B / A will give 2
Modulus - Divides left hand operand by right hand operand
% B % A will give 0
and returns remainder
++ Increment - Increases the value of operand by 1 B++ gives 21
-- Decrement - Decreases the value of operand by 1 B-- gives 19

The Relational Operators:


There are following relational operators supported by Java language
Assume variable A holds 10 and variable B holds 20, then:
Operator Description Example
Checks if the values of two operands are equal or not, if yes (A == B) is not
==
then condition becomes true. true.
Checks if the values of two operands are equal or not, if
!= (A != B) is true.
values are not equal then condition becomes true.
Checks if the value of left operand is greater than the value (A > B) is not
>
of right operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value of
< (A < B) is true.
right operand, if yes then condition becomes true.
Checks if the value of left operand is greater than or equal to
(A >= B) is not
>= the value of right operand, if yes then condition becomes
true.
true.
Checks if the value of left operand is less than or equal to the
<= (A <= B) is true.
value of right operand, if yes then condition becomes true.

The Bitwise Operators:


Java defines several bitwise operators, which can be applied to the integer types,
long, int, short, char, and byte.

30
JAVA PROGRAMMING

Bitwise operator works on bits and performs bit-by-bit operation. Assume if A = 60; and B
= 13; now in binary format they will be as follows:
A = 0011 1100
B = 0000 1101
-----------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The following table lists the bitwise operators:
Assume integer variable A holds 60 and variable B holds 13 then:

Operator Description Example


(A & B) will give
Binary AND Operator copies a bit to the result if it exists in
& 12 which is 0000
both operands.
1100
(A | B) will give
| Binary OR Operator copies a bit if it exists in either operand. 61 which is 0011
1101
(A ^ B) will give
Binary XOR Operator copies the bit if it is set in one operand
^ 49 which is 0011
but not both.
0001
(~A ) will give -61
which is 1100
Binary Ones Complement Operator is unary and has the 0011 in 2's
~
effect of 'flipping' bits. complement form
due to a signed
binary number.
A << 2 will give
Binary Left Shift Operator. The left operands value is moved
<< 240 which is
left by the number of bits specified by the right operand.
1111 0000
Binary Right Shift Operator. The left operands value is moved A >> 2 will give
>>
right by the number of bits specified by the right operand. 15 which is 1111

31
JAVA PROGRAMMING

Shift right zero fill operator. The left operands value is moved A >>>2 will give
>>> right by the number of bits specified by the right operand and 15 which is 0000
shifted values are filled up with zeros. 1111

The Logical Operators:


The following table lists the logical operators:
Assume Boolean variables A holds true and variable B holds false, then:
Operator Description Example
Called Logical AND operator. If both the operands are non-
&& (A && B) is false.
zero, then the condition becomes true.
Called Logical OR Operator. If any of the two operands are
|| (A || B) is true.
non-zero, then the condition becomes true.
Called Logical NOT Operator. Use to reverses the logical state
! of its operand. If a condition is true then Logical NOT operator !(A && B) is true.
will make false.

The Assignment Operators:


There are following assignment operators supported by Java language:
Operator Description Example
C = A + B will
Simple assignment operator, Assigns values from right side
= assign value of A
operands to left side operand
+ B into C
C += A is
Add AND assignment operator, It adds right operand to the
+= equivalent to C =
left operand and assign the result to left operand
C+A
C -= A is
Subtract AND assignment operator, It subtracts right operand
-= equivalent to C =
from the left operand and assign the result to left operand
C-A
C *= A is
Multiply AND assignment operator, It multiplies right operand
*= equivalent to C =
with the left operand and assign the result to left operand
C*A
/= Divide AND assignment operator, It divides left operand with C /= A is
the right operand and assign the result to left operand equivalent to C =

32
JAVA PROGRAMMING

C/A
C %= A is
Modulus AND assignment operator, It takes modulus using
%= equivalent to C =
two operands and assign the result to left operand
C%A
C <<= 2 is same
<<= Left shift AND assignment operator
as C = C << 2
C >>= 2 is same
>>= Right shift AND assignment operator
as C = C >> 2
C &= 2 is same
&= Bitwise AND assignment operator
as C = C & 2
C ^= 2 is same
^= bitwise exclusive OR and assignment operator
as C = C ^ 2
C |= 2 is same as
|= bitwise inclusive OR and assignment operator
C=C|2
Misc Operators:
There are few other operators supported by Java Language.
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of
three operands and is used to evaluate Boolean expressions. The goal of the operator is to
decide which value should be assigned to the variable. The operator is written as:
variable x = (expression) ? value if true : value if false
Following is the example:
public class Test {

public static void main(String args[]){


int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;


System.out.println( "Value of b is : " + b );
}

33
JAVA PROGRAMMING

}
This would produce the following result:
Value of b is : 30
Value of b is : 20
instanceof Operator:
This operator is used only for object reference variables. The operator checks
whether the object is of a particular type(class type or interface type). instanceof operator
is written as:
( Object reference variable ) instanceof (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check
for the class/interface type on the right side, then the result will be true. Following is the
example:
public class Test {

public static void main(String args[]){


String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
System.out.println( result );
}
}
This would produce the following result:
true
This operator will still return true if the object being compared is the assignment
compatible with the type on the right. Following is one more example:
class Vehicle {}

public class Car extends Vehicle {


public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result );
}
}
34
JAVA PROGRAMMING

This would produce the following result:


true
Precedence of Java Operators:
Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher precedence than
others; for example, the multiplication operator has higher precedence than the addition
operator:
For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Relational > >= < <= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

PROGRAM CONTROL STATEMENTS:


Control statements are the statements which alter the flow of execution and
provide better control to the programmer on the flow of execution. In Java control

35
JAVA PROGRAMMING

statements are categorized into selection control statements, iteration control statements
and jump control statements.
 Java’s Selection Statements:
Java supports two selection statements: if and switch. These statements allow
us to control the flow of program execution based on condition.
if Statement:
if statement performs a task depending on whether a condition is true or false.
Syntax: 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.
Program : Write a program to find biggest of three numbers.
//Biggest of three numbers
class BiggestNo
{ public static void main(String args[])
{ int a=5,b=7,c=6;
if ( a > b && a>c)
System.out.println ("a is big");
else if ( b > c)
System.out.println ("b is big");
else
System.out.println ("c is big");
}
}
Output:
D:/kumar>javac BiggestNo.java
D:/kumar>java BiggestNo
b is big
D:/kumar>
36
JAVA PROGRAMMING

Switch Statement:
When there are several options and we have to choose only one option from
the available ones, we can use switch statement.
Syntax: switch (expression)
{ case value1: //statement sequence
break;
case value2: //statement sequence
break;
………….…..
case valueN: //statement sequence
break;
default: //default statement sequence
}
Here, depending on the value of the expression, a particular corresponding case will be
executed.
Program : Write a program for using the switch statement to execute a particular task
depending on color value.
//To display a color name depending on color value
class ColorDemo
{ public static void main(String args[])
{ char color = ‘r’;
switch (color)
{ case ‘r’: System.out.println (“red”); break;
case ‘g’: System.out.println (“green”); break;
case ‘b’: System.out.println (“blue”); break;
case ‘y’: System.out.println (“yellow”); break;
case ‘w’: System.out.println (“white”); break;
default: System.out.println (“No Color Selected”);
}
}
}
Output:
D:/kumar>javac ColorDemo.java
D:/kumar>java ColorDemo
37
JAVA PROGRAMMING

red
D:/kumar>

 Java’s Iteration Statements:


Java’s iteration statements are for, while and do-while. These statements are used
to repeat same set of instructions specified number of times called loops.
A loop repeatedly executes the same set of instructions until a termination condition is
met.
while Loop:
while loop repeats a group of statements as long as condition is true. Once
the condition is false, the loop is terminated. In while loop, the condition is tested first; if
it is true, then only the statements are executed. while loop is called as entry control loop.
Syntax: while (condition)
{
statements;
}
Program : Write a program to generate numbers from 1 to 20.
//Program to generate numbers from 1 to 20.
class Natural
{ public static void main(String args[])
{ int i=1;
while (i <= 20)
{ System.out.print (i + “\t”);
i++;
}
}
}
Output:
D:/kumar>javac Natural.java
D:/kumar>java Natural
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
D:/kumar>

38
JAVA PROGRAMMING

do-while Loop:
do…while loop repeats a group of statements as long as condition is
true. In do...while loop, the statements are executed first and then the condition is tested.
do…while loop is also called as exit control loop.

Syntax: do
{
statements;
} while (condition);
Program : Write a program to generate numbers from 1 to 20.
//Program to generate numbers from 1 to 20.
class Natural1
{ public static void main(String args[])
{ int i=1;
do
{ System.out.print (i + “\t”);
i++;
} while (i <= 20);
}
}
Output:
D:/kumar>javac Natural1.java
D:/kumar>java Natural1
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
D:/kumar>

for Loop:
The for loop is also same as do…while or while loop, but it is more compact
syntactically. The for loop executes a group of statements as long as a condition is true.
Syntax: for (expression1; expression2; expression3)
{ statements;
}

39
JAVA PROGRAMMING

Here, expression1 is used to initialize the variables, expression2 is used for


condition
checking and expression3 is used for increment or decrement variable value.

Program : Write a program to generate numbers from 1 to 20.


//Program to generate numbers from 1 to 20.
class Natural2
{ public static void main(String args[])
{ int i;
for (i=1; i<=20; i++)
System.out.print (i + “\t”);
}
}
Output:
D:/kumar>javac Natural2.java
D:/kumar>java Natural2
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
D:/kumar>

· Java’s Jump Statements:


Java supports three jump statements: break, continue and return.
These statements transfer control to another part of the program.
break:
Ø break can be used inside a loop to come out of it.
Ø break can be used inside the switch block to come out of the switch block.
Ø break can be used in nested blocks to go to the end of a block. Nested blocks
represent a block written within another block.
Syntax: break; (or) break label;//here label represents the name of the block.
Program : Write a program to use break as a civilized form of goto.
40
JAVA PROGRAMMING

//using break as a civilized form of goto


class BreakDemo
{ public static void main (String args[])
{ boolean t = true;
first:
{
second:
{
third:
{
System.out.println (“Before the break”);
if (t) break second; // break out of second block
System.out.println (“This won’t execute”);
}
System.out.println (“This won’t execute”);
}
System.out.println (“This is after second block”);
}
}
}
Output:
D:/kumar>javac BreakDemo.java
D:/kumar>java BreakDemo
Before the break
This is after second block
D:/kumar>
continue:
This statement is useful to continue the next repetition of a loop/ iteration.
When continue is executed, subsequent statements inside the loop are not executed.
Syntax: continue;
Program : Write a program to generate numbers from 1 to 20.
//Program to generate numbers from 1 to 20.
class Natural
{ public static void main (String args[])
41
JAVA PROGRAMMING

{ int i=1;
while (true)
{ System.out.print (i + “\t”);
i++;
if (i <= 20 )
continue;
else
break;
}
}
}
Output:
D:/kumar>javac Natural.java
D:/kumar>java Natural
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
D:/kumar>

return statement:
Ø return statement is useful to terminate a method and come back to the calling method.
Ø return statement in main method terminates the application.
Ø return statement can be used to return some value from a method to a calling method.
Syntax: return; (or)
return value; // value may be of any type

Program : Write a program to demonstrate return statement.


//Demonstrate return
class ReturnDemo
{ public static void main(String args[])
{ boolean t = true;
System.out.println (“Before the return”);
if (t)
return;
System.out.println (“This won’t execute”);
42
JAVA PROGRAMMING

}
}
Output:
D:/kumar>javac ReternDemo.java
D:/kumar>java ReturnDemo
Before the return
D:/kumar>

Note: goto statement is not available in java, because it leads to confusion and
forms infinite loops.

ARRAYS:
An array is a group of like-typed variables that are referred to by a common name. Arrays
of any type can be created and may have one or more dimensions. Aspecific element in an
array is accessed by its index. Arrays offer a convenient means of grouping related
information.
On which memory, arrays are created in java?
Arrays are created on dynamic memory by JVM. There is no question of static memory in
Java; everything (variable, array, object etc.) is created on dynamic memory only.
Arrays: An array represents a group of elements of same data type. Arrays are
generally categorized into two types:
 Single Dimensional arrays (or 1 Dimensional arrays)
 Multi-Dimensional arrays (or 2 Dimensional arrays, 3 Dimensional arrays, …)

Single Dimensional Arrays:


A one-dimensional array is, essentially, a list of like-typed variables. To create an
array, you first must create an array variable of the desired type. The general form of a
one-dimensional array declaration is
type var-name[ ];
Here, type declares the base type of the array. The base type determines the data
type of each element that comprises the array. Thus, the base type for the array
determines what type of data the array will hold.

43
JAVA PROGRAMMING

A one dimensional array or single dimensional array represents a row or a


column of elements. For example, the marks obtained by a student in 5 different
subjects can be represented by a 1D array.
 We can declare a one dimensional array and directly store elements at the
time of its declaration, as: int marks[] = {50, 60, 55, 67, 70};
 We can create a 1D array by declaring the array first and then allocate
memory for it by using new operator, as:
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.
int marks[]; //declare marks array
marks = new int[5]; //allot memory for storing 5 elements
These two statements also can be written as:
int marks [] = new int [5];
 We can pass the values from keyboard to the array by using a loop, as given here
for(int i=0;i<5;i++)
{
//read integer values from keyboard and store into marks[i]
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
Marks[i]=Integer.parseInt(br.readLine());
}
Let us examine some more examples for 1D array:
float salary[]={5670.55f,12000f};
float[] salary={5670.55f,12000f};
string names[]=new string[10];
string[] names={‘v’,’r’};
Let’s review: Obtaining an array is a two-step process.
First, you must declare a variable of the desired array type.
Second, you must allocate the memory that will hold the array, using new, and assign it
to the array variable. Thus, in Java all arrays are dynamically allocated.

44
JAVA PROGRAMMING

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.
The advantage of using arrays is that they simplify programming by replacing a lot of
statements by just one or two statements. In C/C++, by default, arrays are created on
static memory unless pointers are used to create them. In java, arrays are created on
dynamic memory i.e., allotted at runtime by JVM.
Program : Write a program to accept elements into an array and display the same.
// program to accept elements into an array and display the same.
import java.io.*;
class ArrayDemo1
{
public static void main (String args[]) throws IOException
{ //Create a BufferedReader class object (br)
BufferedReader br = new BufferedReader (new InputStreamReader (System.in));
System.out.println (“How many elements: “ );
int n = Integer.parseInt (br.readLine ());
//create a 1D array with size n
int a[] = new int[n];
System.out.print ("Enter elements into array : ");
for (int i = 0; i<n;i++)
a [i] = Integer.parseInt ( br.readLine ());
System.out.print (“The entered elements in the array are: “);
for (int i =0; i < n; i++)
System.out.print (a[i] + “\t”);
}
}
Output:
D:/kumar>javac ArrayDemo1.java
D:/kumar>java ArrayDemo1
How many elements:5
Enter elements into arry:10 20 30 40 50
The entered elements in the array are:10 20 30 40 50
D:/kumar>

45
JAVA PROGRAMMING

Multi-Dimensional Arrays (2D, 3D … arrays):


A two dimensional array is a combination of two or more (1D) one dimensional
arrays. A three dimensional array is a combination of two or more (2D) two dimensional
arrays.
 Two Dimensional Arrays (2d array):
A two dimensional array represents several rows and columns of data. To represent
a two dimensional array, we should use two pairs of square braces [ ] [ ] after the array
name. For example, the marks obtained by a group of students in five different subjects
can be represented by a 2D array.
o We can declare a two dimensional array and directly store elements at the time
of its declaration, as:
int marks[] [] = {{50, 60, 55, 67, 70},{62, 65, 70, 70, 81}, {72, 66, 77, 80, 69} };
o We can create a two dimensional array by declaring the array first and then we can allot
memory for it by using new operator as:
int marks[ ] [ ]; //declare marks array
marks = new int[3][5]; //allot memory for storing 15 elements.
These two statements also can be written as: int marks [ ][ ] = new int[3][5];
Program : Write a program to take a 2D array and display its elements in the form of a
matrix.
//Displaying a 2D array as a matrix
class Matrix
{ public static void main(String args[])
{ //take a 2D array
int x[ ][ ] = {{1, 2, 3}, {4, 5, 6} };
// display the array elements
for (int i = 0 ; i < 2 ; i++)
{ System.out.println ();
for (int j = 0 ; j < 3 ; j++)
System.out.print(x[i][j] + “\t”);
}
}
}
Output:
D:/kumar>javac Matrix.java
46
JAVA PROGRAMMING

D:/kumar>java Matrix
1 2 3
4 5 6
D:/kumar>

 Three Dimensional arrays (3D arrays):


We can consider a three dimensional array as a combination of several two
dimensional arrays. To represent a three dimensional array, we should use three pairs of
square braces [ ] [ ] after the array name.
o We can declare a three dimensional array and directly store elements at the time
of its
declaration, as:
int arr[ ] [ ] [ ] = {{{50, 51, 52},{60, 61, 62}}, {{70, 71, 72}, {80, 81, 82}}};
o We can create a three dimensional array by declaring the array first and then we can
allot memory for it by using new operator as:
int arr[ ] [ ] = new int[2][2][3]; //allot memory for storing 15 elements.
//example for 3-D array
class ThreeD
{
public static void main(String args[])
{
int dept, student, marks, tot=0;

47
JAVA PROGRAMMING

int arr[][][]={{{50,51,52},{60,61,62}},{{70,71,72},{80,81,82}},
{{65,66,67},{75,76,77}}};
for(dept=0;dept<3;dept++)
{
System.out.println("dept"+(dept+1)+":");
for(student=0;student<2;student++)
{
System.out.print("student"+(student+1)+"marks:");
for(marks=0;marks<3;marks++)
{
System.out.print(arr[dept][student][marks]+" ");
tot+=arr[dept][student][marks];
}
System.out.println("total:"+tot);
tot=0;
}
System.out.println();
}
}
}

arrayname.length:
If we want to know the size of any array, we can use the property ‘length’ of
an array. In case of 2D, 3D length property gives the number of rows of the array.
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];
48
JAVA PROGRAMMING

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. It is the same as writing
int nums[], nums2[], nums3[]; // create three arrays
The alternative declaration form is also useful when specifying an array as a return type
for
a method.
Using Command-Line Arguments:
Sometimes you will want to pass information into a program when you run it. This is
accomplished by passing command-line arguments to main( ).
A command-line argument is the information that directly follows the program’s name on
the command line when it is executed. To access the command-line arguments inside a
Java program is quite easy they are stored as strings in a String array passed to the args
parameter of main( ).
The first command-line argument is stored at args[0], the second at args[1], and so on.
For example, the following program displays all of the command-line arguments that it is
called with:
// Display all command-line arguments.
class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " +args[i]);
}
}
Try executing this program, as shown here:
java CommandLine
this is a test 100 -1
When you do, you will see the following output:
args[0]: this
args[1]: is
args[2]: a
args[3]: test
49
JAVA PROGRAMMING

args[4]: 100
args[5]: -1
REMEMBER All command-line arguments are passed as strings. You must convert numeric
values to their internal forms manually.
STRINGS
Strings:
A String represents group of characters. Strings are represented as String
objects in java.
The String class is defined in the java.lang package and hence is implicitly available
to all the programs in Java. The String class is declared as final, which means that it
cannot be subclassed. It extends the Object class and implements the Serializable,
Comparable, and CharSequence interfaces.

Java implements strings as objects of type String. A string is a sequence of


characters. Unlike most of the other languages, Java treats a string as a single value
rather than as an array of characters.
Creating Strings:
 We can declare a String variable and directly store a String literal using assignment
operator.
String str = "Hello";
 We can create String object using new operator with some data.
String s1 = new String ("Java");
 We can create a String by using character array also.
char arr[] = { 'p','r','o',’g’,’r’,’a’,’m’};
 We can create a String by passing array name to it, as:
String s2 = new String (arr);
 We can create a String by passing array name and specifying which characters we
need:
String s3 = new String (str, 2, 3);
Here starting from 2nd character a total of 3 characters are copied into String s3.

50
JAVA PROGRAMMING

STRING HANDLING IN JAVA :


String Class Methods:

51
JAVA PROGRAMMING

String represents a sequence of characters. It has fixed length of character


sequence. Once a string object has been created than we can't change the character that
comprise that string. It is immutable. This allows String to be shared. String object can be
instantiated like any other object
String str = new String ("Stanford “);
str += "Lost!!";
Accessor methods:
length(), charAt(i), getBytes(), getChars(istart,iend,gtarget[],itargstart),
split(string,delim), toCharArray(), valueOf(g,iradix), substring(iStart [,iEndIndex)]) [returns
up to but not including iEndIndex]

Modifier methods:
concat(g), replace(cWhich, cReplacement), toLowerCase(), toUpperCase(), trim().

Boolean test methods:


contentEquals(g), endsWith(g), equals(g), equalsIgnoreCase(g), matches(g),
regionMatches(i1,g2,i3,i4), regionMatches(bIgnoreCase,i1,g2,i3,i4), startsWith(g)

Integer test methods:


compareTo(g) [returns 0 if object equals parameter, -1 if object is before parameter
in sort order, +1 if otherwise], indexOf(g) [returns position of first occurrence of substring
g in the string, -1 if not found], lastIndexOf(g) [returns position of last occurrence of
substring g in the string, -1 if not found], length().

Constructors defined in the String class

The String class defines several constructors. The most common constructor of the
String class is the one given below:

public String(String value)

This constructor constructs a new String object initialized with the same sequence
of the characters passed as the argument. In other words, the newly created String object

52
JAVA PROGRAMMING

is the copy of the string passed as an argument to the constructor.

Other constructors defined in the String class are as follows:

public String()

This constructor creates an empty String object. However, the use of this
constructor is unnecessary because String objects are immutable.

public String(char[] value)

This constructor creates a new String object initialized with the same sequence of
characters currently contained in the array that is passed as the argument to it.

public String(char[] value, int startindex, int len)

This constructor creates a new String object initialized with the same sequence of
characters currently contained in the subarray. This subarray is derived from the character
array and the two integer values that are passed as arguments to the constructor. The int
variable startindex represents the index value of the starting character of the subarray,
and the int variable len represents the number of characters to be used to form the new
String object.

public String(StringBuffer sbf)

This constructor creates a new String object that contains the same sequence of
characters currently contained in the string buffer argument.

public String(byte[] asciichars)

The array of bytes that is passed as an argument to the constructor contains the
ASCII character set. Therefore, this array of bytes is first decoded using the default charset
of the platform. Then the constructor creates a new String object initialized with same
sequence of characters obtained after decoding the array.

53
JAVA PROGRAMMING

public String(byte[] asciiChars, int startindex, int len)

This constructor creates the String object after decoding the array of bytes and by using
the subarray of bytes.

Special String Operations:


Finding the length of string

The String class defines the length() method that determines the length of a string.
The length of a string is the number of characters contained in the string. The signature of
the length() method is given below:
public int length()

String Concatenation using the + operator

The + operator is used to concatenate two strings, producing a new String object as
the result. For example,

String sale = "500";


String s = "Our daily sale is" + sale + "dollars";
System.out.println(s);

This code will display the string "Our daily sale is 500 dollars".

The + operator may also be used to concatenate a string with other data types. For
example,

int sale = 500;


String s = "Our daily sale is" + sale + "dollars";
System.out.println(s);

This code will display the string "Our daily sale is 500 dollars". In this case, the
variable sale is declared as int rather than String, but the output produced is the same.

54
JAVA PROGRAMMING

This is because the int value contained in the variable sale is automatically converted to
String type, and then the + operator concatenates the two strings.

String Comparison

The String class defines various methods that are used to compare strings or
substrings within strings. Each of them is discussed in the following sections:

Note: Since strings are stored as a memory address, the == operator can't be used for
comparisons. Use equals() and equalsIgnoreCase() to do comparisons. A simple example
is:

equals()

The equals() method is used to check whether the Object that is passed as the
argument to the method is equal to the String object that invokes the method. It returns
true if and only if the argument is a String object that represents the same sequence of
characters as represented by the invoking object. The signature of the equals() method is
as follows:

boolean i=str1.equals(str2)

equalsIgnoreCase()

The equalsIgnoreCase() method is used to check the equality of the two String
objects without taking into consideration the case of the characters contained in the two
strings. It returns true if the two strings are of the same length and if the corresponding
characters in the two strings are the same ignoring case. The signature of the
equalsIgnoreCase() method is:

boolean i=str1.equalsIgnoreCase( str2)

55
JAVA PROGRAMMING

compareTo()

The compareTo() method is used in conditions where a Programmer wants to sort a


list of strings in a predetermined order. The compareTo() method checks whether the
string passed as an argument to the method is less than, greater than, or equal to the
invoking string. A string is considered less than another string if it comes before it in
alphabetical order. The signature of the compareTo() method is as follows:

int i=str1. compareTo( str2)

where, str is the String being compared to the invoking String. The compareTo()
method returns an int value as the result of String comparison. The meaning of these
values are given in the following table:

compareToIgnoreCase()
The String class also has the compareToIgnoreCase() method that compares two
strings without taking into consideration their case difference. The signature of the
method is given below:

int i=str1.compareToIgnoreCase( str2)

regionMatches()

The regionMatches() method is used to check the equality of two string regions
where the two string regions belong to two different strings. The signature of the method
is given below:

public boolean regionMatches(int startindex, String str2, int startindex2, int len)

There is also an overloaded version of the method that tests the equality of the
substring ignoring the case of characters in the substring. Its signature is given below:

public boolean regionMatches(boolean ignoreCase, int startindex, String str2, int

56
JAVA PROGRAMMING

startindex2, int len)

In both signatures of the method, startindex specifies the starting index of the
substring within the invoking string. The str2 argument specifies the string to be
compared. The startindex2 specifies the starting index of the substring within the string to
be compared. The len argument specifies the length of the substring being compared.
However, in the latter signature of the method, the comparison is done ignoring the case
of the characters in the substring only if the ignoreCase argument is true.

startsWith()

The startsWith() method is used to check whether the invoking string starts with the
same sequence of characters as the substring passed as an argument to the method. The
signature of the method is given below:
public boolean startsWith(String prefix)

There is also an overloaded version of the startsWith() method with the following
signature:
public boolean startsWith(String prefix, int startindex)

In both signatures of the method given above, the prefix denotes the substring to
be matched within the invoking string. However, in the second version, the startindex
denotes the starting index into the invoking string at which the search operation will
commence.
endsWith()

The endsWith() method is used to check whether the invoking string ends with the
same sequence of characters as the substring passed as an argument to the method. The
signature of the method is given below:

public boolean endsWith(String prefix)

Modifying a String

57
JAVA PROGRAMMING

The String objects are immutable. Therefore, it is not possible to change the original
contents of a string. However, the following String methods can be used to create a new
copy of the string with the required modification:

substring()

The substring() method creates a new string that is the substring of the string that
invokes the method. The method has two forms:

public String substring(int startindex)


public String substring(int startindex, int endindex)

where, startindex specifies the index at which the substring will begin and endindex
specifies the index at which the substring will end. In the first form where the endindex is
not present, the substring begins at startindex and runs till the end of the invoking string.

Concat()
The concat() method creates a new string after concatenating the argument string
to the end of the invoking string. The signature of the method is given below:

public String concat(String str)

replace()

The replace() method creates a new string after replacing all the occurrences of a
particular character in the string with another character. The string that invokes this
method remains unchanged. The general form of the method is given below:

public String replace(char old_char, char new_char)

trim()

The trim() method creates a new copy of the string after removing any leading and
trailing whitespace. The signature of the method is given below:

58
JAVA PROGRAMMING

public String trim(String str)


toUpperCase()

The toUpperCase() method creates a new copy of a string after converting all the
lowercase letters in the invoking string to uppercase. The signature of the method is given
below:

public String toUpperCase()

toLowerCase()

The toLowerCase() method creates a new copy of a string after converting all the
uppercase letters in the invoking string to lowercase. The signature of the method is given
below:

public String toLowerCase()

Searching Strings

The String class defines two methods that facilitate in searching a particular
character or sequence of characters in a string. They are as follows:

IndexOf()

The indexOf() method searches for the first occurrence of a character or a substring
in the invoking string. If a match is found, then the method returns the index at which the
character or the substring first appears. Otherwise, it returns -1.

The indexOf() method has the following signatures:

public int indexOf(int ch)


public int indexOf(int ch, int startindex)

59
JAVA PROGRAMMING

public int indexOf(String str)


public int indexOf(String str, int startindex)

lastIndexOf()

The lastIndexOf() method searches for the last occurrence of a character or a substring in
the invoking string. If a match is found, then the method returns the index at which the
character or the substring last appears. Otherwise, it returns –1.

The lastIndexOf() method has the following signatures:

public int lastIndexOf(int ch)


public int lastIndexOf (int ch, int startindex)
public int lastIndexOf (String str)
public int lastIndexOf (String str, int startindex)
Program : Write a program using some important methods of String class.
// program using String class methods
class StrOps
{ public static void main(String args [])
{ String str1 = "When it comes to Web programming, Java is #1.";
String str2 = new String (str1);
String str3 = "Java strings are powerful.";
int result, idx; char ch;
System.out.println ("Length of str1: " + str1.length ());
// display str1, one char at a time.
for(int i=0; i < str1.length(); i++)
System.out.print (str1.charAt (i));
System.out.println ();
if (str1.equals (str2) )
System.out.println ("str1 equals str2");
else
System.out.println ("str1 does not equal str2");
if (str1.equals (str3) )
System.out.println ("str1 equals str3");

60
JAVA PROGRAMMING

else
System.out.println ("str1 does not equal str3");
result = str1.compareTo (str3);
if(result == 0)
System.out.println ("str1 and str3 are equal");
else if(result < 0)
System.out.println ("str1 is less than str3");
else
System.out.println ("str1 is greater than str3");
str2 = "One Two Three One"; // assign a new string to str2
idx = str2.indexOf ("One");
System.out.println ("Index of first occurrence of One: " + idx);
idx = str2.lastIndexOf("One");
System.out.println ("Index of last occurrence of One: " + idx);
}
}
Output:
D:/kumar>javac StrOPs.java
D:/kumar>java StrOps
Length of str1:46
When it comes to web programming, Java is #1.
Str1 equals str2
Str1 does not equal str3
Str1 is greater than str3
Index of first occurrence of one:0
Index of last occurrence of one:14
D:/kumar>
StringBuffer:
StringBuffer:
StringBuffer objects are mutable, so they can be modified. The methods that
directly manipulate data of the object are available in StringBuffer class.
Creating StringBuffer:
 We can create a StringBuffer object by using new operator and pass the string to the
object, as: StringBuffer sb = new StringBuffer ("Kiran");
61
JAVA PROGRAMMING

 We can create a StringBuffer object by first allotting memory to the StringBuffer


object using new operator and later storing the String into it as:
StringBuffer sb = new StringBuffer (30);
In general a StringBuffer object will be created with a default capacity of 16 characters.
Here, StringBuffer object is created as an empty object with a capacity for storing 30
characters. Even if we declare the capacity as 30, it is possible to store more than 30
characters into StringBuffer.
To store characters, we can use append () method as:
Sb.append (“Kiran”);
This represents growable and writeable character sequence. It is mutable in nature.
StringBuffer are safe to be used by multiple thread as they are synchronized but this
brings performance penalty.
It defines 3-constructor:
• StringBuffer(); //initial capacity of 16 characters
• StringBuffer(int size); //The initial size
• StringBuffer(String str);

StringBuffer str = new StringBuffer ("Stanford ");


str.append("Lost!!");

Program : Write a program using some important methods of StringBuffer class.


// program using StringBuffer class methods
import java.io.*;
class Mutable
{ public static void main(String[] args) throws IOException
{ // to accept data from keyboard
BufferedReader br=new BufferedReader (new InputStreamReader (System.in));

62
JAVA PROGRAMMING

System.out.print ("Enter sur name : ");


String sur=br.readLine ( );
System.out.print ("Enter mid name : ");
String mid=br.readLine ( );
System.out.print ("Enter last name : ");
String last=br.readLine ( );
// create String Buffer object
StringBuffer sb=new StringBuffer ( );
// append sur, last to sb
sb.append (sur);
sb.append (last);
// insert mid after sur
int n=sur.length ( );
sb.insert (n, mid);
// display full name
System.out.println ("Full name = "+sb);
System.out.println ("In reverse ="+sb.reverse ( )); }}
Output:
D:/kumar>javac Mutable.java
D:/kumar>java Mutable
Enter sur name:kranthi
Enter mid name:kumar
Enter last name:A
Full name=kranthi kumar A
In reverse=A ramuk ihtnark
D:/kumar>
Accessor methods:
capacity(), charAt(i), length(), substring(iStart [,iEndIndex)])
Modifier methods:
append(g), delete(i1, i2), deleteCharAt(i), ensureCapacity(), getChars(srcBeg,
srcEnd, target[], targetBeg), insert(iPosn, g), replace(i1,i2,gvalue), reverse(),
setCharAt(iposn, c), setLength(),toString(g)
So the basic differences are…..
1. String is immutable but StringBuffer is not.
63
JAVA PROGRAMMING

2. String is not threadsafe but StringBuffer is thread safe


3. String has concat() for append character but StringBuffer has append() method
4. while you create String like String str = new String(); it create 2 object 1 on heap and 1
on String Constant pool and that refered by str but in StringBuffer it Create 1 object on
heap
StringBuilder

StringBuilder class is introduced in Java 5.0 version. This class is an alternative to


the existing StringBuffer class. If you look into the operations of the both the classes, there
is no difference. The only difference between StringBuilder and StringBuffer is that
StringBuilder class is not synchronized so it gives better performance. Whenever there are
no threading issues, its preferable to use StringBuilder. StringBuffer class can be replaced
by StringBuilder with a simple search and replace with no compilation issue.
Accessor methods: capacity(), length(), charAt(i), indexOf(g), lastIndexOf(g)
Modifier methods: append(g), delete(i1, i2), insert(iPosn, g), getChars(i),
setCharAt(iposn, c), substring(), replace(i1,i2,gvalue), reverse(), trimToSize(g ), toString(g)

64

You might also like