[go: up one dir, main page]

0% found this document useful (0 votes)
61 views107 pages

Unit 1

JAVA

Uploaded by

Meera
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)
61 views107 pages

Unit 1

JAVA

Uploaded by

Meera
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/ 107

OBJECT ORIENTED PROGRAMMING WITH JAVA(SBSB5113)

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

8 Structure of a Java Program


 Every Java program is written as a collection of one or more classes. Each class contains
data members and methods that act upon data members.
 The methods contain executable statements. Even though a Java program contain many
classes, only one of them should contain the main() method.
 The execution of a Java program starts with the main() method.
 A Java program can contain one or more sections as shown below.

Documentation Section <---------- Suggested


Package Statement <---------- Optional
Import Statements <---------- Optional
Interface Statements
<---------- Optional
Class Definitions
<---------- Optional
Main Method Class
{
Main Method Definition <---------- Essential
}

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:

/* This program receives the salary of an employee


and computes the incentive
*/
 The documentation comment is used to produce an HTML file that documents our
program. The documentation comment begins with a /** and ends with a */.
Package Statement
 The package statement is optional. If a package program involves the package statement,
it should be written as the first statement of that program.
Import Statements
 The import statement is placed next to the package statement in a Java program. Suppose
that in a Java program we refer to a class which is within the predefined package named
io, which in turn is within another predefined package named java. We have to write the
following import statement in such a Java program.
import java.io.*;
This statement instructs the Java interpreter to load the classes in the io package, which is
within the java package. Each predefined package in Java, such as io and Java, will
contain several classes. The import statement in Java is similar to the #include statement
in C++.
Interface Statements
 An interface is like a class but include a group of method declarations. This is also an
optional section and is used only when we wish to implement the multiple inheritance
feature in the program.
Class Definitions
 A Java program may contain multiple class definitions. A Java class is made up of data
members and methods that act upon these data members. Each method shall contain one or
more executable statements. Each Java program shall have one or more classes. The
number of classes used depends on the complexity of the problem.
Main Method Class
 The main method class is the essential part of a Java program. A simple Java program
may contain only this part. The main method creates objects of various classes and
establishes communications between them. On reaching the end of main, the program
terminates and the control passes back to the operating system.
2.9 Simple Java Program
//Example.java
class Example
{
public static void main(String args[])
{
System.out.println(“Welcome to Java Programming.”);
}
}
Class declaration
The first line
class Example
declares a class, which is an object-oriented concept. Java is a true object-oriented language
and therefore, everything must be placed inside a class. class is a keyword and declares that a
new class definition follows. Example is a Java identifier that specifies the name of the class
to be defined.
Opening brace
Every class definition in Java begins with an opening brace “{“ and ends with a matching
closing brace “}”, appearing in the last line in the example.
The main line
public static void main(String args[])
declares a method named main. Conceptually, this is similar to the main() function in C / C+
+. Every Java application program must include the main() method. This is the starting point
for the interpreter to begin the execution of the program. A Java application can have any
number of classes but only one of them must include a main method to initiate the execution.
This line contains a number of keywords, public, static and void.
-----------------------------------------------------------------------------------------------------------------
------
public The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes. This is similar to
the C++ public modifier.
Static Next appears the keyword static, which declares this method as one that belongs to
the entire class and not a part of any object of the class. The main must always be
declared as static since the interpreter uses this method before any objects are
created.
void The type modifier void states that the main method does not return any value.
----------------------------------------------------------------------------------------------------------------
-------
All parameters to a method are declared inside a pair of parentheses. Hence, String args[]
declares a parameter named args, which contains an array of objects of the class type String.
The Output Line
The only executable statement in the program is
System.out.println(“Welcome to Java Programming.”);
This is similar to the printf() statement of C or cout<<construct of C++. Since Java is a true
object oriented language, every method must be part of an object. The println method is a
member of the out object, which is a static data member of System class This line prints the
string
Welcome to Java Programming.
on the screen. The method always appends a newline character to the end of the string. This
means that any subsequent output will start on a new line. Every Java statement must end with
a semicolon.
2.10 Java Character Set
 The set of characters allowed in Java constitutes its character set. All the constituents
of a Java program, such as identifiers, literals, keywords, expression and statements are
written only by using the characters in the following character set:
Numerals : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Alphabets : 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

: 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

Special Characters : +, -, *, /, %, =, <, >, (, ), ‘, ,, :, ?, #, $, !, ^, ~, [, ], {, }


 Java uses the uniform 16-bit coding scheme called UNICODE to represent characters
internally. The Unicode can incorporate 65000 characters.
2.11 Lexical Issues
 Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
Whitespace
 A space, tab, or newline is called a whitespace in Java.
 Java is a free-form language. This means that we do not follow any special indentation
rules. There must be at least one whitespace character between each token that was not
already delineated by an operator or separator.
Identifiers

 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

 A sequence of valid characters that represent a constant value is called a literal.


 Literals are also known as constants. Java language specifies five major types of
literals. They are:
 Integer literals
 Floating-point literals
 Character literals
 String literals
 Boolean literals
Comments
 There are three types of comments defined by Java: Single-line Comment, Multline
Comment and Documentation Comment. This type of comment is used to produce an
HTML filethat documents our program. The documentation comment begins with a

/**and ends with a */.

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:

Symbol Name Purpose


() Parentheses Used to contain lists of parentheses in method definition and
invocation. Also used for defining precedence in
expressions, containing expressions in control statements,
and surrounding cast types.
{} Braces Used to contain the values of automatically initialized
arrays. Also, used to define a block of code for classes,
methods, and local scopes.
[] Brackets Used to declare array types. Also used when dereferencing
array values.
: Semicolon Used to separate statements.
, Comma Used to separate consecutive identifiers in a variable
declaration, also used to chain statements together inside a
‘for’ statement.
. Period Used to separate package names from sub-packages and
classes.Also, used to separate a variable or method from a
reference variable.
:: Colons Used to create a method or constructor reference.
… Ellipsis Indicates a variable-arity parameter.
@ Ampersand Begins an annotation.

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)

abstract assert boolean break byte case


catch char class const continue default
do double else enum exports extends
final finally float for goto if
implements import instanceof int interface long
module native new open opens package
private protected provides public requires return
short static strictfp super switch synchronized
this throw throws to transient transitive
try uses void volatile while with
Table 2.1: Java Keywords
2.12 Java Statements
 A statement is an executable combination of tokens ending with a semicolon (;) mark.
Java statements are instructions that tell the programming language what to do. Java
implements several types of statements described in table below.
Summary of Java Statements
Statement Description Remarks
Empty Statement These do nothing and are used Same as C and C++
during program development as a
place holder.
Labeled Statement Any statement may begin with a Identical to C and C++
label. Such labels must not used as except their use with
keywords,. jump statements
Expression Statement Java has several types of Same as C++
Expression statements: Assignment,
pre-Increment/decrement, Post-
Increment/decrement, Method Call
and Allocation Expression.
Selection Statement There are three types of selection Same as C and C++
statements in Java: if, if-else, and
switch.
Iteration Statement There are three types of iteration Same as C and C++
statements: while, do and for. except for jumps and
labels
Jump Statement Jump statements pass control to the C and C++ do not use
labeled statement. The four types of labels with jump
Jump statement are: break, continue, statements
return and throw.
Synchronization Statement These are used for handling issues Not available in C and
with multi-threading. C++
Guarding Statement These are used to handle Same as in C++ except
exceptions. Thestatements use the finally statement
keywords try, catch, and finally.

Figure 2.1: Classification of Java Statements


2.13 Implementing a Java Program
 Implementation of a Java application program involves a series of steps. They include:
 Creating the program
 Compiling the program
 Running the program
Creating the Program
 To enter the program, we can use any word processor, such as MS-Word or the Windows
Notepad editor or the DOS editor. Assume that we have entered the following program:

//Simple Java Program


class Example
{
public static void main(String args[])
{
System.out.println(“Welcome to Java programming.”);
}
}
 Save this program in a file called Example.java ensuring that the file name contains the
class name properly. This file is called the source file.

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.

Compiling the Program

 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:

//Java program that uses command line arguments as input


class CmdLineTest
{
public static void main(String args[])
{
int count,i=0;
String str;
count=args.length;
System.out.println("Number of arguments = "+count);
while(i<count)
{
str=args[i];
i=i+1;
System.out.println(i +" : "+"Java is "+str+"!");
}
}
}
Compile and run the program with the command line as follows:
Java CmdLineTest Simple Object-Oriented Distributed Robust Secure Portable Multithreaded Dynamic
Upon execution, the command line arguments Simple, Object-Oriented, etc. are passed to the
program through the array args. That is the element args[0] contains Simple, args[1] contains
Object-Oriented and so on.
The output of the program would be s follows:
Number of arguments = 8
1: Java is Simple!
2: Java is Object-Oriented!
3: Java is Distributed!
4: Java is Robust!
5: Java is Secure!
6: Java is Portable!
7: Java is Multithreaded!
8: Java is Dynamic!
Exercises:
1. Define OOP.
2. Define Class.
3. What is an Object?
4. Write the benefits of OOP.
5. List out few applications of OOP.
6. Define Bytecode.
7. What is JDK in Java?
8. Define API.
9. Explain briefly about the Strucutre of a Java Program.
10. Explain the various access specifiers used in Java.
11. Discuss in detail about Java Character Set.
12. What are Java Keywords?
13. Explain the various kinds of Java statements.
14. Define JVM.
15. What are Command Line Arguments in Java?
**************************

*******************************************************************
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

Figure 3.1: Data Types in Java

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.

Figure 3.3: Floating Point Data Types


The following table gives the size and range of these two types:
--------------------------------------------------------------
Type Size Range
--------------------------------------------------------------
float 4 bytes 3.4e-038 to 3.4e+038
double 8 bytes 1.7e-308 to 1.7e+308
--------------------------------------------------------------
float
 The type float specifies a single-precision value that uses 32 bits of storage.
 Variable of type float are useful when we need a fractional component, but don’t
require a large degree of precision.
 For example, float can be useful when representing dollars and cents.
Example:
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(), sqrt(), return double values.
 When we need to maintain accuracy over many iterative calculations, or are
manipulating large-valued numbers, double is the best choice.
Example:
double pi;
Character Type
 Character Data Types are used to store character constants in memory.
 In Java, the character data type is denoted by the keyword char.
 The char type assumes a size of 2 bytes but, basically, it can hold only a single
character. The range of a char is 0 to 65,536.

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

 The mantissa is either a real number expressed in decimal notation or an integer.


 The exponent is an integer with an optional plus or minus sign. The letter e separating
the mantissa and the exponent can be written in either lowercase or uppercase.
 Since the exponent causes the decimal point to “float”, this notation is said to represent a
real number in floating point form.
 Examples of legal floating point constants are:
0.65e4 12e-2 1.5 e+5 3.18E3 -1.2 E-1
 A floating point constant may thus comprise four parts:
 a whole number
 a decimal point
 a fractional part
 an exponent
Single Character Constants
 A Single Character Constant (or simply character constant) contains a single
character enclosed within a pair of single quote marks.
 Examples of character constants are:
'5' 'X' ';' 'a'

Note: Character Constant '5' is not the same as the number 5.


String Constants
 A String Constant is a sequence of character enclosed between double quotes.
 The characters may be alphabets, digits, special characters and blank spaces. Examples
are:
"Hello Java" "1997" "WELLDONE” “?...!” “5+3" "X"
Backslash Character Constants
 Java supports some special backslash character constants that are used in output
methods.
 For example, the symbol ‘\n’ stands for newline character.

 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’;

3.4 Giving Values to Variables


 A variable must be given a value after it has been declared before it is used in an
expression.
 This can be declared in two ways:
 By using an assignment statement
The assignment statement is used to assign a value to a variable.
variableName=value;
type variableName=value;
 By using a read Statement
The readLine() method is used to read a line of text from the keyboard.
int n=Integer.parseInt(br.readLine());
3.5 Scope of Variables
 The area of the program where the variable is accessible (i.e., usable) is called its
scope.
 Java allows variables to be declared within any block. A block defines the scope.
 Java variables are classified into three parts:
 Instance Variables
 A variable declared outside the method/block/constructor but inside the body is
called an instance variable.
 When an object of the class is created then the object also creates one copy of the
instance variable and destroyed when the object is destroyed.
 We can specify the access specifier for instance variables. By default, the default access
specifier will be used.
 Initialization of Instance Variable is not Mandatory. Its default value is depending on
the data type of variable.
 These variables can be accessed by creating objects.
 Class Variables
 Class Variables are declared inside a class.
 Class variables are global to a class and belong to the entire set of objects that class
creates.
 Only one memory location is created for each class variable.
 Local Variables
 A variable declared inside the body of a method or block or constructor is called a
local variable.
 We can’t access these variable outside the method. These variables are created in
memory when the function/block/constructor is called. After completing the execution
of function/block/constructor these variables are destroyed by JVM.
 We can access these variables only within that block because the scope of these
variables exists only within the block.
 The initialization of the local variables is mandatory. If we don’t initialize the variable
compiler will throw run time exception.
3.6 Symbolic Constants
 Memory locations whose values cannot be changed within a program are called
Constants or Symbolic Constants.
 A constant is declared as follows:
final type symbolic-name=value;
Examples:
final int PASS_MARK=50;
final float PI=3.14159;
Note:
 Symbolic names take the same form as variable names. But, they are written in
CAPITALS because they are distinguished them from normal variable names.
 After declaration, they should not be assigned any other value within the program.
 They can't be declared inside of a class. They should be declared as beginning of the
class.
3.7 Type Conversion and Type Casting
 The two terms Type Conversion and the Type Casting are used in a program to
convert one data type to another data type.
Type Conversion
 Type Conversion allows a compiler to convert one data type to another
