Unit 1
Unit 1
UNIT 1-INTRODUCTION
Object oriented concepts -Classes and Objects – Methods – Constructors – Types of
Constructors- Inheritance – Basics – Using Super – Method Overriding – Abstract Classes –
Using final with inheritance - String Handling – String class – String buffer class.
Introduction
Java is a General-Purpose, High-Level Object-Oriented Programming language
developed by Sun Microsystems of USA in 1991.
It is a simple programming language. Java makes writing, compiling, and debugging
programming easy. It helps to create reusable code and modular programs.
Java code can run on all platforms that support Java. Java applications are compiled to
byte code that can run on any Java Virtual Machine. The syntax of Java is similar to
C/C++.
Java is currently one of the most popular programming languages in use, particularly for
client-server web applications.
History of Java
Java is invented by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike
Sheridan at Sun Microsystems, Inc. in 1991. Java is related to C++, which is inherited
from the language C. The character of Java is inherited from C and C++ language. It
took approx. Eighteen months to develop the first working version. It was first named as
“Oak” but was renamed as “Java” in 1995.
The basic idea behind creating this language is to create a platform-independent
language that is used to develop software for consumer electronic devices such as
microwave ovens, remote controls, etc. Initially, it was not designed for Internet
applications.
Java had an extreme effect on the Internet by the innovation of a new type of networked
program called the Applet. An Applet is a Java program that is designed to be
transmitted over the internet and executed by the web browser that is Java-compatible.
Applets are the small program that is used to display data provided by the server, handle
user input, provide a simple function such as calculator etc.
Java solves the Security and the portability issue of the other language that is being used.
The key that allows doing so is the Bytecode. Bytecode is a highly optimized set of
instruction that is designed to be executed by the Java Virtual Machine (JVM). Java
programs are executed by the JVM also helps to make Java a secure programming g
language because the JVM contains the application and prevents it from affecting the
external systems.
1. Definition of OOP
Object-Oriented Programming is an approach that provides a way of modularizing
programs by creating partitioned memory area for both data and functions that
can be used as templates for creating copies of such modules on demand.
1.2 Object-Oriented Paradigm
OOP allows us to decompose a problem into a number of smaller entities called Objects
and then build data and functions (known as methods in Java) around these entities.
The combination of data and functions make up an object.The data of an object can be
accessed only by the methods associated with that object. However, methods of one
object can access the methods of other objects.
Basic Concepts of Object-Oriented Programming
Object Oriented Programming is a method of implementation in which programs are
organized as cooperative collection of objects, each of which represents an instance of a
class, and whose classes are all members of a hierarchy of classes united via inheritance
relationships.
The general concepts of OOP are as follows:
1. Classes
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which we can create an individual object.
Class doesn't consume any space.
2. Objects
An Object can be defined as an instance of a class. An object contains an address and
takes up some space in memory.
Any entity that has state and behavior is known as an object. For example, a chair, pen,
table, keyboard, bike, etc.
In other terms, objects are the runtime entities of a class. For example, the object for
Student class can be created as follows:
Student st1;
st1 is the runtime entity of Student and it will have the data members Name, DOB and
marks and the functions Total, Average and Display can be used by st1 to calculate.
3. Abstraction
Abstraction refers to the act of representing essential features without including the
explanations. Since the classes use the concept of data abstraction, they are known as
Abstract Data Types.
4. Encapsulation
The wrapping up of data and functions into a single unit is called as encapsulation.
A java class is the example of encapsulation.
5. Inheritance
Inheritance is the process by which objects of one class acquire the properties of another
class.
For example, a student as well as a staff is a Person. Both have some common
properties. Inheritance allows the programmer to reuse defined properties.
6. Polymorphism
Polymorphism means the ability to take more than one form. For example, consider the
operation of addition.
For two numbers, the operation will generate a sum.
If the operands are strings, then the operation would produce a third string by
concatenation.
7. Dynamic Binding
Binding refers to the linking of a procedure call to the code to be executed.
Dynamic Binding means that the code associated with a given procedure call is not
known until the time of the call at run-time.
8. Message Passing
Objects communicate with one another by sending and receiving information. A
message for an object is a request for execution of a procedure.
Message Passing involves specifying the name of the object, the name of the function
(message) and the information to be sent.
2.4 Benefits of OOP
OOP offers several benefits to both the program designer and the user. The principal
advantages are:
Through inheritance, we can eliminate redundant code and extend the use of existing
classes.
We can build programs from the standard working modules that communicate with
one another, rather than having to start writing the code from scratch. This leads to
saving of development time and higher productivity.
The principle of data hiding helps the programmer to build secure programs that
cannot be invaded by code in other parts of the program.
It is possible to have multiple objects to coexist without any interference.
It is possible to map objects in the problem domain to those objects in the program.
It is easy to partition the work in a project based on objects.
The data-centered design approach enables us to compare more details of a model in
an implementable form.
Object-oriented systems can be easily upgraded from small to large systems.
2.5 Applications of OOP
Applications of OOP are beginning to gain importance in many areas. The most popular
application of Object-Oriented Programming, has been in the area of user interface design
such as windows. There are hundreds of windowing systems developed using OOP
techniques.
The promising areas for applications of OOP include:
Real-time Systems
Simulation and Modeling
Object-Oriented Databases
Hypertext, Hypermedia and Exper text
AI and Expert Systems
Neural Networks and Parallel Programming
Decision Support and Office Automation Systems
Documentation Section
The documentation section contains a set of comment lines. Java supports three types of
comments.
1. Single-line Comment
2. Multiline Comment
3. Documentation Comment
A single line comment starts with // and ends in the single line.
Example:
// The following program will calculate the bonus
A multiline comment spreads over several lines. Such a comment begins with /* and ends
with */
Example:
: A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z
Identifiers are names given to classes, methods, variables, objects, arrays, packages
and interfaces in a program. These are user defined names.
Rules:
Identifiers are formed with alphabets, digits, underscore and dollar sign characters.
The first character must be an alphabet.
Uppercase and lowercase letters are distinct.
They can be of any length.
They are case sensitive.
Literals
Operators
An operator is a symbol which represents some operation that can be performed on data.
There are eight operators in Java. They are Arithmetic operators, Relational operators,
Logical operators, Shorthand assignment operators, Increment and decrement operators,
Conditional operator, Bitwise operators, Special operators.
Separators
A symbol that is used to separate one group from another group is called a
separator.
The most commonly used separator in Java is the semicolon.It is used to terminate
statements.
The separators are shown in the following table:
Java Keywords
Java Keywords are also known as as reserved words.
Java Keywords are predefined in JAVA and they are used to represent some predefined
actions.
We cannot use them as names for variables, classes, methods and so on.
All keywords are to be written in lower-case letters.
In addition to the keywords, Java reserves the following: true, false, and null. These are
values defined by Java.
There are 61 keywords currently defined in the Java language (Table 2.1)
Note: All Java source files will have the extension java. If a program contains multiple
classes, the file name must be the classname of the class containing the main method.
To compile the Example program, execute the compiler, javac, specifying the name of the
source file on the command line as shown here:
C:\JDK1.6.0_01\BIN>javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version
of the program. The Java bytecode is the intermediate representation of our program that
contains the instructions the Java interpreter will execute. Thus, the output of javac is not
code that can be directly executed.
Running the Program
To actually run the program, we must use the Java interpreter called java. To do so, pass
the class name Example as a command-line argument as shown here:
C:\JDK1.6.0_01\BIN>java Example
When the program is run, the following output is displayed:
Welcome to Java Programming.
When Java source code is compiled, each individual class is put into its own output file
named after the class and using the .class extension.
2.14 Java Virtual Machine
The JVM (Java Virtual Machine) is the environment in which Java programs execute.
It is software that is implemented on top of real hardware and operating system.
JVM is Write Once-Run Anywhere (WORA) software.
JVM forms part of large system JRE.
JVM's main job is interpreting java byte code and translating this into actions or OS
calls.
JVM is OS dependent which makes java source code as machine independent.
2.15 Command Line Arguments
Command line arguments are parameters that are supplied to the application
program at the time of invoking it for execution.
We can write Java programs that can receive and use the arguments provided in the
command line. The signature of the main() method used in our earlier programs:
public static void main(String args[])
args is declared as an array of strings. Any arguments provided in the command line (at
the time of execution) are passed to the array args as its elements. We can simply access
the array elements and use them in the program as we wish.
The individual elements of an array are accessed by using an index or subscript like
args[i]. The value of i denotes the position of the elements inside the array.
Example:
*******************************************************************
Chapter 3 Data Types and Variables
*******************************************************************
3.1 Data Types
Data Types specify the size and type of values that can be stored.
Java language is rich in its data types. Java has four main primitive data types built into
the language.
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.
Data Types in Java under various categories are shown in Figure 3.1
Integer Types
Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values. Java does not support unsigned, positive-only integers.
The width and ranges of these integer types vary widely, as shown in this table:
------------------------------------------------------------------------------------------------------
Type Size Range
------------------------------------------------------------------------------------------------------
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to 2,147,483,647
long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
-----------------------------------------------------------------------------------------------------------
Figure 3.2: Integer Data Types
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 we are working with a stream of
data from a network or file.
Byte variables are declared by use of the byte keyword.
Example:
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. This type is mostly applicable to 16-bit
computers.
Example:
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.
Example:
int a,b,c;
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.
Example:
long distance;
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision.
Floating point types are used to hold numbers containing fractional parts such as
27.59 and -1.375.
There are two kinds of floating-point types, float and double, which represent
single- and double-precision numbers, respectively.
Example:
char ch;
ch=’X’;
Boolean Type
Boolean type is used when we want to test a particular condition during the
execution of the program.
There are only two values that a Boolean type can take: true or false. Boolean type is
denoted by the keyword boolean and uses only one bit of storage.
Boolean values are often used in selection and iteration statements.
Example:
boolean flag;
flag=true;
3.2 Constants (Literals)
Constant refers tofixed values that do not change during the execution of a program.
Constants are declared using the final keyword.
Java support several types of constants as follows:
Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers,
namely, decimal integer, octal integer, and hexadecimal integer.
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional minus
sign.
Valid examples of decimal integer constants are:
123 -321 0 654321
Embedded spaces, commas, and non-digit character are not permitted between digits.
For example,
15 750 20,000 $1000
are illegal numbers.
An octal integer constant consists of any combination of digits from the set 0
through 7, with a leading 0.
Some examples of octal integer are:
037 0 0435 0551
A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer.
They may also include alphabets A through F or a through f. A letter A through F
represents the numbers 10 through 15.
Following are the examples of valid hex integers.
0x2 0x9F 0xbcd 0x
Real Constants
A number with a decimal point is called a real constant or a floating point constant.
Some examples of real constants are:
0.0083 -0.75 435.36
A real number may also be expressed in exponential (or scientific) notation.
For example, the value 215.65 may be written as 2.1565e2 in exponential notation.e2
means multiply by 102. The general form is:
mantissa e exponent
A list of such backslash character constants is given in table below. These character
combinations are known as escape sequences.
Constant Meaning
'\b' back space
'\f' form feed
'\n' new line
'\t' horizontal tab
'\r' carriage return
'\'' single quote
'\"' double quote
'\\' Backslash
3.3 Variables
A variable is an identifier that denotes a storage location used to store a data value.
A variable may take different values at different times during the execution of the
program.
A variable name can be chosen by the programmer in a meaningful way so as to reflect
what it represents in the program.
Some examples of variable names are:
i) average
ii) height
iii) total_height
iv) classStrength
Rules:
A variable name may consist of alphabets, digits, the underscore (_) and the dollar
character.
The first character in a variable name should not be a digit.
Uppercase and lowercase are distinct. This means that the variable Total is not the same
as total or TOTAL.
A keyword should not be used as a variable name.
White spaces are not allowed within a variable name.
A variable name can be of any length.
Declaration of Variables
In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown here:
Datatype identifier [=value][,identifier [=value]…];
Examples:
int a,b,c;
int d=3,e,f=5;
byte age=22;
double pi=3.14159;
char x=’x’;
Example 1:
int x = 20;
long y = x; // Automatic Conversion
Example 2:
1 Introduction
The Control Statements are used for controlling the execution of the program.
There are three main categories of control statements;
Selection Statements: if and switch.
Looping Statements: while, do-while and for.
Transfer Statements: break, continue and return.
5.2 Selection Statements
Java supports two selection statements - if and switch. These statements allow us to
control the flow of the program.
Depending upon the expressions or values, the corresponding blocks/statements of code
will be executed or by passed.
The two statements are
if statement is a conditional branch statement. This is a two way branch statement.
Depending upon the whether a condition is true or false, the corresponding code is
executed.
switch statement is a multiway branch statement. Depending upon the value used for
switching, the corresponding code is executed.
These two statements are very powerful and are used widely across any application. They
provide effective solutions for branching problems.
1. The if Statement
The if statement is a powerful decision making statement and is used to control the
flow of execution of statements.
It is basically a two-way decision statement and is used in conjunction with an
expression.
The if statement may be implemented in different forms depending on the complexity of
conditions to be tested.
i) Simple if statement
ii) if…else statement
iii) Nested if…else statement
iv) if-else-if Ladder
i) Simple if Statement
The if statement executes a block of code only if the specified condition is true.
If the condition is false, then the if block is skipped and execution continues with the rest
of the program.
Syntax:
if (Condition)
{
//Statements;
}
Example:
//Java program to find the biggest among three numbers using nested if statement
//big3.java
import java.io.*;
class big3
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b,c;
System.out.println("Enter the first number");
a=Integer.parseInt(br.readLine());
System.out.println("Enter the second number");
b=Integer.parseInt(br.readLine());
System.out.println("Enter the third number");
c=Integer.parseInt(br.readLine());
if ((a>b) && (a>c))
{
System.out.println("Biggest="+a);
}
if ((b>a) && (b>c))
{
System.out.println("Biggest="+b);
}
else
{
System.out.println("Biggest="+c);
}
}
}
Output:
Enter the first number
50
Enter the second number
40
Enter the third number
30
Biggest=50
iv) if…else…if Ladder
An if...else...if ladder can be used to execute one block of code among multiple
blocks.
Syntax:
if(Condition1)
{
//Statements
}
else if(Condition2)
{
//Statements
}
.
.
.
else
{
//Statements
}
This construct is known as the else if ladder.
The conditions are evaluated from top (of the ladder) to bottom.
When the test condition is true, code inside the body of that if block is executed. And,
program control jumps outside the if...else...if ladder.
If all test expressions are false, code inside the body of else are executed.
Example:
The value of the expression is evaluated and compared with each of the values in the
case statements.
If a match is found, the code sequence following that case statement is executed. If none
of the constants matches the value of the expression, then the default statement is
executed. However, the default statement is optional.
The break statement is used inside the switch to terminate a statement sequence.
Example:
//Java program to print the days of the week using switch statement
//days_of_week.java
import java.io.*;
class days_of_week
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int d;
System.out.println("Enter the day code");
d=Integer.parseInt(br.readLine());
switch(d)
{
case 1 : System.out.println("Sunday");
break;
case 2 : System.out.println("Monday");
break;
case 3 : System.out.println("Tuesday");
break;
case 4 : System.out.println("Wednesday");
break;
case 5 : System.out.println("Thursday");
break;
case 6 : System.out.println("Friday");
break;
case 7 : System.out.println("Saturday");
break;
default : System.out.println("Wrong day code");
}
}
}
Output:
Enter the day code
2
Monday
Nested switch Statement
A switch statement inside another switch statement is known as nested switch
statement.
The inner switch statement will be part of any case of an outer switch.
The inner switch statement will be executed only if the outer switch statement condition
is true.
Example:
//Java Program to implement Nested Switch Statement
import java.io.*;
public class ExampleOfNestedSwitch
{
public static void main(String args[]) throws IOException
{
int year, marks;
BufferedReader br=new BufferedReader(New InputStreamReader(System.in));
System.out.println(“Enter the year”);
year=Integer.parseInt(br.readLine());
System.out.println(“Enter the marks”);
marks=Integer.parseInt(br.readLine());
switch(year)
{
case 1:
System.out.println("First year students are not eligible for scholarship ");
break;
case 2:
System.out.println("Second year students are not eligible for scholarship");
break;
case 3:
switch(marks)
{
case 50:
System.out.println("You are not eligible for scholarship");
break;
case 80:
System.out.println("Congrats! You are eligible for scholarship");
break;
}
break;
default:
System.out.println("Please enter valid year");
}
}
}
Output:
Enter the year
3
Enter the marks
80
Congrats! You are eligible for scholarship
if…else switch
If statement is used to select among two The switch statement is used to select among
alternatives multiple alternatives.
It contains either logical or equality It contains a single expression which can be either a
expression. character or integer variable.
It evaluates all types of data, such as integer, It evaluates either an integer, or character.
floating-point, character or Boolean.
First, the condition is checked. If the It executes one case after another till the break
condition is true then 'if' block is executed keyword is not found, or the default statement is
otherwise 'else' block executed.
If the condition is not true, then by default, If the value does not match with any case, then by
else block will be executed. default, default statement is executed.
It is difficult to edit the if-else statement, if It is easy to edit switch cases as, they are
the nested if-else statement is used. recognized easily.
If there are multiple choices implemented If we have multiple choices then the switch
through 'if-else', then the speed of the statement is the best option as the speed of the
execution will be slow. execution will be much higher than 'if-else'.
The while loop executes a block of code as long as a specified condition is true.
If the number of iterations is not fixed, it is recommended to use a while loop.
It is also known as an Entry-Controlled loop.
Syntax:
while(Condition)
{
//Body of while loop
}
The Condition can be any Boolean expression.
The body of while loop will be executed as long as the conditionl expression is true.
When the Condition becomes false, control passes to the next line of code immediately
following the while loop.
Example:
The do...while loop executes a block of code repeatedly until the specified condition
is true.
The do…while loop is executed at least once because the condition is checked after the
loop body.
The do…while loop is similar to the while loop, however there is a difference between
them. In while loop, the condition is evaluated before the execution of loop’s body but in
do…while loop the condition is evaluated after the execution of loop’s body.
Syntax:
do
{
//Body of the loop
}
while(Condition);
The Condition can be any Boolean expression.
Each iteration of the do…while loop first executes the body of the loop and then
evaluates the conditional expression. If this expression is true, the loop will repeat.
Otherwise, the loop terminates.
Example:
//Java program to print the positive integers from 1 to n
//print_digits.java
import java.io.*;
class print_digits
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n,i=1;
System.out.println("Enter the number");
n=Integer.parseInt(br.readLine());
do
{
System.out.println(i);
i++;
}
while(i<=n);
}
}
Output:
Enter the number
5
1
2
3
4
5
3. The for Statement
The for loop is used to execute a set of statements repeatedly for a specified number
of times.
It is commonly used for simple iteration.
Syntax:
for (initialization; condition; increment/decrement)
{
//Body of for loop
}
If only one statement is being repeated, there is no need for the curly braces.
1. Initialization: The initialization portion of the loop is executed first. Generally, this is
an expression that sets the value of the loop control variable, which acts as a counter
that controls the loop. The initialization expression is executed only once.
2. Condition: The condition must be a Boolean expression. If this expression is true,
then the body of the loop is executed. If it is false, the loop terminates.
3. Body of for loop: It contains a block of code that executes each time after evaluating
the condition true.
4. Increment/decrement: This is usually an expression that increments or decrements
the loop control variable.
Example:
//Java program to find the factorial value of a given number
//fact.java
import java.io.*;
class fact
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n;
long f=1;
System.out.println("Enter the number");
n=Integer.parseInt(br.readLine());
for(int i=1;i<=n;i++)
{
f=f*i;
}
System.out.println("Factorial Value="+f);
}
}
Output:
Enter the number
5
Factorial Value=120
5.4 Jump (Transfer) Statements
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of the program.
1. The break statement
The break statement is used to terminate the loop.
When a break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
The break statement can be used in all types of loops such as for loop, while loop and do-
while loop.
Syntax:
break; // The unlabeled form
break label; // The labeled form
In Java, the break statement has three uses. First, as we have seen, it terminates a
statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it
can be used as a “civilized” form of goto.
i) Using break to Exit a Loop
By using break, we can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop.
Example:
//Java program to illustrate the break statement
//BreakExample.java
class BreakExample
{
public static void main(String args[])
{
System.out.println("Numbers 1 - 10");
for (int i = 1;i<=100;i++)
{
if (i == 5) break; // Terminate loop if i is 5
System.out.println(i);
}
}
}
Output:
Numbers 1 - 10
1
2
3
4
ii) Using break as a Form of goto
The break statement can also be employed by itself to provide a “civilized” form of the
goto statement.
Java does not have a goto statement. By using this form of break, we can break out of
one or more blocks of code.
Syntax:
break label;
Here, label is the name of the label that identifies a block of code. When this form of
break executes, control is transferred out of the named block of code.
To name a block, put a label at the start of it. A label is any valid Java identifier
followed by a colon. Once we have labeled the block, we can then use this label as the
target of a break statement.
Example:
//Java program to find the sum of 1 to n numbers using the break label statement
//BreakLoop.java
import java.io.*;
class BreakLoop
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n,i,s=0;
System.out.println("Enter the number");
n=Integer.parseInt(br.readLine());
s=s+i;
i++;
start:
if (i<=n) break start;
System.out.println(“Sum=”+s);
}
}
Output:
Enter the number
5
Sum=15
2. The continue Statement
The continue statement is used to continue the loop.
When a continue statement is encountered the control directly jumps to the
beginning of the loop for the next iteration instead of executing the statements of
the current iteration.
The continue statement is used when we do not want to execute the remaining statements
in the loop, but we do not want to exit the loop itself.
Syntax:
continue; // The unlabeled form
continue label; // The labeled form
The label name is optional, and is usually only used when we wish to return to the
outermost loop in a series of nested loops.
Example 1:
//Java program to print the odd numbers between 1 to 10
//ContinueExample.java
class ContinueExample
{
public static void main(String args[])
{
System.out.println("Odd Numbers");
for (int i = 1; i <= 10; ++i)
{
if (i % 2 == 0)
continue;
// Rest of loop body skipped when i is even
System.out.println(i);
}
}
}
Output:
Odd Numbers
1
3
5
7
9
Example 2:
//Using continue with a label
//ContinueLabel.java
class ContinueLabel
{
public static void main(String args[])
{
outer: for (int i=0;i<5;i++)
{
for (int j=0;j<5;j++)
{
if (j>i)
{
System.out.println();
continue outer;
}
System.out.print(“ “+(i*j));
}
}
System.out.println();
}
}
Output:
0
01
02 4
03 6 9
0 4 8 12 16
Differences Between break and continue Statements
Output:
15
16
17
25
26
27
3. Nested do-while loop
A do-while within another do-while loop is called nested do-while loop.
Syntax:
do
{
do
{
// Statement of inside loop
}
while(condition);
// Statement of outer loop
}
while(condition);
Example:
//Java program to implement nested do-while loop
import java.io.*;
class NestedDoWhileExample
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n, i, j;
System.out.println(“Enter the number of rows”);
n=Integer.parseInt(br.readLine());
System.out.println("Triangle number pattern\n");
i=1;
do
{
j=1;
do
{
System.out.println(j + “ “);
j++;
}
while(j<=i);
System.out.println("\n");
i++;
}
while(i<=n);
}
}
Output:
Enter the number of rows
5
Triangle number pattern
1
12
123
1234
12345
***************************************************************************
****
Classes, Objects and Methods
***************************************************************************
****
7.1 Introduction
The class is the logical construct upon which the entire Java language is built because it
defines the shape and nature of the object. The class forms the basis for object-oriented
programming in Java. Any concept we wish to implement in a Java program must be
encapsulated in a class.
Classes provide a convenient method for packing together a group of logically
related data items and functions that work on them. In Java, the data items are called
fields and the functions are called methods. Classes create objects and objects use
methods to communicate between them.
The most important thing to know about a class is that it defines a new data type. Once
defined, this new type can be used to create objects of that type. Thus, a class is a
template for an object, and an object is an instance of a class.
7.2 Defining a Class
A class is a user-defined data type which has data members and member functions.
A class is a template or blueprint from which objects are created.
A class is declared by using the class keyword.
The general form of a class definition is:
class classname
{
type variable1;
type variable2;
............
type variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodname2(parameter-list)
{
// body of method
}
….
type methodnameN(parameter-list)
{
// body of method
}
}
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a
class are called members of the class.
Variables defined within a class are called instance variables because each instance of
the class (i.e. each object of the class) contains its own copy of these variables. Thus, the
data for one object is separate and unique from the data for another.
Example:
class Rectangle
{
int length;
int width;
void getData(int x, int y)
{
length=x;
width=y;
}
}
The class Rectangle contains two integer type instance variables. These variables are only
declared and therefore no storage space has been created in the memory. Instance variables
are also known as member variables.
The method has a return type of void because it does not return any value. We pass two
integer values to the method, which are then assigned to the instance variables length and
width. The getData() method is basically added to provide values to the instance variables.
7.3 Creating Objects
An Object is an instance of a Class. When a class is defined, no memory is allocated
but when it is instantiated (i.e. an object is created) memory is allocated.
Objects in Java are created using the new operator. The new operator is used to
allocate memory at runtime.
It has this general form:
classname class-var=new classname();
Here, class-var is a variable of the class type being created. The classname is the name
of the class that is being instantiated. The class name followed by parentheses specifies
the constructor for the class. A constructor defines what occurs when an object of a
class is created.
Example:
Rectangle rect1=new rectangle();
7.4 Distinction between a class and an object
A class creates a new data type that can be used to create objects. That is, a class creates
a logical framework that defines the relationship between its members.
When we declare an object of a class, we are creating an instance of that class.
Thus, a class is a logical construct. An object has physical reality. That is, an object
occupies space in memory.
7.5 Accessing Class Members
The instance variables and methods are accessed using the dot (.) operator.
The syntax for accessing a class member is:
objectname.variablename
objectname.methodname(parameter-list);
Here objectnme is the name of the object, variablename is the name of the instance
variable inside the object we wish to access, methodname is the method that we wish to
call, and parameter-list is a comma separated list of “actual values” (or expressions)
that must match in type and number with the parameter list of the methodname declared
in the class.
Example:
Rectangle rect1=new Rectangle();
rect1.length=15;
rect1.width=10;
We can call the getData() method on any Rectangle object to set the values of both
length and width.
Example:
Rectangle rect1=new Rectangle(); // Creating an object
rect1.getData(15,10); // Calling the method using the object
This code creates rect1 object and then passes the values 15 and 10 for the x and y
parameters of the method getData(). This method then assigns these values to length
and width variables respectively.
7.6 Assigning Object Reference Variables
Object reference variables act differently than we might expect when an assignment
takes place.
Example:
Rectangle r1=new Rectangle();
Rectangle r2=r1;
We might think that r2 is being assigned a reference to a copy of the object referred to by
r1. After this fragment executes, r1 and r2 will both refer to the same object. The
assignment of r1 to r2 did not allocate any memory or copy any part of the original
object. It simply makes r2 refer to the same object as does r1. Thus, any changes made to
the object through r2 will affect the object r1 is referring, since they are the same object.
7.7 Methods
Methods are the functions that operate on instances of classes in which they are
defined.
Objects can communicate with each other using methods and can call methods in other
classes.
Classes usually consist of two things: instance variables and methods.
Methods are declared inside the body of the class but immediately after the declaration
of instance variables.
The general form of method declaration is
type methodname(parameter-list)
{
// Body of method
}
Here, type specifies the type of data returned by the method. This can be any valid type,
including class types that we create. If the method does not return a value, its return type
must be void.
The methodname can be any valid identifier that specifies the name of the method.
The parameter-list is a sequence of type and identifier pairs separated by commas.
Parameters are essentially variables that receive the value of the arguments passed to the
method when it is called. If the method has no parameters, then the parameter list will be
empty.
The body actually describes the operations to be performed on the data.
A method may be instructed to return a value after its execution is over. The following
form of the return statement is used.
return value;
Here, value is the value returned.
7.8 Calling Methods
Calling a method is similar to calling or referring to an instance variable. The methods are
accessed using the dot notation.
Example:
// Java Application using classes and objects
// RectArea.java
import java.io.*;
class Rectangle
{
int length, width; // Declaration of variables
void getData(int x,int y) // Definition of method
{
length=x;
width=y;
}
Method Overloading allows a class to define multiple methods with the same name,
but different parameters.
Benefits of using Method Overloading
Method overloading increases the readability of the program.
This provides flexibility to programmers so that they can call the same method for
different types of data.
This reduces the execution time because the binding is done in compilation time itself.
Method overloading minimizes the complexity of the code.
With this, we can use the code again, which saves memory.
Example:
Output:
30
60
31.0
The actual and the formal parameters are stored in different memory locations.
Therefore, any changes made inside formal parameters of the method are not reflected in
the actual parameters of the caller.
Test incrByTen()
{
Test temp=new Test(a+10);
return temp;
}
}
class RetOb
{
public static void main(String args[])
{
Test ob1=new Test(2);
Test ob2;
ob2= ob1.incrByTen();
System.out.println(" ob1.a : "+ob1.a);
System.out.println(" ob2.a : "+ob2.a);
ob2= ob2.incrByTen();
System.out.println(" ob2.a after second increase : "+ob2.a);
}
}
Output:
ob1.a : 2
ob2.a : 12
ob2.a after second increase : 22
7.16 Recursion
Recursion is a process by which a function calls itself.
A method in Java that calls itself is called recursive method.
This technique provides a way to break complicated problems down into simple problems
which are easier to solve.
Example:
class SuperDemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int x,y;
System.out.println("Enter the values of x & y");
x=Integer.parseInt(br.readLine());
y=Integer.parseInt(br.readLine());
B subOb=new B(x,y);
subOb.show();
}
}
Output:
Enter the values of x & y
4
6
i in superclass: 4
i in subclass : 6
2. Multiple Inheritance
The mechanism of inheriting the features of more than one base class into a single class is
known as multiple inheritance.
Java does not support multiple inheritance but the multiple inheritance can be
achieved by using the interface.
3. Multilevel Inheritance
The mechanism of deriving a class from another derived class is called multilevel
inheritance.
This concept allows us to build a chain of classes as shown in Figure 7.2
4. Hierarchical Inheritance
Hierarchical Inheritance is a method of inheritance where one or more derived
classes are derived from a common base class. i.e there is one super class and
multiple subclasses.
This form of inheritance is commonly used in Java program design.
Syntax:
class Subclassname1 extends Superclassname
{
// Variables and Methods
}
class Subclassname2 extends Superclassname
{
// Variables and Methods
}
Example:
// Java program to implement Hierarchical Inheritance
//HierInheritanceDemo.java
class Employee
{
float salary = 40000;
void dispSalary()
{
System.out.println("The Employee salary is :" +salary);
}
}
class PermanentEmp extends Employee
{
double hike = 0.5;
void incrementSalary()
{
System.out.println("The Permanent Employee incremented salary is :" +(salary+(salary * hike)));
}
}
class TemporaryEmp extends Employee
{
double hike = 0.35;
void incrementSalary()
{
System.out.println("The Temporary Employee incremented salary is :" +(salary+(salary *
hike)));
}
}
public class HierInheritanceDemo
{
public static void main(String args[])
{
PermanentEmp p = new PermanentEmp();
TemporaryEmp t = new TemporaryEmp();
p.dispSalary();
p.incrementSalary();
t.dispSalary();
t.incrementSalary();
}
}
Output:
The Employee salary is: 40000.0
The Permanent Employee incremented salary is : 60000.0
The Employee salary is: 40000.0
The Temporary Employee incremented salary is : 54000.0
7.18 Method Overriding
Method Overriding is a feature that allows us to use the same method name in the
child class which is already present in the parent class.
In other words, it is performed between two classes using inheritance relation. Method
Overriding is one of the way by which Java can achieve Run Time Polymorphism.
Rules for Method Overriding
1. Method name must be the same in both parent and child classes.
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship between classes (inheritance).
4. Private, final and static methods cannot be overridden.
Example:
// Java program to implement Method Overriding
// MethodOverriding.java
import java.io.*;
class Parent // Base Class
{
void show()
{
System.out.println("Parent's show method");
}
}
class Child extends Parent // Inherited Class
{
// This method overrides show() of Parent
void show()
{
System.out.println("Child's show method");
}
}
class MethodOverriding // Main class
{
public static void main(String args[])
{
Parent obj1 = new Parent();
obj1.show();
Parent obj2 = new Child();
obj2.show();
}
}
Output:
Parent's show method
Child's show method
Example:
Output:
Finalizing…
Finalized.
7.24 Abstract Methods and Classes
Abstract Methods
A method without body (no implementation) is known as abstract method.
A method must always be declared in an abstract class, or in other words we can say that
if a class has an abstract method, it should be declared abstract as well.
The general form is:
abstract type name(parameter-list);
Rules of Abstract Method
1. Abstract methods don’t have body, they just have method signature as shown above.
2. If a class has an abstract method it should be declared abstract, the vice versa is not true,
which means an abstract class doesn’t need to have an abstract method compulsory.
3. If a regular class extends an abstract class, then the class must have to implement all the
abstract methods of abstract parent class or it has to be declared abstract as well.
Example:
// Java program using abstract method in an abstract class
// Demo.java
import java.io.*;
abstract class Sum
{
public abstract int sumOfTwo(int n1, int n2);
public abstract int sumOfThree(int n1, int n2, int n3);
//Regular method
public void disp()
{
System.out.println("Method of class Sum");
}
}
//Regular class extends abstract class
class Demo extends Sum
{
public int sumOfTwo(int num1, int num2)
{
return num1+num2;
}
public int sumOfThree(int num1, int num2, int num3)
{
return num1+num2+num3;
}
public static void main(String args[])
{
Demo obj = new Demo();
System.out.println(obj.sumOfTwo(3, 7));
System.out.println(obj.sumOfThree(4, 3, 19));
obj.disp();
}
}
Output:
10
26
Method of class Sum
Abstract Class
A class that is declared with an abstract keyword is known as abstract class.
An abstract class cannot be instantiated, which means we are not allowed to create
an object of it. It can be used only as a super-class for those classes that extend the
abstract class.
The default functionality of the class still exists, with its fields, methods and constructors
being accessed in the same way as with the other classes.
An abstract class may contain methods without any implementation, called abstract
methods.
A class that extends an abstract class must implement all its abstract methods (if any).
The general form of an abstract class is:
abstract class Class_Name
{
………….
………….
abstract type name(parameter-list);
…………
}
Here,
abstract: It is a keyword that must be used at the time of declaration.
Class_Name: We can provide class names according to our functionality.
abstract method: Each abstract class has at least one abstract method.
Example:
// Java program to demonstrate abstract class
//AbstractDemo.java
import java.io.*;
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("Drawing Rectangle");
}
}
class Circle extends Shape
{
void draw()
{
System.out.println("Drawing Circle");
}
}
class AbstractDemo
{
public static void main(String args[])
{
Circle c=new Circle();
c.draw();
}
}
Output:
Drawing Circle
***************************************************************************
***
Chapter 8 String Handling
**************************************************************************
****
8.1 Definition
A string is a sequence of characters. Java implements strings as objects of type String.
Java has methods to compare two strings, search for a substring, concatenate two strings,
and change the case of letters within a string. Also, String objects can be constructed a
number of ways, making it easy to obtain a string when needed.
In Java, strings are class objects and implemented using two classes, namely, String and
StringBuffer. These classes are defined in the package java.lang.
8.2 String Class
The String class represents character strings. A Java string is an instantiated object of
the String class. The Java platform provides the String class to create and manipulate
strings.
Strings are constant; their values cannot be changed after they are created. Java strings
are reliable and more predictable. A Java string is not a character array and is not NULL
terminated.
The class String includes methods for examining individual characters of the
sequence, for comparing strings, for searching strings, for extracting substrings, and for
creating a copy of a string with all characters translated to uppercase or to lowercase.
1. The String Constructors
String()
String(char chars[])
String(char chars[], int startIndex, int numChars)
String(String strObj)
String(byte asciiChars[])
String(byte asciiChars[], int startIndex, int numChars)
i) String()
This is the default constructor. To create an empty string, we call the default constructor.
Example:
String S=new String();
will create an instance of String with no characters in it.
ii) String(char chars[])
The String class provides a variety of constructors to create strings that have initial
values. This constructor is used to create a String initialized by an array of characters.
Example:
char chars[]={‘a’,’b’,’c’};
2. String Methods
The String class contains a number of methods that allow us to perform a string
manipulation. Some of the most commonly used string methods are as follows:
i) charAt()
The charAt() method returns the character at the specified index in a string.
The index of the first character is 0, the second character is 1, and so on.
The general form is:
StringObject.charAt(int index)
Example:
//Java program to demonstrate charAt method
import java.io.*;
public class CharAtDemo
{
public static void main(String args[])
{
String Str = "Hello";
char result = Str.charAt(0);
System.out.println(result);
}
}
Output:
H
ii) compareTo()
The concat() method concatenates multiple strings. This method appends the
specified string at the end of the given string and returns the combined string.
The general form is:
StringObject.concat(string)
Example:
//Java program to demonstrate concat method
import java.io.*;
public class ConcatDemo
{
public static void main(String args[])
{
String FirstName = "Raja";
String LastName = "ram";
System.out.println(FirstName.concat(LastName));
}
}
Output:
Rajaram
iv) equals()
The equals() method compares two strings, and returns true if the strings are equal, and
false if not.
The general form is:
StringObject.equals(string)
Example:
//Java program to demonstrate equals method
import java.io.*;
public class EqualsDemo
{
public static void main(String args[])
{
String Str1 = "Java";
String Str2 = "Java";
StringStr3 = "Python";
System.out.println(Str1.equals(Str2));
System.out.println(Str1.equals(Str3));
}
}
Output:
true
false
v) equalsIgnoreCase()
The equalsIgnoreCase() method compares two strings, ignoring lowercase and
uppercase differences.
This method returns true if the strings are equal, and false if not.
The general form is:
StringObject.equalsIgnoreCase(string)
Example:
//Java program to demonstrate equalsIgnoreCase method
import java.io.*;
public class EqualsIgnoreCaseDemo
{
public static void main(String args[])
{
String Str1 = "Java";
String Str2 = "JAVA";
StringStr3 = "Python";
System.out.println(Str1.equalsIgnoreCase(Str2));
System.out.println(Str1.equalsIgnoreCase(Str3));
}
}
Output:
true
false
vi) endsWith()
The endsWith() method is used to check whether a given string ends with the specified
string.
The general form is:
StringObject.endsWith(String str)
Here, str is the String being tested. If the string matches, true is returned. Otherwise,
false is returned.
Example:
Output:
Sindhi College
viii) getBytes()
The getBytes() method returns the byte array of the string. In other words, it returns
sequence of bytes.
The general form is:
StringObject.getBytes()
Example:
//Java program to demonstrate getBytes method
import java.io.*;
public class GetBytesEx
{
public static void main(String args[])
{
String Str="ABCD";
byte[] arr=Str.getBytes();
for(int i=0;i<arr.length;i++)
{
System.out.println(arr[i]);
}
}
}
Output:
65
56
67
68
ix) indexOf()
The indexOf() method Searches for the first occurrence of a character or substring in a
given String.
There are 4 variations of this method in String class:
int indexOf(int ch): It returns the index of the first occurrence of character ch in a given
String.
int indexOf(int ch, int fromIndex): It returns the index of first occurrence of character
ch in the given string after the specified index “fromIndex”.
int indexOf(String str): Returns the index of string str in a particular String.
int indexOf(String str, int fromIndex): Returns the index of string str in the given string
after the specified index “fromIndex”.
All the above variations returns -1 if the specified char/substring is not found in the
particular String.
Example 1:
Now is the time for all good men to come to the aid of their country.
indexOf(t) = 7
indexOf(the) = 7
indexOf(t, 10) = 11
indexOf(the, 10) = 44
x) lastIndexOf()
The lastIndexOf() method searches for the last occurrence of a character or substring in a
given string.
It has the following 4 forms:
int lastIndexOf(int ch): It returns the last occurrence of character ch in the given String.
int lastIndexOf(int ch, int startIndex): It returns the last occurrence of ch, it starts
looking backwards from the specified index “startIndex”.
int lastIndexOf(String str): Returns the last occurrence of substring str in a String.
int lastIndexOf(String str, int startIndex): Returns the last occurrence of str, starts
searching backward from the specified index “startIndex”.
Example:
//Java program to demonstrate lastIndexOf().
import java.io.*;
class LastIndexOfDemo
{
public static void main(String args[])
{
String S = "Now is the time for all good men to come to the aid of their country.";
System.out.println(S);
System.out.println("lastIndexOf(t) = " + S.lastIndexOf('t'));
System.out.println("lastIndexOf(the) = " + S.lastIndexOf("the"));
System.out.println("lastIndexOf(t, 60) = " +S.lastIndexOf('t', 60));
System.out.println("lastIndexOf(the, 60) = " + S.lastIndexOf("the", 60));
}
}
Output:
Now is the time for all good men to come to the aid of their country.
lastIndexOf(t) = 65
lastIndexOf(the) = 55
lastIndexOf(t, 60) = 55
lastIndexOf(the, 60) = 55
xi) length()
1. replace()
2. replaceAll()
3. replaceFirst()
1. replace()
The replace() method replaces every occurrence of a given character with a new
character and returns a new string.
The general form is:
StringObject.replace(char original, char replacement)
Here, original specifies the string to be replaced by the string specified by replacement.
The resulting string is returned.
Example:
2. replaceAll()
The replaceAll() method returns a new string where each occurrence of the matching
substring is replaced with the replacement string.
The general form is:
StringObject.replaceAll(String regex, String replacement)
Here,
regex - regular expression that is to be replaced
replacement -matching substrings are replaced with this string
Example:
Matching of the string starts from the beginning of a string (left to right). The general
form is:
StringObject.replaceFirst(String regex, String replacement)
Here,
regex − regular expression.
replacement − the string that replaces regular expression.
Example:
//Java program to demonstrate replaceFirst method
import java.io.*;
public class repFirst_Ex
{
public static void main(String args[])
{
String Str = new String("Welcome to SindhicollegeSindhi");
System.out.print("Original String : " );
System.out.println(Str);
System.out.print("After replacing 1st occurrence of regex with replacement : " );
System.out.println(Str.replaceFirst("Sindhi", "Alpha"));
}
}
Output:
Original String : Welcome to SindhicollegeSindhi
After replacing 1st occurrence of regex with replacement : Welcome to
AlphacollegeSindhi
xiii) startsWith()
The startsWith() method checks whether the given string begins with the
specified string or not.
The general form is:
StringObject.startsWith(String str)
Here, str is the String being tested. If the string matches, true is returned. Otherwise,
false is returned.
Example:
//Java program to demonstrate startsWith method
import java.io.*;
class StartsWith_Ex
{
public static void main(String args[])
{
String str = "Java Programming";
System.out.println(str.startsWith("Java"));
System.out.println(str.startsWith("Program"));
}
}
Output:
true
false
xiv) substring()
1. substring(jnt StartIndex)
The substring() method is used to extract a part of the string.
The general form is:
StringObject.substring(int StartIndex)
Here, StartIndex specifies the beginning index
Example:
//SubstrExample
import java.io.*;
public class Substr_Ex1
{
public static void main(String args[])
{
String Str = new String("Welcome to DataPoint");
System.out.print("The extracted substring is : ");
System.out.println(Str.substring(11));
}
}
Output:
xvi) toLowerCase()
The toLowerCase() method is used to convert all the characters of a string to lowercase
letters.
The general form is:
StringObject.toLowerCase()
Example:
Example:
Example:
Output:
The StringBuffer class in Java is same as String class except it is mutable i.e. it can be
changed.
1. StringBuffer Constructors
StringBufferObject.append(String str)
Example:
//Java program to demonstrate append method
import java.io.*;
public class StringBuffer_AppendEx
{
public static void main(String args[])
{
StringBuffer str = new StringBuffer("Sindhi");
str.append("College");
System.out.println(str);
}
}
Output:
SindhiCollege
ii) capacity()
The capacity()method returns the allocated capacity of the StringBuffer object.
The general form is:
StringBufferObject.capacity()
Example:
//Java program to demonstrate capacity() method
import java.io.*;
public class StrBuffer_CapacityEx
{
public static void main(String args[])
{
StringBuffer str = new StringBuffer();
System.out.println(str.capacity());
}
}
Output:
16
The delete()method is used to delete the string from the specified startIndex to endIndex.
The general form is:
StringBufferObject.delete(int startIndex, int endIndex)
Here, startIndex specifies the index of the first character to remove, and endIndex
specifies an index of the last character to remove. Thus, the substring deleted runs from
startIndex to endIndex-1. The resulting StringBuffer object is returned.
Example:
//Java program to demonstrate delete method
import java.io.*;
public class StringBuffer_DeleteEx
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Java lang package");
System.out.println("Given String = " + sb);
// Deleting characters from index 4 to index 9
sb.delete(4, 9);
System.out.println("After deletion = " + sb);
}
}
Output:
Given String = Java lang package
After deletion = Java package
v) deleteCharAt(int index)
Example:
Output:
16
34
vii) getChars()
The getChars() method copies characters from the given string into the destination
character array.
The general form is:
. StringBufferObject.getChars(int srcStartIndex,int srcEndIndex,char[]destArray,int
destStartIndex)
Here,
srcStartIndex: Index of the first character in the string to copy.
srcEndIndex: Index after the last character in the string to copy.
destArray: Destination array where chars wil get copied.
destStartIndex: Index in the array starting from where the charswill be pushed into the
array.
Example:
Output:
Sindhi College
viii) insert()
The insert() method is used to insert the given string at the specified index.
There are various overloaded insert() methods available in StringBuffer class.
The few forms of the insert() method are:
StringBufferObject.insert(int index, String str)
StringBufferObject.insert(int index, char ch)
StringBufferObject.insert(int index, Object obj)
Here, index specifies the index at which point the string will be inserted into the
invoking StringBuffer object.
Example:
//Java program to demonstrate insert() method of StringBuffer class
import java.io.*;
class Insert_Example
{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//Now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:
HJavaello
ix) indexOf()
The indexOf() method is used to return the index of the first occurrence of the specified
substring.
In StringBuffer class, there are two types of indexOf() method depending upon the
parameters passed to it.
1. indexOf(String str)
This method returns the position of the first occurrence of the specified substring within
the original string.
If the substring str is not present, then -1 is returned.
The general form is:
StringBufferObject.indexOf(String str)
Here, str is the string to be searched.
Example:
The length()method is used to return the length of the string i.e. total number of
characters.
The general form is:
StringBufferObject.length()
Example:
//Java program to demonstrate length() method
import java.io.*;
public class Length_Ex
{
public static void main(String args[])
{
StringBuffer Str = new StringBuffer("Sindhi College");
// Printing the length of stringbuffer
System.out.println("Length = " + Str.length());
}
}
Output:
Length = 14
xii) replace()
The replace() method is used to replace one string with another string.
The substring being replaced is specified by the indexes startIndex and endIndex. Thus,
the substring at the startIndex through endIndex–1 is replaced.
The general form is:
StringBufferObject.replace(int startIndex, int endIndex, String str)
Here,
StartIndex - It is the starting index of the substring
EndIndex - It is the end index (exclusive) of the substring.
Str - It is a string which replaces the substring from this sequence.
Example:
//Java program to demonstrate replace() method
import java.io.*;
public class Replace_Ex
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Program compile time");
System.out.println("Given String: "+sb);
System.out.println("After replace: "+sb.replace(8, 15, "run"));
}
}
Output:
Given String: Program compile time
After replace: Program run time
xiii) reverse()
Output:
Given String: abc
Character at index 1: bc
New String: axc
Character at index 1: xharacter at index 1: b
xv) setLength()
The setLength() method is used to set the new length of the string.
The general form is:
StringBufferObject.setLength(int len)
Here, len specifies the length of the buffer. This value must be nonnegative. When we
increase the size of the buffer, null characters are added to the end of the existing buffer.
Example:
//Java program to implement setLength method
import java.io.*;
public classSetLength_Example
{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("Sindhi College");
System.out.println("Given String: "+sb);
System.out.println("Length: "+sb.length());
//Set new length of character sequence
sb.setLength(7);
System.out.println("Set new length: "+sb.length());
System.out.println("New String: "+sb);
}
}
Output:
Given String: Sindhi College
Length: 14
Set new length: 7
New String: Sindhi
xvi) substring()
The substring() method is used to extract a substring from the original string.
There are two overloaded substring() methods available in StringBuffer class. These
methods are differentiated on the base of their parameters.
1. substring(int startIndex)
This method is used to return the substring from the specified startIndex.
The general form is:
StringBufferObject.substring(int startIndex)
This form will extract substring from startIndex till the end of the buffer.
Example:
//Java program to demonstrate substring(int startIndex) Method
import java.io.*;
public class SubString_Ex1
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("StringBuffer");
System.out.println("Given String: "+sb);
String sub_str= sb.substring(6);
System.out.println("Sub String from start index 6= "+sub_str);
}
}
Output:
Given String: StringBuffer
Sub String from start index 6= Buffer
2. substring(int startIndex, int endIndex)
This method is used to return the substring from the specified startIndex and endIndex.
The general form is:
StringBufferObject.substring(int startIndex, int endIndex)
This will extract a substring from startIndex till the endIndex but won't
include the character at endIndex.
Example:
//Java program to demonstrate sunstring(int StartIndex, int endIndex) method
import java.io.*;
public class Substring_Ex2
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Java is a programming language");
System.out.println("Given String: "+sb);
String sub_str= sb.substring(10,20);
//Sub string from start index 10 and end index 20
System.out.println("Sub string from index 10 to 20: "+sub_str);
}
}
Output:
stva is a programming language
Given String: Java is a programming languageequence from index 10 to 22:
string from index 10 to 22: programming
xvii) toString()
The toString() method can be used to convert a StringBuffer object to a String.
The general form is:
StringBufferObject.toString()
Example: