Object Oriented Programming Using Java
Subject Code: 033CSC011
Unit - I
Sajeetkumar Pujar
Assistant Professor of Computer Science
Govt. First Grade College, Haliyal
What is Language?
• A language is a structured system of communication.
• The structure of a language consists of grammar and
vocabulary.
What is Program?
• A program is a set of instructions that a computer uses
to perform a specific task.
What is Programming Language?
• A programming language is a computer language that is
used by programmers (developers) to communicate
with computers.
• It is a set of instructions written in any specific language
to perform a specific task.
• Examples: C, C++, Java, Python etc.
Types of Programming Language?
1. Procedure Oriented Programming Language:
– Focuses on functions rather than data & objects.
– Examples: C, COBOL, FORTRAN, PASCAL etc.
2. Object Oriented Programming Language:
– Focuses on data & objects rather than functions.
– C++, Java, Python etc.
Object Oriented Programming Language:
• Object-oriented programming is a way of solving a
complex problem by breaking them into a small
sub-problem.
Basic Concepts of OOP:
• Class
• Object
• Data abstraction
• Encapsulation
• Inheritance
• Polymorphism
Class:
• Class is a collection of objects of similar type.
• Example: Mango, Apple, Orange are the member of
the class fruit.
• Classes are user-defined data types and behave like
the built-in data types of a programming language.
Object:
• These are basic entities in an object oriented system.
• They may represent a person, a place, a bank account,
a table of data or any item that the program has to
handle.
Data abstraction:
• Abstraction refers to the act of representing essential
features without including the background details or
explanation.
Encapsulation:
• The wrapping up of data and functions into a single
unit(class) is known as Encapsulation.
• The data is not accessible to the outside world, and
only those functions which are wrapped in the class
can access it.
Inheritance:
• Inheritance is the process by which objects of one class acquire
the properties of objects of another class
• Or the process of deriving a new class from an already existing
class.
• The advantage of inheritance is the idea of reusability.
• It means that we can add additional features to an existing class
without modifying it.
• The new class will have the combined features of both the classes.
Polymorphism:
• The ability to take more than one form.
• An operation that exhibits/shows different behaviors in different
instances.
• Function Overloading: Using a same function name to perform
different types of tasks
• Operator Overloading: The process of making an operator to
exhibit different behaviors in different instances
Introduction to Java:
• Java is a high-level, general-purpose, object-oriented, and secure
programming language developed by James Gosling at Sun
Microsystems, Inc. in 1991.
• It is formally known as OAK.
• In 1995, Sun Microsystem changed the name to Java.
• In 2009, Sun Microsystem takeover by Oracle Corporation.
Features of Java:
1. Simple:
• Java is a simple language because its syntax is
simple, clean, and easy to understand.
• For example, pointer and operator overloading are
not used in Java.
Features of Java:
2. Object-Oriented:
• In Java, everything is in the form of the object.
• A java program must have at least one class and
object.
Features of Java:
3. Robust:
• Java makes an effort to check error at run time and
compile time.
• It uses a strong memory management system
called garbage collector.
• Exception handling and garbage collection features
make it strong.
Features of Java:
4. Secure:
• Java is a secure programming language because it
has no explicit pointer and programs runs in the
virtual machine.
• Java contains a security manager that defines the
access of Java classes.
Features of Java:
5. Platform-Independent:
• Java provides a guarantee that code writes once
and run anywhere.
• The byte code is platform-independent and can be
run on any machine.
Features of Java:
6. Portable:
• Java Byte code can be carried to any platform.
• No implementation-dependent features.
• Everything related to storage is predefined, for
example, the size of primitive data types.
Features of Java:
7. High Performance:
• Java is an interpreted language.
• Java enables high performance with the use of the
Just-In-Time compiler.
Features of Java:
8. Distributed:
• Java also has networking facilities.
• It is designed for the distributed environment of
the internet because it supports TCP/IP protocol. It
can run over the internet.
Features of Java:
9. Multi-threaded:
• Java also supports multi-threading. It means to
handle more than one job a time.
Features of Java:
10. Compiled and Interpreted:
• A computer language is either compiled or interpreted.
• Java combines both these features.
• Java compiler translates the source code into bytecode
instructions.
• Java interpreter translates the bytecode instructions
into machine code.
Features of Java:
11. Dynamic and Extensible:
• Java is a dynamic language.
• Java is capable of dynamically linking in new class
libraries, methods, and objects.
• Java programs support functions written in other
languages such as C and C++ (These functions are
known as native methods).
• Native methods are linked dynamically at runtime.
Java Virtual Machine (JVM):
• Java Virtual Machine is a program whose purpose is to
execute other programs.
• The JVM has two primary functions:
– To allow Java programs to run on any device or
operating system (known as the "Write once, run
anywhere" principle),
– To manage and optimize program memory.
Java Virtual Machine (JVM):
Java Program Byte Code
Java Compiler
(Source Code) (Virtual Machine)
Process of compilation
Byte Code
Java Interpreter Machine Code
(Virtual Machine)
Process of converting bytecode into machine code
Java Virtual Machine (JVM):
Just-In-Time Compiler(JIT):
• JIT in Java is an integral part of the JVM.
• It accelerates execution performance many times over
the previous level.
• It optimizes the performance of the Java application at
compile or run time.
Just-In-Time Compiler(JIT):
JAVA Tokens:
• Keywords
• Identifiers
• Literals
• Operators
• Separators
Keywords:
• Keywords are an essential part of a language
definition.
• They have a specific meaning in Java.
• We cannot use them as names for variables, classes,
methods.
• They should be written in lower-case letters.
Keywords:
Identifiers:
• Identifiers are programmer-designed tokens.
• They are used for naming classes, methods, variables,
objects, labels, packages and interfaces in a program.
Identifiers:
● Following are the Java Identifier rules.
● They can have alphabets, digits, and the underscore and
dollar sign characters.
● They must not begin with a digit.
● Uppercase and lowercase letters are distinct.
● They can be of any length.
Literals:
● Literals in Java are a sequence of characters (digits, letters,
and characters) that represent values to be stored in variables.
● Java specifies 5 major types of literals.
○ Integer literals
○ Floating point literals.
○ Character literals.
○ String literals
○ Boolean literals
Operators:
● An operator is a symbol that takes one or more arguments and
operates on them to produce a result.
Constants:
• Constants in Java refer to fixed values that do not change
during the execution of a program.
Constants:
Java Constants
Numeric Constants Character Constants
Integer Real Character String
Constants Constants Constants Constants
Integer Constants:
• An integer constant refers to a sequence of digits.
• There are three types of integer constants.
– Decimal integer
– Octal integer
– Hexadecimal integer
Decimal Integer Constants:
• Decimal integers consist of a set of digits between 0 and 9.
• Valid examples:
123 -321 0 654321
• Embedded spaces, commas, and non-digit characters are not
permitted between digits.
• Following numbers are invalid integers.
15 750 20,000 $1000
Octal Integer Constants:
• Octal integers consist of a set of digits between 0 and 7 with a
leading 0.
• Examples:
037 0 0345 0551
Hexadecimal Integer Constants:
• A sequence of digits preceded by 0x or oX is considered as
hexadecimal integer constant.
• 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 hexadecimal integers.
0X2 0X9F 0xbcd 0x
Real Constants:
• The real constants(floating point) are represented by numbers
containing fractional parts.
• Examples:
0.0083 -0.75 345.44
Real Constants:
• A real number may also be expressed in exponential (or
scientific) notation.
• The general form is:
mantissa e exponent
• Examples:
215.65 2.1565e2
0.000002 2.0e-6
35400000000 3.54e10
Real Constants:
• A floating point constant may comprise of four parts:
– A whole number
– A decimal point
– A fractional part
– An exponent
Single Character Constants:
• A single character constant (character constant) contains a
single character enclosed within a pair of single quote marks.
• Examples:
‘5’ ‘X’ ‘;’ ‘ ’
String Constants:
• A string constant is a sequence of characters enclosed
between double quotes.
• The characters may be alphabets, digits, special characters and
blank spaces.
• Examples:
“Java” “1990” ‘5+4’ “X” “Hello World”
Variables:
• A variable is an identifier that denotes a storage location used
to store a value.
• A variable may take different values at different times during
the program execution.
• A variable names may consist of alphabets, digits, underscore,
and dollar characters.
Rules for Variables:
• Variable must not begin with a digit.
• Uppercase and lowercase are distinct.
• Keyword cannot be used as a variable.
• While spaces are not allowed in variable.
• Variable names can be of any length.
Data Types:
• Data types specify the size and type of values that can be
stored in a variable.
Data Types:
• Primitive (Intrinsic)
– Numeric
• Integer
• Floating-point
– Non-numeric
• Character
• Boolean
• Non-Primitive (Derived)
– Arrays
– Classes
– Interfaces
Integer Types:
• Integer types can hold whole numbers.
• The size of the values that can be stored depends of the
integer data types.
• Java supports 4 types of integers
– byte
– short
– int
– long
Integer Types:
Size and Range of Integer Types
Type Size Minimum Value Maximum Value
byte 1 byte -128 127
short 2 bytes -32,768 32,767
int 4 bytes -2,147,483,648 2,147,483,647
long 8 bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807
Floating Point Types:
• Floating point types can hold numbers containing fractional
parts.
• Java supports 2 types of floating point types:
– float
– double
• Floating point data types support a special value known as
Not-a-Number(NaN).
• NaN is used to represent the result of operations such as dividing
zero by zero, finding a square root of a negative number, etc.
Floating Point Types:
Size and Range of Floating Point Types
Type Size Minimum Value Maximum Value
float 4 byte 3.4e-38 3.4e+38
double 8 bytes 1.7e-308 1.7e+308
Character Types:
• Java provides a character data type called char.
• char variable can hold only a single character.
• Size of char variable is 2 bytes.
Boolean Types:
• Boolean type is used to test a particular condition during
the program execution.
• It takes only two values: true or false
• Boolean type is denoted by the keyword boolean.
• It uses only one bit of storage.
Operators:
• An operator is a symbol that tells the computer to perform
certain mathematical or logical manipulations.
• Operators are used in programs to manipulate data and
variables.
Operators:
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Assignment Operators
• Increment and Decrement Operators
• Conditional Operators
• Bitwise Operators
Arithmetic Operators:
Operator Meaning
+ Addition or Unary Plus
- Subtraction or Unary Minus
* Multiplication
% Modulo division
Relational Operators:
Operator Meaning
< Is less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Is not equal to
Logical Operators:
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Assignment Operators:
• Assignment operator (=) is used to assign the value of an
expression to a variable.
• Java has a set of shorthand assignment operators which are
used in the form:
Variable Operator = Expression;
• For Example:
x = x + 1 is equivalent to x += 1
Assignment Operators:
Statement with Simple Statement with
Assignment Operator Shorthand Operator
a=a+1 a += 1
a=a-1 a -= 1
a = a * (n + 1) a *= n + 1
a = a / (n + 1) a /= n + 1
a=a%b a %= b
Increment & Decrement Operators:
• Java has two useful operators such as increment and
decrement operators.
++ and --
• The operator ++ adds 1 to the operand while - - subtracts 1.
Increment & Decrement Operators:
• These are unary operators and are used in the following
form:
++x; or x++;
--x; or x--;
++x; is equivalent to x = x + 1; (or x + = 1)
--x; is equivalent to x = x - 1; (or x - = 1)
class P2
{
public static void main(String[] args)
{
int m = 10, n = 20;
[Link](" m = "+ m);
[Link](" n = "+ n);
[Link](" ++m = "+ ++m);
[Link](" n++ = "+ n++);
[Link](" m = "+ m);
[Link](" n = "+ n);
}
}
Conditional Operators:
• The character pair ?: is a ternary operator.
• The general form is:
Exp1 ? Exp2 : Exp3
• Exp1 is evaluated first.
– If it is true(nonzero), then Exp2 is evaluated.
– If it is false, then Exp3 is evaluated.
Conditional Operator Example:
int a = 10,b = 15; int a = 10,b = 15;
x =(a > b)? a : b; if (a > b)
x = a;
else
x = b;
Bitwise Operators:
• Bitwise operators are used to manipulate the values at bit
level.
• These are used for testing the bits, or shifting them to the
right or left.
• These are not applied to float and double.
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise Exclusive OR
~ One’s Complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
// Program to demonstrate Bitwise AND Operator.
class BitwiseAnd
{
public static void main(String[] args)
{
int a = 4, b = 7;
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("a & b = " + (a & b));
}
}
// Program to demonstrate Bitwise OR Operator.
class BitwiseOR
{
public static void main(String[] args)
{
int a = 4, b = 7;
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("a | b = " + (a | b));
}
}
// Program to demonstrate Bitwise Exclusive OR.
class BitwiseXOR
{
public static void main(String[] args)
{
int a = 4, b = 7;
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("a ^ b = " + (a ^ b));
}
}
// Program to demonstrate Bitwise Complement.
class BitwiseComplement
{
public static void main(String[] args)
{
int a = 4, b = 7;
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("~a = " + ~a);
[Link]("~b = " + ~b);
}
}
Note: The bitwise complement of any integer
N is equal to -(N + 1).
10: 00000000 00000000 00000000 00001010
(~10)1’s: 11111111 11111111 11111111 11110101
2’s: 00000000 00000000 00000000 00001010
+1
-11: 00000000 00000000 00000000 0001011
// Program to demonstrate Bitwise left shift.
class BitwiseLeftShift
{
public static void main(String args[])
{
int a = 10;
int b = a << 2;
[Link]("a = "+a);
[Link]("b = "+b);
}
}
// Program to demonstrate Bitwise right shift.
class BitwiseRightShift
{
public static void main(String args[])
{
int a = 10;
int b = a >> 2;
[Link]("a = "+a);
[Link]("b = "+b);
}
}
class BitwiseRightShiftWithZeroFill
{
public static void main(String args[])
{
int x, y;
x=10;
y=-10;
[Link]("x<<2 = "+(x<<2));
[Link]("x>>2 = "+(x>>2));
[Link]("x>>>2 = "+(x>>>2));
[Link]("y>>>2 = "+(y>>>2));
}
}
Output:
x<<2 = 40
x>>2 = 2
x>>>2 = 2
y>>>2 = 1073741821
10: 00000000 00000000 00000000 00001010
1’s: 11111111 11111111 11111111 11110101
+1
(-10)2’s: 11111111 11111111 11111111 11110110
-10>>>2: 00111111 11111111 11111111 00111101
Control Structures (Selection & Looping):
• These are also known as Decision Making Statements.
• When a program breaks the sequential flow and jumps to another
part of the code, it is known as branching.
• When the branching is based on a particular condition, it is known
as conditional branching.
• If branching takes place without any condition/decision, it is
known as unconditional branching.
if statement:
if(condition)
{
Statements
}
if-else statement:
if(condition)
{
True-block Statements
}
else
{
False-block Statements
}
Nested if-else statement:
if(condition 1)
{
if(condition 2)
{
True-block Statements
}
else
{
False-block Statements
}
}
else
{
False-block Statements
}
else if ladder:
if(condition 1)
{
statements
}
else if (condition 2)
{
statements
}
……
……
else
{
}
The switch statement:
switch(condition 1)
{
case 1: statements
break;
case 2: statements
break;
case 3: statements
break;
…………
…………
default: statements
}
The while statement:
variable initialization;
while(condition 1)
{
Body of the loop
}
The do while statement:
variable initialization;
do
{
Body of the loop
}
while(condition 1);
The for statement:
for(initialization;condition;increment)
{
Body of the loop
}
The break statement:
while(condition)
{
………………
………………
if(condition)
break;
………………
}
………………
The continue statement:
while(condition)
{
………………
………………
if(condition)
continue;
………………
}
………………
Class:
• Class is a user-defined data-type which is used to
define its properties.
• Class contains variables and methods.
• The variables are also known as instance
variables.
• The methods are also known as instance methods.
Class Definition Syntax:
class ClassName [extends SuperClassName]
{
variable declaration;
methods declaration;
}
Instance Variables:
class Sample
{
int length;
int width;
}
Instance Methods:
class Sample
{
return_type MethodName (Parameter-list)
{
Method Body
}
}
Instance Methods:
Method declarations have four basic parts:
• The name of the method (MethodName)
• The type of the value the method returns
• A list of parameters (parameter-list)
• The body of the method
Instance Methods:
class Rectangle
{
int length, width;
void getdata(int x, int y)
{
length = x;
width = y;
}
}
Creating objects:
• An object is a block of memory that contains space to
store all the instance variables.
• Objects are created using the new operator.
• The new operator creates an object of the specified
class and returns a reference to that object.
Creating objects:
Rectangle r1; // Declare
r1 = new Rectangle(); // instantiate
Rectangle r1; r1 null
Object
r1 = new Rectangle(); r1
Reference
Rectangle
Object
Accessing Class Members:
• All the variables must be assigned values before they
are used.
• We cannot access the instance variables and the
methods directly.
• Syntax:
[Link];
or
[Link](parameter-list);
class Rectangle
{
int len,wid;
void getData(int x, int y)
{
len = x;
wid = y;
}
int area()
{
int area = len * wid;
return area;
}
}
class RectArea
{
public static void main(String args[])
{
int a1, a2;
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle();
[Link] = 15;
[Link] = 10;
a1 = [Link] * [Link];
[Link](20,30);
a2 = [Link]();
[Link]("Area 1 = "+a1);
[Link]("Area 2 = "+a2);
}
}
Java methods:
• A method is a block of code that performs a specific task.
• Types of methods:
– Predefined/ Built-in Methods
– User defined methods
Predefined/Built-in methods:
• The predefined methods are the methods that are already
defined in the Java class libraries.
• It is also known as the standard library method or built-in method.
• We can directly use these methods just by calling them in the
program at any point.
• Examples:
– println(), length(), equals(), compareTo(), sqrt(), etc.
User defined methods:
• The method written by the user or programmer is known as a
user-defined method.
• These methods are modified according to the requirement.
• Syntax:
return_type MethodName(Parameter-list)
{
Method Body
}
class Sample
{
int add1(int a, int b)
{
return a+b;
}
float add2(float x, float y)
{
return x+y;
}
public static void main(String args[])
{
Sample s1 = new Sample();
[Link](s1.add1(10,20));
[Link](s1.add2(10.3f,50.5f));
}
}
Method Overloading:
• The methods that have the same name, but different
parameter lists and different definitions is called
method overloading.
• When a method is called/invoked, Java matches up the
method name first and then the number and type of
parameters to decide which one of the definitions .
class Sample
{
int add(int a, int b)
{
return a+b;
}
float add(float x, float y)
{
return x+y;
}
public static void main(String args[])
{
Sample s1 = new Sample();
[Link]([Link](10,20));
[Link]([Link](10.3f,50.5f));
}
}
Constructor:
• Constructor is a method which is used to initialize an
object when it is first created.
class Sample
{
int len, wid;
Sample(int x, int y)
{
len = x;
wid = y;
}
}
class ConstructorDemo
{
public static void main(String args[])
{
Sample s = new Sample(10,20);
[Link]([Link]);
[Link]([Link]);
}
}
Constructor characteristics:
• It has the same name as class name.
• It is called/invoked automatically whenever an object is
created.
• It has no return type.
• It does not return a value.
Constructor types:
• Default Constructor (Non-parameterized constructor)
• Parameterized Constructor
Default Constructor (Non-parameterized constructor):
• A constructor which does not take any arguments or
parameters is called Default Constructor.
class Sample
{
int len, wid;
Sample()
{
len = 10;
wid = 15;
}
}
Parameterized Constructor:
• A constructor which takes arguments or parameters is
called Parameterized Constructor.
class Sample
{
int len, wid;
Sample(int x, int y)
{
len = x;
wid = y;
}
}
Overloaded Constructor:
• Having more than one constructor in a class with the
same name but different parameter list is called
Constructor Overloading.
class Sample
{
int len, wid;
Sample()
{
len = wid = 10;
}
Sample(int x, int y)
{
len = x;
wid = y;
}
}
class ConstructorDemo
{
public static void main(String args[])
{
Sample s1 = new Sample(10,20);
Sample s2 = new Sample();
}
}
Math class:
• Math class is a predefined/built-in method.
• It helps to perform the numeric operations like square, square
root, cube, cube root, exponential and trigonometric operations
and etc.
class MathDemo
{
public static void main(String args[])
{
[Link]([Link](-5));
[Link]([Link](25));
[Link]([Link](5,3));
[Link]([Link](125));
[Link]([Link](20,30));
[Link]([Link](20,30));
}
}
Arrays:
• An array is a group of contiguous/homogeneous or related data
items that share a common name.
• An array can be of any variable type.
• Creation of an array involves three steps.
– Declaring the array
– Creating memory locations
– Storing values into the memory locations. (Initialization)
Declaration of Arrays:
• Arrays in Java can be declared in two forms:
data_type arrayName[];
or
data_type [] arrayName;
• Example
int number[];
float [] average;
Creation of Arrays:
• Java allows us to create arrays using new operator.
arrayName = new Data_type[size];
• Example:
number = new int [5];
average = new float[10];
Creation of Arrays:
• Both declaration and creation can be combined into one.
Data_type arrayName[] = new Data_type[size];
• Example:
int number[] = new int [5];
float [] average = new float[10];
Initialization of Arrays:
• The process of storing the values into an array is called
initialization.
arrayName[index] = value;
• Example:
number[0] = 10;
number[1] = 5;
number[2] = 20;
……………
……………
Initialization of Arrays:
• The array can be initialized automatically like ordinary variables
when they are created.
Data_type arrayName[] = {list of values};
• The list of values separated by commas.
• Size is not given.
• Example:
int number [] = {10,5,34,40 ,20};
String:
• String is a sequence of characters.
• The sequence of characters can be represented using a character array.
• Example:
char charArray[] = new char [4];
charArray[0] = ‘J’;
charArray[1] = ‘a’;
charArray[2] = ‘v’;
charArray[3] = ‘a’;
The above declaration and initialization is same as given below:
char charArray[] = {‘J’,’a’,’v’,’a’};
String:
• String is a predefined class available in Java.
• String object is immutable.
• Strings may be declared and created as follows:
String StringObject;
StringObject = new String (“string”);
• Example:
String s;
s = new String(“Hello”);
String:
• Example:
String s;
s = new String(“Hello”);
or
String s = new String(“Hello”);
or
String s = “Hello”;
String methods:
• toLowerCase()
• toUpperCase()
• length()
• compareTo()
• equals()
• equalsIgnoreCase()
• charAt()
• indexOf()
• replace()
• trim()
toLowerCase():
String s1 = "HELLO World";
String s2 = [Link]();
It converts the string s1 to lowercase and stores the result in s2.
toUpperCase():
String s1 = "Hello World";
String s2 = [Link]();
It converts the string s1 to uppercase and stores the result in s2.
length():
String s1 = "Hello World";
int n = [Link]();
It finds the length of the string and stores the result in ‘n’.
compareTo():
String s1 = "Dharwad";
String s2 = “Hubli”
int n = [Link](s2);
It compares the contents of the string s1 with s2 and stores one
of the following results in ‘n’.
• -ve value if s1 is smaller than s2.
• Zero if s1 and s2 are equal.
• +ve value if s1 is bigger than s2.
equals():
String s1 = "Dharwad";
String s2 = “Hubli”
boolean b = [Link](s2);
It returns true if s1 and s2 are identical (including spelling, case,
blanks), false otherwise.
equalsIgnoreCase():
String s1 = "Dharwad";
String s2 = “Hubli”;
boolean b = [Link](s2);
It returns true if s1 and s2 are identical ignoring the case (it will
check only the spelling and blanks), false otherwise.
charAt():
String s1 = "Dharwad";
char c = [Link](n);
where n is an integer value.
It returns the character at position ‘n’ to variable ‘c’.
indexOf():
String s1 = "Dharwad";
int n = [Link](c);
where c is a character.
It returns the position of the first occurrence of the character ‘c’
and stores the result in ‘n’.
replace():
String s1 = "Java";
String s2 = [Link](c1, c2);
where c1 and c2 are characters.
It replaces all the occurrences of character c1 to c2.
trim():
String s1 = " Java ";
String s2 = [Link]();
It removes leading and trailing blank spaces from string s1 and
stores the result in s2.
StringBuffer:
• StringBuffer is a predefined class available in Java.
• StringBuffer object is mutable.
• Strings may be declared and created as follows:
StringBuffer StringObject;
StringObject = new StringBuffer (“string”);
• Example:
StringBuffer s;
s = new StringBuffer(“Hello”);
StringBuffer:
• Example:
StringBuffer s;
s = new StringBuffer(“Hello”);
or
StringBuffer s = new StringBuffer(“Hello”);
StringBuffer methods:
• setCharAt()
• append()
• insert()
• replace()
• delete()
• reverse()
setCharAt()
[Link](n,x);
Where n is the position and x is the character.
StringBuffer s1 = new StringBuffer(“Java”);
[Link](0,'L');
It modifies the nth character to x.
append()
StringBuffer s1 = new StringBuffer(“Java”);
StringBuffer s2 = new StringBuffer(“Program”);
[Link](s2);
It concatenates the string s1 with s2.
insert()
[Link](n,s2);
Where n is a position.
StringBuffer s1 = new StringBuffer(“Java”);
StringBuffer s2 = new StringBuffer(“Program”);
[Link](0,s1);
It inserts the string s2 at the position ‘n’ of the string s2.
replace()
[Link](start,end-1,s2);
StringBuffer s1 = new StringBuffer(“Java”);
[Link](1,3,”Hello”);
It replaces the given string from the specified start and end-1
index.
delete()
[Link](start,end-1);
StringBuffer s1 = new StringBuffer(“Hello”);
[Link](1,3);
It deletes the string from the specified start and end-1 index.
reverse()
[Link]();
StringBuffer s1 = new StringBuffer(“Hello”);
[Link]();
It reverses the given string.
File:
• The problems with storing values in variables and arrays are as
follows:
1. The data is lost when a variable goes out of scope or when
the program is terminated (Storage is temporary).
2. It is difficult to handle large volumes of data using variables
and arrays.
• To overcome these difficulties, the files are used.
• The files are stored on secondary storage devices such as floppy
disk or hard disk.
File:
• A file is a collection of related records placed in a particular area
on the disk.
• The record is composed of several fields and a field is a group of
characters.
• The data stored in files is often called persistent data.
• The File class has been defined in [Link] package.
Basic File Operation Methods:
Operation Method Package
To Create a file createNewFile() [Link]
To Read a file read() [Link]
To Write a file write() [Link]
To Delete a file delete() [Link]
To create a File object:
• To create an object of File, the package [Link] is to be
imported.
• The File object is created as given below:
import [Link];
File f = new File(String pathName);
boolean value = [Link]();
import [Link];
class FileOperations
{
public static void main(String[] args)
{
File f = new File("[Link]");
try
{
boolean value = [Link]();
if (value)
{
[Link]("The new file is created.");
}
else
{
[Link]("The file already exists.");
}
}
catch(Exception e)
{
}
}
}
To write a file:
• To write the data into the file, we can use the FileWriter class.
import [Link];
FileWriter output = new FileWriter(String pathName);
import [Link];
class FileWriterDemo
{
public static void main(String[] args)
{
String data = "This is the data in the output file";
try
{
FileWriter output = new FileWriter("[Link]");
[Link](data);
[Link]("Data is written to the file.");
[Link]();
}
catch (Exception e)
{
[Link]();
}
}
}
To read a file:
• To read data from the file, we can use the FileReader class.
import [Link];
FileReader input = new FileReader(String pathName);
import [Link];
class FileReaderDemo
{
public static void main(String[] args)
{
char[] array = new char[100];
try
{
FileReader input = new FileReader("[Link]");
[Link](array);
[Link]("Data in the file:");
[Link](array);
[Link]();
}
catch(Exception e)
{
}
}
}
To delete a file:
• We can use the delete() method of the File class to delete the
specified file or directory. It returns
➢ true if the file is deleted.
➢ false if the file does not exist.
import [Link];
class FileDeleteDemo
{
public static void main(String[] args)
{
File file = new File("[Link]");
boolean value = [Link]();
if(value)
{
[Link]("The File is deleted.");
}
else
{
[Link]("The File is not deleted.");
}
}
}
References:
1. Programming with Java, E. Balagurusamy, 4th Edition, McGraw Hill Publications.
2. [Link]
3. [Link]
-[Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]