data type at the compile time of a program or code.
 Converting a lower data type to a higher data type is known as widening.
 In this case the conversion is done automatically therefore, it is known as implicit
type casting.
 In this case both data types should be compatible with each other.

Example 1:

int x = 20;
long y = x; // Automatic Conversion

Example 2:

//Java Program to implement Type Conversion


public class TypeConversionExample
{
public static void main(String args[])
{
char ch = 'C';
int i = ch;
System.out.println("Integer value of the given character: "+i);
}
}
Output:
Integer value of the given character: 67
Type Casting
 Type Casting is a mechanism in which one data type is converted to another
data type by a programmer.
 Converting a higher data type to a lower data type is known as narrowing.
 In this case the casting is not done automatically, we need to convert explicitly using
the cast operator “( )” explicitly. Therefore, it is known as explicit type casting.
 In this case both data types need not be compatible with each other.

 The syntax is:


type variable1=(type) variable2;
Example 1:
int m=50;
byte n=(byte)m;
long count=(long)m;
Example 2:
//Java Program to implement Type Casting
import java.util.*;
public class TypeCastingExample
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer value: ");
int i = sc.nextInt();
char ch = (char) i;
System.out.println("Character value of the given integer: "+ch);
}
}
Output:

Enter an integer value:


67
Character value of the given integer: C
Differences Between Type Casting and Type Conversion
Sl. No. Type Casting Type Conversion
1 Type Casting is a mechanism in which Type Conversion allows a compiler to
one data type is converted to another data convert one data type to another data type at
type by a programmer. the compile time of a program or code.
2 It can be used both compatible data type Type Conversion is only used with
and incompatible data type. compatible data types.
3 It requires a programmer to manually The compiler automatically converts it at
casting one data into another type. the run time of a program.
4 It is used while designing a program by It is used or take place at the compile time
the programmer. of a program.
5 When casting one data type to another, When converting one data type to another,
the destination data type must be smaller the destination type should be greater than
than the source data. the source data type.
6 It is also known as narrowing It is also known as widening conversion
conversion because one larger data type because one smaller data type converts to a
converts to a smaller data type. larger data type.
7 It is more reliable and efficient. It is less efficient and less reliable.
8 There is a possibility of data loss in type Possibility of data loss is very less
casting.
9 float b = 3.0; int x = 5, y = 2, c;
int a = (int) b float q = 12.5, p;
p = q/x;

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

Here, Condition is a boolean expression. It returns either true or false.


If a user doesn’t provide curly braces (‘{‘ ‘}’ ) then by default only one statement will be
considered inside the if block.
Example:
// Java program to demonstrate Simple if Statement
import java.io.*;
public class IfStatementDemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a, b;
System.out.println("Enter the first number");
a=Integer.parseInt(br.readLine());
System.out.println("Enter the second number");
b=Integer.parseInt(br.readLine());
if (a > b)
{
System.out.println("Biggest="+a);
}
System.out.println("Biggest="+b);
}
}
Output:
Enter the first number
10
Enter the second number
20
Biggest=20
ii) The if…else Statement
 The if…else Statement is used to execute a block of code if the condition is true and
another block of code if the condition is false.
 We can either have a single statement or a block of code within if…else blocks.
Syntax:
if (Condition)
{
//Statements;
}
else
{
//Statements;
}
Here, Condition is a boolean expression. It returns either true or false.
Example :
//Java program to check whether the given number is odd or even
//oddeven.java
import java.io.*;
class oddeven
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n,r;
System.out.println("Enter the number");
n=Integer.parseInt(br.readLine());
r=n%2;
if (r==0)
System.out.println("The given number is even");
else
System.out.println("The given number is odd");
}
}
Output:
Enter the number
5
The given number is odd
iii) Nested if…else Statement
 An if…else statement within another if…else statement is called nested if…else
statement.
 When a series of decisions are involved, we may have to use more than one if…else
statement in nested form as follows:
if (Condition-1)
{
if (Condition-2)
{
//Statement-1;
}
else
{
//Statement-2;
}
}
else
{
//Statement-3;
}
//Statement-x;

 If the Condition-1 is false, Statement-3 will be executed; otherwise, it continues to


perform the second test. If the condition-2 is true, the Statement-1 will be
evaluated; otherwise the Statement-2 will be evaluated and then the control is
transferred to the Statement-x.

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:

//Java Program to implement if-else-if ladder


//PrintStudentGrade.java
import java.io.*;
class PrintStudentGrade
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int marks;
System.out.println("Enter the marks");
marks=Integer.parseInt(br.readLine());
if( marks >= 75 )
{
System.out.println("Distinction");
}
else if( marks >= 60 )
{
System.out.println("First Class");
}
else if( marks >= 50 )
{
System.out.println("Second Class");
}
else
{
System.out.println("Fail");
}
}
}
Output:
Enter the marks
75
Distinction
2. The switch Statement
 The switch statement is a multiway branch statement. It provides an easy way to
dispatch execution to different parts of code based on the value of the expression.
 It often provides a better alternative than a large series of if-else-if statements.
Syntax:
switch(expression)
{
case value1:
// Statements
break;
case value2:
//Statements
break;
.
.
.
default:
//Default Statement
}

 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

Differences Between if..else and switch Statements

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'.

5.3 Looping Statements


 The process of repeatedly executing a block of statements is known as looping.
 The Java language provides three constructs for performing loop operations. They are:
1. The while Statement
2. The do…while Statement
3. The for Statement

1. The while Statement

 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:

//Java program to add individual digits of an n digit number


//add_digt.java
import java.io.*;
class add_digt
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n,r,s=0;
System.out.println("Enter the number");
n=Integer.parseInt(br.readLine());
while(n>0)
{
r=n%10;
s=s+r;
n=n/10;
}
System.out.println("Sum of all digits="+s);
}
}
Output:
Enter the number
125
Sum of all digits=8
2. The do…while Statement

 The do...while loop executes a block of code repeatedly until the specified condition
is true.

 It is also known as an Exit-Controlled Loop.

 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

break Statement continue Statement


1. It is used to jump out of the loop. 1. It is used to break a single iteration.
2. The loop gets terminated or halted 2. The loop gets halted only for a single
permanently when the break statement iteration when the continue Java statement
condition matches. condition matches.
3. It is very commonly used with the “switch 3. It is not compatible with the “switch
statements”. statements”.

3. The return statement


 The return statement can be used to return a value from a method.
 The return statement causes the program control to transfer back to the caller of a
method.
 The general form of return statement is
return;
return expression;
Example:
//Java Program to demonstrate continue statement
import java.io.*;
public class Test
{
int square(int s)
{
return s * s; // Return a square value.
}
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
Test t = new Test();
int n;
System.out.println(“Enter the value of n”);
n = Integer.parseInt(br.readLine());
int sq = t.square(n);
// Displaying the result.
System.out.println("Square of “ + n +”= " +sq);
}
}
Output:
Enter the value of n
10
Square of 10 = 100
Nested Loops
 Nested loop means a loop statement inside another loop statement.
 When we "nest" two loops, the outer loop takes control of the number of complete
repetitions of the inner loop.
1. Nested for loop
 Placing one for loop within the body of another for is called nested for loop.
Syntax:
for ( initialization; condition; increment/decrement )
{
for ( initialization; condition; increment/decrement )
{
// Statement of inner loop
}
// Statement of outer loop
}
Example:
//Demonstrate Nested for loop
//NestedForLoop.java
public class NestedForLoop
{
public static void main(String[] args)
{
for(int i=1;i<=5;i++)
{
for(int j=1;j<=i;j++)
{
System.out.print(i);
}
System.out.println();
}
}
}
Output:
1
22
333
4444
55555
2. Nested while loop
 A nested while loop is a while statement inside another while statement
Syntax:
while(condition)
{
while(condition)
{
// Statement of inner loop
}
// Statement of outer loop
}
Example:
//Java program to demonstrate nested while loop
class NestedWhileExample
{
public static void main(String args[])
{
int outer = 1;
while(outer < 3)
{
int inner = 5;
while(inner < 8)
{
System.out.println(outer + " " + inner);
inner++;
}
outer++;
}
}
}

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

int rectArea() // Definition of another method


{
int area=length*width;
return(area);
}
}
class RectArea // Class with main method
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int l,b,area1;
Rectangle rect1=new Rectangle(); // Creating an object
System.out.println("Enter the length");
l=Integer.parseInt(br.readLine());
System.out.println("Enter the breadth");
b=Integer.parseInt(br.readLine());
rect1.getData(l,b);
area1=rect1.rectArea();
System.out.println("Area of the rectangle="+area1);
}
}
Output:
Enter the length
10
Enter the breadth
15
Area of the rectangle=150
7.9 Constructors
 A Constructor is a special member function whose task is to initialize the objects of
its class.
 Constructors have the same name as the class name.
 Constructors are automatically called when an object is created.
 It is called constructor because it constructs the values of data members of the class.
 Constructors do not have a return type; not even void.
 A constructor can be overloaded.
Types of Constructors
 There are two types of constructors. They are:
1. Default Constructor (Constructor with no argument)
2. Parameterized Constructor.
1. Default Constructor
 A constructor that has no parameter is known as the default constructor.
 The default constructor automatically initializes all instance variables to zero.
 The general form is
constructorname() // Constructor with no argument
{
// Give initial values to data members
}
Where, constructorname is the name of the class.
Example:
// Java Application using default constructor
// RectangleArea.java
class Rectangle
{
int length, width; // Declaration of variables
Rectangle() // Default Constructor
{
length=10;
width=15;
}
int rectArea()
{
return(length*width);
}
}
class RectangleArea // Class with main method
{
public static void main(String args[])
{
Rectangle rect1=new Rectangle(); // Calling constructor
int area1=rect1.rectArea();
System.out.println("Area of the rectangle="+area1);
}
}
Output:
Area of the rectangle=150
2. Parameterized Constructors
 A constructor that has parameters is known as parameterized constructor
 The parameterized constructor is used to provide different values to distinct objects.
 The general format of the parameterized constructor is as follows:
constructorname(datatype arg1, datatype arg2,…datatype argN)
{
// Give initial values to data members
}
where, constructorname is the name of the class.
datatype arg1, datatype arg2,… are the list of parameters
Example:

// Java Application using Parameterized Constructors


// RectangleArea.java
import java.io.*;
class Rectangle
{
int length, width; // Declaration of variables
Rectangle(int x, int y) // Defining parameterized constructor
{
length=x;
width=y;
}
int rectArea()
{
return(length*width);
}
}
class RectangleArea // Class with main method
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int l, b;
System.out.println("Enter the length");
l=Integer.parseInt(br.readLine());
System.out.println("Enter the breadth");
b=Integer.parseInt(br.readLine());
Rectangle rect1=new Rectangle(l,b); // Calling constructor
int area1=rect1.rectArea();
System.out.println("Area of the rectangle="+area1);
}
}
7.10 The this keyword
 The this keyword is used to refer to the current object.
 It can be used inside the method or constructor of a class.
 The most common use of this keyword is to eliminate the confusion between class
attributes and the parameters with the same name.
 Methods declared with the keyword static (class methods) cannot use this.
Example:
// Java program that illustrates the usage of the keyword this
// ThisDemo.java
import java.io.*;
class Sample
{
int x,y;
void GetData(int x, int y)
{
this.x=x;
this.y=y;
}
void Display()
{
System.out.println("x="+x);
System.out.println("y="+y);
}
}
class ThisDemo
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b;
System.out.println("Enter the values of a & b");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
Sample obj=new Sample();
obj.GetData(a,b);
obj.Display();
}
}
Output:
Enter the values of a & b
30
40
x=30
y=40

7.11 Method Overloading

 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:

// Java program to demonstrate Method Overloading


import java.io.*;
public class Sum_Nos
{
public int sum(int x, int y)
{
return (x + y);
}
public int sum(int x, int y, int z)
{
return (x + y + z);
}
public double sum(double x, double y)
{
return (x + y);
}
// Main Program
public static void main(String args[])
{
Sum_Nos S = new Sum_Nos();
System.out.println(S.sum(10, 20));
System.out.println(S.sum(10, 20, 30));
System.out.println(S.sum(10.5, 20.5));
}
}

Output:

30
60
31.0

7.12 Overloading Constructors


 The technique of having two or more constructors in a class is known
as constructor overloading.
 A class can have multiple constructors that differ in the number and/or type of their
parameters.
Example:
// Java program to implement Constructor Overloading
// Student.java
import java.io.*;
class Student
{
int id;
String name;
int age;
Student(int i, String n)
{
id = i;
name = n;
}
Student(int i, String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
public static void main(String args[])
{
Student s1 = new Student(111,"Sun");
Student s2 = new Student(222,"Chandra",16);
s1.display();
s2.display();
}
}
Output:
111 Sun 0
222 Chandra 16
7.13 Objects as Parameters

 Objects can also be passed to methods.


 Objects are implicitly passed by use of call-by-reference.
Example:
// Passing Object as Parameter in Function
// Add_Nos.java
import java.io.*;
class Add
{
int a;
int b;
Add(int x, int y) // Parametrized Constructor
{
a=x;
b=y;
}
void sum(Add A1) // Object 'A1' passed as parameter in function 'sum'
{
int c=A.a+A.b;
System.out.println("Sum of a and b: "+c);
}
}
public class Add_Nos
{
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int m, n
System.out.println(“Enter the first number”);
m=Integer.parseInt(br.readLine());
System.out.println(“Enter the second number”);
n=Integer.parseInt(br.readLine());
Add A=new Add(m, n);
A.sum(A);
}
}
Output:
Enter the first number
10
Enter the second number
20
Sum of a and b: 30

7.14 Passing arguments to methods


 There are two ways of passing arguments to methods. They are:
1. Call by Value
2. Call by Reference
1. Call by Value
 In Call by Value approach, the values of the actual parameters are copied into the formal
parameter list of a method.

 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.

 It is also known as Pass by Value.


2. Call by Reference
 In Call By Reference approach, the address of an argument is copied into the formal
parameter of the method.
 The actual and the formal parameters are stored in same memory locations.
 It means that changes made in the parameter alter the passing argument.
 It is also known as Pass by Reference.
Example 1:
// Java program that demonstrates Call By Value
// CallByValue.java
import java.io.*;
class Test
{
void meth(int i, int j)
{
i*=2;
j/=2;
}
}
class CallByValue
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b;
Test ob=new Test();
System.out.println("Enter the values of a & b");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
System.out.println(" a and b before call : "+a+" "+b);
ob.meth(a,b);
System.out.println(" a and b after call : "+a+" "+b);
}
}
Output:
Enter the values of a & b
15
20
a and b before call : 15 20
a and b after call : 15 20
Example 2:
// Objects are passed by reference
// CallByRef.java
import java.io.*;
class Test
{
int a,b;
Test(int i, int j)
{
a=i;
b=j;
}
void meth(Test o)
{
o.a*=2;
o.b/= 2;
}
}
class CallByRef
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int a,b;
System.out.println("Enter the values of a & b");
a=Integer.parseInt(br.readLine());
b=Integer.parseInt(br.readLine());
Test ob=new Test(a,b);
System.out.println(" a and b before call : "+ob.a+" "+ob.b);
ob.meth(ob);
System.out.println(" a and b after call : "+ob.a+" "+ob.b);
}
}
Output:
Enter the values of a & b
15
20
a and b before call : 15 20
a and b after call : 30 10
7.15 Returning Objects
 A method can return any type of data, including class types that we create.
Example:
// Returning an object
// RetOb.java
import java.io.*;
class Test
{
int a;
Test(int i)
{
a=i;
}

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:

// Java program to find the factorial of a number using recursion


// Recursion.java
import java.io.*;
class Factorial
{
int fact(int n)
{
if (n==1)
return 1;
else
return(n*fact(n-1));
}
}
class Recursion
{
public static void main(String args[]) throws IOException
{
Factorial f=new Factorial();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int m;
System.out.println("Enter the value of m");
m=Integer.parseInt(br.readLine());
System.out.println("Factorial of "+m +" is "+f.fact(m));
}
}
Output:
Enter the value of m
5
Factorial of 5 is 120
7.17 Inheritance
Definition
 The mechanism of deriving a new class from an old one is called inheritance. The old
class is known as the base class or super class or parent class and the new one is called
the subclass or derived class or child class.
Defining a Subclass
 A subclass is defined as follows:
class subclass-name extends superclass-name
{
Variables declaration;
Methods declaration;
}
 The keyword extends signifies that the properties of the superclass-name are extended to
the subclass-name.
 The subclass will now contain its own variables and methods as well those of the
superclass.
 This kind of situation occurs when we want to add some more properties to an existing
class without actually it.
Types of Inheritance
 There are various types of Inheritance in Java.
1. Single Inheritance (only one super class)
2. Multiple Inheritance (several super classes)
3. Hierarchical Inheritance (one super class, many sub classes)
4. Multilevel Inheritance (Derived from a derived class)

 These forms of inheritance are shown in Figure 7.1.


 Java does not implement multiple inheritance. However, this concept is implemented
using a secondary inheritance path in the form of interfaces.

Figure 7.1: Forms of Inheritance


1. Single Inheritance
 Single Inheritance is defined as the inheritance in which a derived class is inherited
from only one base class.
 It allows a derived class to inherit the properties and behavior of a base class, thus
enabling code reusability as well as adding new features to the existing code.
Syntax:
class Sub-classname extends Super-classname
{
// Variables and Methods
}
 The extends keyword indicates that we are creating a new class that derives from an
existing class.
 A class which is inherited is called a parent or superclass, and the new class is called child
or subclass.
Example:
// Java Application using Single Inheritance
//SingleInheritance.java
import java.io.*;
class Room
{
int length;
int breadth;
int area()
{
return (length*breadth);
}
}
class BedRoom extends Room
{
int height;
BedRoom(int x, int y, int z)
{
length= x;
breadth=y;
height=z;
}
int volume()
{
return (length*breadth*height);
}
}
class SingleInheritance
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int l,b,h;
System.out.println("Enter the length");
l=Integer.parseInt(br.readLine());
System.out.println("Enter the breadth");
b=Integer.parseInt(br.readLine());
System.out.println("Enter the height");
h=Integer.parseInt(br.readLine());
BedRoom room1=new BedRoom(l,b,h);
int area1= room1.area();
int volume1=room1.volume();
System.out.println("Area = "+area1);
System.out.println("Volume = "+volume1);
}
}
Output:
Enter the length
10
Enter the breadth
20
Enter the height
30
Area = 200
Volume = 600
The super keyword
 The super keyword in Java is used in subclasses to access superclass members.
 The most common use of the super keyword is to eliminate the confusion between
superclasses and subclasses that have methods with the same name.
 Super has two general forms. The first calls the superclass constructor. The second is
used to access a member of the superclass that has been hidden by a member of a
subclass.
i) Using super to Call Superclass Constructors
 A subclass can call a constructor method defined by its superclass by use of the following
form of super:
super(parameter-list);
Here, parameter-list specifies any parameter needed by the constructor in the superclass.
super() must always be the first statement executed inside a subclass constructor.
ii) A Second Use for super
 The second form of super acts somewhat like this, except that it always refers to the
superclass of the sublass in which it is used.
 This usage has the following general form:
super.member
Here, member can be either a method or an instance variable.
 This second form of super is most applicable to situations in which member names of a
subclass hide members by the same name in the superclass.
Example:
// Java program using super to overcome name hiding.
//SuperDemo.java
import java.io.*;
class A
{
int i;
}
// Create a subclass by extending class A.
class B extends A
{
int i; // this i hides the i in A
B(int a, int b)
{
super.i=a; // i in A
i=b; // i in B
}
void show()
{
System.out.println("i in superclass: "+super.i);
System.out.println("i in subclass : "+i);
}
}

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

Figure 7.2: Multilevel Inheritance


Syntax:
class A
{
// Variables and Methods
}
class B extends A
{
// Variables and Methods
}
class C extends B
{
// Variables and Methods
}
The class A serves as a base class for the derived class B, which in turn serves as a base class
for the derived class C. The class B is known as intermediate base class since it provides a
link for the inheritance between A and C.
Example:
// Java program to implement multilevel inheritance
import java.io.*;
class Car
{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car
{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
public class Maruti800 extends Maruti
{
public Maruti800()
{
System.out.println("Maruti Model: 800");
}
public void speed()
{
System.out.println("Max: 80Kmph");
}
public static void main(String args[])
{
Maruti800 obj=new Maruti800();
obj.vehicleType();
obj.brand();
obj.speed();
}
}
Output:
Class Car
Class Maruti
Maruti Model: 800
Vehicle Type: Car
Brand: Maruti
Max: 80Kmph

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

7.19 Differences between Method Overloading and Method Overriding in Java


 There are many differences between method overloading and method overriding in java.
 A list of differences between method overloading and method overriding are given
below:
Sl.
Method Overloading Method Overriding
No.
1) Method Overloading is used to Method Overriding is used to provide the
increase the readability of the program. specific implementation of the method
that is already provided by its super class.
2) Method Overloading is Method Overriding occurs in two classes
performed within class. that have IS-A (inheritance) relationship.
3) In case of method In case of method overriding, parameter
overloading, parameter must be must be same.
different.
4) Method Overloading is an example Method Overriding is an example for Run
for Compile Time Polymorphism. Time Polymorphism.
5) Return type can be same or different in Return type must be same in method
method overloading. But we must have overriding.
to change the parameter.

7.20 Final Variables and Methods


final Variables
 Variables that are declared with the final keyword are known as final variables.
 The value of a final variable cannot change after it has been initialized.
 Such variables are similar to constants in other programming languages.
 The general form is:
final type variablename=value;
Example 1:
final float PI=3.14159;
final int SIZE=100;
It is a common coding convention to choose all uppercase identifiers for final variables.
Variables declared as final do not occupy any memory on a per-instance basis. Thus, a
final variable is essentially a constant.
Example 2:
//Java Program to implement final variable
import java.io.*;
class Bike
{
final int SpeedLimit=90; //final variable
void run()
{
SpeedLimit=400;
}
public static void main(String args[])
{
Bike obj=new Bike();
obj.run();
}
}
Output:
Compile Time Error
final Methods
 The final keyword is used in a method declaration to indicate that the method
cannot be overridden by subclasses.
 Methods called from constructors should generally be declared final.
 A final method cannot be overriden or hidden by subclasses. This is used to prevent
unexpected behavior from a subclass altering a method that may be crucial to the function
or consistency of the class.
Example:
//Final Method Example
class Bike
{
final void run()
{
System.out.println("Running");
}
}
class Honda extends Bike
{
void run()
{
System.out.println("Running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
Output:
Compile Time Error
7.21 final classes
 A class that cannot be subclassed is called a final class.
 This is achieved in Java using the keyword final as follows:
final class A {………………}
final class B extends A {…………..}
 Any attempt to inherit these classes will cause an error and the compiler will not allow it.
 Declaring a class final prevents any unwanted extensions to the class
Example:

//Java Program to implement final classs


import java.io.*;
final class Bike
{
}
class Honda extends Bike
{
void run()
{
System.out.println("Running safely with 100kmph");
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
Output:
Compile Time Error
7.23 Garbage Collection
 Garbage Collection (GC) is a form of automatic memory management.
 Garbage Collection (GC) is the process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.

Advantages of Garbage Collection


 It makes Java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
 It is automatically done by the garbage collector (a part of JVM) so we don't need to
make extra efforts.
7.24 Finalizer Methods
finalize() method
 The finalize() method is called the finalizer.
 It is a protected method of java.lang.Object class.
 The finalize() method is invoked each time before the object is garbage collected.
 This method is used to perform some final operations or clean up operations on an object
before it is removed from the memory.
 We can override the finalize() method to keep those operations we want to perform
before an object is destroyed.
 The finalize() method has this general form:
protected void finalize()
{
// Finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize() by code
defined
outside its class.

Example:

//Java program that implements the finalize() method


import java.util.*;
public class ObjectDemo extends GregorianCalendar
{
public static void main(String args[])
{
try
{
ObjectDemo cal = new ObjectDemo();
// Print current time
System.out.println("" + cal.getTime());
// finalize cal
System.out.println("Finalizing...");
cal.finalize();
System.out.println("Finalized.");
}
catch (Throwable ex)
{
ex.printStackTrace();
}
}
}

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

 The String class supports several 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’};

String S=new String(chars);

This constructor initializes S with the string “abc”.

iii) String(char chars[], int startIndex, int numChars)


 This constructor is used to specify a sub range of a character array as an initializer. Here,
startIndex specifies the index at which the sub range begins, and numChars specifies
the number of characters to use.
Example:

char chars[]={‘a’, ’b’, ’c’, ’d’, ‘e’, ‘f’};

String S=new String(chars,2,3);

This initializes S with the characters “cde”.

iv) String(String strObj)


 This constructor is used to construct a String object that contains the same character
sequence as another. Here, strObj is a String object.
Example:

String S1=new String(“Java”);

String S2=new String(S1);

Here, S1 and S2 contain the same string.


v) String(byte asciiChars[])
vi) String(byte asciiChars[], int startIndex, int numChars)
 The String class provides constructors that initialize a string when given a byte array.
Here, asciiChars specifies the array of bytes. The second form allows us to specify a sub
range. In each of these constructors, the byte-to-character conversion is done by using the
default character encoding of the platform.
Example:

byte ascii[] ={65, 66, 67, 68, 69, 70};


String S1=new String(ascii)
System.out.println(S1); // ABCDEF
String S2=new String(ascii,2,3);
System.out.println(S2); // CDE

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 compareTo() method is used to compare two stringslexicographically (in the


dictionary order).
 This method is returns negative if string1 is less than string2, positive if string1 is greater
than string2, and zero if string1 is equal to string2.
 The general form is:
StringObject.compareTo(string)
Example:
//Java program to compare strings
import java.io.*;
class CompareTo_Ex
{
public static void main(String args[])
{
String Str1 = "Learn Java";
String Str2 = "Learn Java";
String Str3 = "Learn Python";
int result;
// Comparing Str1 with Str2
result = Str1.compareTo(Str2);
System.out.println(result); // 0
// Comparing Str1 with Str3
result = Str1.compareTo(Str3);
System.out.println(result); // -1
// Comparing Str3 with Str1
result = Str3.compareTo(Str1);
System.out.println(result); // 1
}
}
Output:
0
-6
6
iii) concat()

 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:

//Java program to demonstrate endsWith method


import java.io.*;
public class EndsWithExample
{
public static void main(String args[])
{
String Str="Welcome to Sindhi College";
System.out.println(Str.endsWith("College"));
System.out.println(Str.endsWith("Sindhi"));
}
}
Output:
true
false
vii) getChars()
 The getChars() method copies characters from the given string into the
destination character array.
 The general form is:
StringObject. getChars(int sourceStart, int sourceEnd, char target[], int targetStart)
Here, sourceStart specifies the index of the beginning of the substring. And sourceEnd
specifies an index that is one past the end of the desired substring. Thus, the substring
contains the characters from sourceStart through sourceEnd-1. The array that will
receive the characters is specified by target. The index within target at which the
substring will be copied is passed to targetStart.
Example:

//Java program to demonstrate getChars method


import java.io.*;
class Getchar_Demo
{
public static void main(String args[])
{
String str = "Welcome to Sindhi College";
char[] destArray = new char[14];
str.getChars(11, 25, destArray, 0);
System.out.println(destArray);
}
}

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:

// Java program to demonstrate indexOf() method


import java.io.*;
class indexOfDemo
{
public static void main(String args[])
{
String S = "Now is the time for all good mento come to the aid of their country.";
System.out.println(S);
System.out.println("indexOf(t) = " + S.indexOf('t'));
System.out.println("indexOf(the) = " + S.indexOf("the"));
System.out.println("indexOf(t, 10) = " + S.indexOf('t', 10));
System.out.println("indexOf(the, 10) = " + S.indexOf("the", 10));
}
}
Output:

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()

 The length() method returns the number of characters in a string.


 The general form is:
StringObject.length()
Example:
//Java program to demonstrate length method
import java.io.*;
public class LengthExample
{
public static void main(String args[])
{
String Str="Sindhi College";
System.out.println("String length is: "+Str.length());
}
}
Output:
14
xii) replace(), replaceAll & replaceFirst() methods

 The Java String class has three types of replace methods:

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:

//Java program to demonstrate replace method


import java.io.*;
public class replace_Ex
{
public static void main(String args[])
{
String Str = new String("The quick fox jumped");
System.out.println("Original String is ': " + Str);
System.out.println("String after replacing 'fox' with 'dog': " + Str.replace("fox",
"dog"));
}
}
Output:
Original String is ': The quick fox jumped
String after replacing 'fox' with 'dog': The quick dog jumped

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:

//Java program to demonstrate replaceAll method


import java.io.*;
public class replaceAllExample
{
public static void main(String args[])
{
String Str="Sindhi College";
String replaceString=Str.replaceAll("i","a");//replaces all occurrences of "i" to "a"
System.out.println(replaceString);
}
}
Ouput:
Sandha College
3. replaceFirst()
 The replaceFirst() method replaces only the first substring which matches a given
regular expression.

 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()

 The substring() method is used to extract a substring.


 There are two types of substring methods in java

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:

The extracted substring is : DataPoint


2. substring(StartIndex, EndIndex)
 The substring() method extracts the characters from a string, between the specified
starting and ending positions and returns a new sub string.
 The general form is:
StringObject.substring(int startIndex, int endIndex)
Here, the startIndex specifies the beginning index, and endIndex specifies the stopping
point. The string returned contains all the characters from the beginning index, up to,
but not including, the ending index.
Example:
//Java program using substring
import java.io.*;
public class Substr2_Ex2
{
public static void main(String args[])
{
String Str = new String("Welcome to Java");
System.out.print("The extracted substring is : ");
System.out.println(Str.substring(11, 15));
}
}
Output:
The extracted substring is : Java
xv) toCharArray()

 The toCharArray() method converts the string to a character array.


 The returned array length is equal to the length of the string.
 The general form is:
StringObject. toCharArray()
Example:
//Java Program to implement toCharArray()
import java.io.*;
class ToCharArrayEx
{
public static void main(String args[])
{
String S = "Sindhi";
char[] Str = S.toCharArray();
for (int i = 0; i <Str.length; i++)
{
System.out.println(Str[i]);
}
}
}
Output:
S
i
n
d
h
i

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:

//Java program to demonstrate toLowerCase method


import java.io.*;
public class ToLowerCase_Ex
{
public static void main(String args[])
{
String Str = "SINDHI COLLEGE";
//Convert to LowerCase
System.out.println(Str.toLowerCase());
}
}
Output:
sindhi college
xvii) toString()
 The toString() method returns the string representation of the object.
 The general form is:
StringObject.toString()

Example:

//Java Program to implement toString()


import java.io.*;
public class Test
{
public static void main(String args[])
{
int x = 5;
System.out.println(x.toString());
}
}
Output:
5
xviii) toUpperCase()
 The toUpperCase() method is used to convert all the characters of a string to uppercase
letters.
 The general form is:
StringObject.toUpperCase()

Example:

//Java program to demonstrate toUpperCase method


import java.io.*;
public class ToUpperCase_Ex
{
public static void main(String args[])
{
String Str = "Sindhi College";
//Convert to UpperCase
System.out.println(Str.toUpperCase());
}
}
Output:
SINDHI COLLEGE
xix) trim()
 The trim() method is used to remove leading and trailing whitespaces from a string.
 The general form is:
StringObject.trim()
Example:
//Java program to demonstrate trim() method
import java.io.*;
class Trim_Ex
{
public static void main(String args[])
{
String Str = " Learn Java Programming ";
System.out.println(Str.trim());
}
}

Output:

Learn Java Programming


xx) valueOf()
 The valueOf() method returns the string representation of the argument passed. This
method has the following variants:
 valueOf(boolean b) − Returns the string representation of the boolean argument.
 valueOf(char c) − Returns the string representation of the char argument.
 valueOf(char[] data) − Returns the string representation of the char array argument.
 valueOf(char[] data, int offset, int count) − Returns the string representation of a
specific subarray of the char array argument.
 valueOf(double d) − Returns the string representation of the double argument.
 valueOf(float f) − Returns the string representation of the float argument.
 valueOf(int i) − Returns the string representation of the int argument.
 valueOf(long l) − Returns the string representation of the long argument.
 valueOf(Object obj) − Returns the string representation of the Object argument.
 The general form is:
StringObject.valueOf()
Example:

//Java program to implement valueOf method


import java.io.*;
public class ValueOf_Ex
{
public static void main(String args[])
{
int i = 10;
float f = 10.10f;
double d = 102939939.939;
boolean b = true;
long l = 1232874;
char[] arr = {'a', 'b', 'c', 'd'};
System.out.println(String.valueOf(i));
System.out.println(String.valueOf(f));
System.out.println(String.valueOf(d));
System.out.println(String.valueOf(b));
System.out.println(String.valueOf(l));
System.out.println(String.valueOf(arr));
}
}
Output:
10
10.1
1.02939939939E8
true
1232874
abcd

8.3 StringBuffer Class


 StringBuffer class is used to create a mutable (modifiable) string.

 The StringBuffer class in Java is same as String class except it is mutable i.e. it can be
changed.

 StringBufferclass is available in java.lang package.

1. StringBuffer Constructors

 StringBuffer defines these Four constructors:


(i) StringBuffer()
(ii) StringBuffer(int size)
(iii) StringBuffer(String str)
(iv) StringBuffer(charSequence []ch)
i) StringBuffer()
 This constructor creates an empty stringbuffer and reserves space for 16 characters.
 This is the default constructor.
 The general form is:
StringBuffer bufname=new StringBuffer();
Example:
StringBuffer str=new StringBuffer();
ii) StringBuffer(int size)
 This constructor creates an empty stringbuffer and takes an integer argument to set
capacity of the buffer.
 The general form is:
StringBuffer bufname=new StringBuffer(size);
Example:
StringBuffer str=new StringBuffer(15);
iii) StringBuffer(String str)
 This constructor creates a stringbuffer object from the specified string.
 The general form is:
StringBuffer bufname=new StringBuffer(str);
Example:
StringBuffer str=new StringBuffer(“Welcome”);
iv) StringBuffer(charSequence []ch)
 This Constructor creates a stringbuffer object from the charsequence array.
2. StringBuffer Methods
 The following methods are some of the most commonly used methods of
StringBuffer class.
i) append(String str)
 The append()method is used to add text at the end of the existing text.
 The general form is:

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

iii) charAt(int index)

 The chatAt()method is used to return the character at the specifiedposition.


 The general form is:
StringBufferObject.charAt(int index)
Example:
//Java program to demonstrate charAt method
import java.io.*;
public class StringBuffer_CharAtEx
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Stringbuffer");
System.out.println("Given String: "+sb);
// Printing character at index value 2
System.out.println("Character at index 2: "+sb.charAt(2));
}
}
Output:
Given String: Stringbuffer
Character at index 2: r
iv) delete(int startIndex, int endIndex)

 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)

 The deleteCharAt()method is used to delete the character at the specified index.


 The general form is:
StringBufferObject.deleteCharAt(int index)

Example:

//Java program to demonstrate deleteCharAt method


import java.io.*;
public class StringBuffer_DeleteCharAtEx
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Raghav");
System.out.println("String buffer before deletion = " + sb);
// Deleting the character at index 5
sb.deleteCharAt(5);
System.out.println("String buffer after deletion = " + sb);
}
}

Output:

String buffer before deletion = Raghav


String buffer after deletion = Ragha

vi) ensureCapacity(int capacity)

 The ensureCapacity() is method is used to set the size of the buffer.


 The general form is:
StringBufferObject.ensureCapacity(int capacity)
Here, capacity specifies the size of the buffer.
Example:
//Java program to demonstrate ensureCapacity method
import java.io.*;
public class StringBuffer_ensureCapacityEx
{
public static void main(String args[])
{
StringBuffer str = new StringBuffer();
System.out.println(str.capacity());
str.ensureCapacity(30); //Greater than the existing capacity
System.out.println(str.capacity()); //Output: 34 (by following the rule –
// (oldcapacity*2) + 2.) i.e (16*2)+2 = 34.
}
}
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:

// Java program to demonstrate getChars() method


class GetChars_Ex
{
public static void main(String args[])
{
String str = "Welcome to Sindhi College";
char[] destArray = new char[14];
str.getChars(11, 25, destArray, 0);
System.out.println(destArray);
}
}

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:

//Java program to demonstrate indexOf(String str) method


import java.io.*;
public class IndexOf_Ex1
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Programming language");
System.out.println("Given String = " + sb);
// Returns the index of the specified substring
System.out.println("Index of substring = " + sb.indexOf("age"));
// Returns -1 as substring is not found
System.out.println("Index of substring = " + sb.indexOf("k"));
}
}
Output:
Given String = Programming language
Index of substring = 17
Index of substring = -1
2. indexOf(String str, int startIndex)
 This method returns the index of the first occurrence of the substring starting at the
specified index.
 If the substring str is not present, then -1 is returned.
 The general form is:
StringBufferObject.indexOf(String str, int startIndex)
Here, str is the string to be searched. startIndex specifies the index of the first character
Example:
//Java program to demonstrate indexOf(String str, int startIndex) method
import java.io.*;
public class IndexOf_Ex2
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Let us go to JavaTpoint to learn Java");
System.out.println("String: " + sb);
// Returns the index of first occurrence substring after the given index
System.out.println("Index of substring Java: " + sb.indexOf("Java",20));
System.out.println("Index of substring to: " + sb.indexOf("to",8));
}
}
Output:
nt to learn java
String: Let us go to JavaTpoint to learn Java
Index of substring Java: 33
Index of substring to: 10
x) lastIndexOf()
 The lastIndexOf() method returns the index of the last occurrence of the specified
substring.
 There are two overloaded lastIndexOf() methods available in StringBuffer class.
1. lastIndexOf(String str)
 This method returns the position of the last occurrence of the specified substring.
 The general form is:
StringBufferObject.lastIndexOf(String str)

Here, str is the string to be searched.


Example:
//Java program to implement lastindexOf
import java.io.*;
public class LastIndexOf_Ex1
{
public static void main(String args[])
{
StringBuffer Str = new StringBuffer("This is lastIndexOf example");
System.out.println("Given String: "+Str);
//Rreturns last index of example
System.out.println("Last index of example: " + Str..lastIndexOf("example"));
}
}
Output:
Given String: This is lastIndexOf example
Last index of example: 20
2. lastIndexOf(String str, int startIndex)
 This method returns the position of the last occurrence of the specified substring.
 The argument startIndex is the index to start the search from.
 The general form is:
StringBufferObject.lastIndexOf(String str, int startIndex)
Here, str is the string to be searched. startIndex specifies the index of the first character.
Example:
//Java program to implement lastIndexOf method
import java.io.*;
public class LastIndexOf_Ex2
{
public static void main(String args[])
{
StringBuffer Str = new StringBuffer("This is string it value is java");
System.out.println("Given String: " + Str);
//Returns last index of is, fromIndex 10
System.out.println("Last index of is: " + sb2.lastIndexOf("is",10));
}
}
Output:

Given String: This is string it value is java


Last index of is: 5
xi) length()

 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()

 The reverse() method is used to reverse the given string.


 The general form is:
StringBufferObject.reverse()
Example:
//Java program using StringBuffer reverse()
import java.io.*;
public class Reverse_Ex
{
public static void main(String args[])
{
StringBuffer Str = new StringBuffer("Hello");
Str.reverse();
System.out.println(Str);
}
}
Output:
olleH
xiv) setCharAt()
 The setCharAt() method is used to set the specified character at the given index.
 The general form is:
StringBufferObject.setCharAt(int index, char ch)
where index specifies the position of the character being set and ch specifies the new value
of the character.
Example
//Java program to demonstrate setCharAt method
import java.io.*;
public class SetCharAt_Ex
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("abc");
System.out.println("Given String: " + sb);
// Character at index 1
System.out.println("Character at index 1: " + sb.charAt(1));
// Set character at index 1
sb.setCharAt(1, 'x');
System.out.println("New String: " + sb);
// Character at index 1
System.out.println("Character at index 1: " + sb.charAt(1));
}
}

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:

//Java program to demonstate toString()


import java.io.*;
public class ToString_Ex
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello World!");
String str = sb.toString();
System.out.println("StringBuffer to String: " + str);
}
}
Output:
StringBuffer to String: Hello World!
8.8 Differences between String class and StringBuffer class

Sl. No. String StringBuffer


1) String objecct is immutable. StringBuffer object is mutable.
2) The length of the String object is The length of the StringBuffer can be
fixed. increased.
3) It is slower during concatenation. It is faster during concatenation.
4) Consumes more memory. Consumes less memory.
5) It overrides the equals() method of It doesn't override the equals() method of
Object class. Hence, the ‘equals’ Object class.
method can be used to compare two
strings.

You might also like