Unit I
Unit I
Unit I
Object Oriented
Thinking
&
Java Basics
UNIT-I 2
Programming Paradigms
• Paradigm can also be termed as method to solve some problem or
do some task.
• Programming paradigm is an approach to solve problem using
some programming language or it is a method to solve a problem
using tools and techniques that are available to us following some
approach.
3
Programming Paradigms
Imperative programming paradigm:
•Imperative (how to do) and declarative (what to do) programming
paradigms.
•It is one of the oldest programming paradigm. It features close relation to
machine architecture. Examples: C , Fortan
Imperative programming is divided into three broad categories.
5
Programming Paradigms
Object-Oriented Programming paradigm
•Object-oriented programming (OOP) is a programming paradigm
based upon objects (having both data and methods) that aims to
incorporate the advantages of modularity and reusability.
6
Programming Paradigms
In procedural programming, program is divided into small In object-oriented programming, program is divided into
parts called functions. small parts called objects.
Procedural programming follows top-down approach. Object oriented programming follows bottom-up approach.
Adding new data and function is not easy. Adding new data and function is easy.
Procedural programming does not have any proper way for Object oriented programming provides data hiding so it is
hiding data, so it is less secure. more secure.
In procedural programming, function is more important than In object-oriented programming, data is more important
data. than function.
Procedural programming is based on unreal world. Object oriented programming is based on real world.
7
Examples: C, FORTRAN, Pascal, Basic etc. Examples: C++, Java, Python, C# etc.
A Way of Viewing The World
9
A Way of Viewing The World
Messages and Methods
The term Florist is used to represent the category (or class) of all
florists.
3rd principle of object-oriented programming:
All objects are instances of a class.
1. Everything is an object.
2. Computation is performed by objects communicating with each other,
requesting that other objects perform actions. Objects communicate by
sending and receiving messages. A message is a request for action
bundled with whatever arguments may be necessary to complete the task.
3. Each object has its own memory, which consists of other objects.
4. Every object is an instance of a class. A class simply represents a
grouping of similar objects, such as integers or lists.
5. The class is the repository for behavior associated with an object.
That is, all objects that are instances of the same class can perform the
same actions.
6. Classes are organized into a singly rooted tree structure, called the
inheritance hierarchy. Memory and behavior associated with instances
of a class are automatically available to any class associated with a
descendant in this tree structure.
OOP Principles
Objects and Classes
Encapsulation:
Inheritance:
Polymorphism:
Message Communication
UNIT-I 15
OOP Principles
Encapsulation: Encapsulation is the mechanism that binds
together code and the data it manipulates.
In Java, the basis of encapsulation is the class.
A class defines the structure and behavior that
Inheritance: will be shared by a set of objects.
Polymorphism:
Polymorphism:
UNIT-I 17
OOP Principles
Encapsulation:
Inheritance:
UNIT-I 18
Java’s History
• Java was conceived by James Gosling at Sun Microsystems
in 1991.
• It took 18 months to develop the first working version.
• This language was initially called “Oak”, but was renamed
“Java” in 1995.
• Java is the name of the island in Indonesia.
• The Java coffee is from the Java island.
• The name was chosen during one of several brainstorming
sessions held by the Java software team.
• "Java" was chosen from among many, many suggestions.
• The name is not an acronym, but rather a reminder of that
hot, aromatic stuff that many programmers like to drink lots of
UNIT-I 19
JDK Versions
• JDK Alpha and Beta (1995)
• JDK 1.0 (23rd Jan 1996)
• JDK 1.1 (19th Feb 1997)
• J2SE 1.2 (8th Dec 1998)
• J2SE 1.3 (8th May 2000)
• J2SE 1.4 (6th Feb 2002)
• J2SE 5.0 (30th Sep 2004)
• Java SE 6 (11th Dec 2006)
• Java SE 7 (28th July 2011)
• Java SE 8 (18th Mar 2014)
• Java SE 9 (21st Sep 2017)
• Java SE 10 (20th Mar 2018)
• Java SE 11-19 (25th September 2018- 20th September 2022
• Java SE 20 (March 2023)
• Java SE 21 (September 2023)
UNIT-I 20
JDK Editions
• Java Standard Edition (J2SE)
– J2SE can be used to develop client-side standalone
applications or applets.
• Java Enterprise Edition (J2EE)
– J2EE can be used to develop server-side applications
such as Java servlets and Java ServerPages.
• Java Micro Edition (J2ME).
– J2ME can be used to develop applications for mobile
devices such as cell phones.
UNIT-I 21
UNIT-I 22
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 23
Characteristics of Java
• Java Is Simple Because Java inherits the
• Java Is Object-Oriented C/C++ syntax and many of
• Java Is Distributed the object-oriented features
of C++, learning Java will be
• Java Is Interpreted easier.
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 24
Characteristics of Java
• Java Is Simple Java is inherently object-oriented.
• Java Is Object-Oriented Although many object-oriented languages
began strictly as procedural languages,
• Java Is Distributed Java was designed from the start to be
• Java Is Interpreted object-oriented. Object-oriented
programming (OOP) is a popular
• Java Is Robust programming approach that is replacing
traditional procedural programming
• Java Is Secure techniques.
• Java Is Architecture-Neutral
One of the central issues in software
• Java Is Portable development is how to reuse code. Object-
• Java's Performance oriented programming provides great
flexibility, modularity, clarity, and
• Java Is Multithreaded reusability through encapsulation,
• Java Is Dynamic inheritance, and polymorphism.
UNIT-I 25
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented Distributed computing involves
several computers working
• Java Is Distributed together on a network. Java is
• Java Is Interpreted designed to make distributed
computing easy.
• Java Is Robust Java also supports Remote
Method Invocation(RMI)
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 26
Characteristics of Java
• Java Is Simple Java enables the creation of cross-
platform programs by compiling into
• Java Is Object-Oriented an intermediate representation called
• Java Is Distributed Java bytecode. This code can be
executed on any system that
• Java Is Interpreted implements the Java Virtual Machine
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 27
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
Java compilers can detect many
• Java Is Distributed problems that would first show up at
• Java Is Interpreted execution time in other languages.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 32
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
Multithread programming is smoothly
• Java Is Distributed integrated in Java, which allows you to write
• Java Is Interpreted programs that do many things
simultaneously. Whereas in other languages
• Java Is Robust you have to call procedures specific to the
• operating system to enable multithreading.
Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 33
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed Java programs carry with them substantial
amounts of run-time type information that is
• Java Is Interpreted used to verify and resolve accesses to
• Java Is Robust objects at run time. This makes it possible
to dynamically link code in a safe and
• Java Is Secure expedient manner.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 34
First Java Program
35
JVM(Java Virtual Machine)
36
37
Compiling Java Source Code
• Java was designed to run object programs on any
platform.
• With Java, you write the program once, and compile the
source program into a special type of object code, known as
bytecode.
• The bytecode can then run on any computer with a Java
Virtual Machine.
• Java Virtual Machine is a software that interprets Java
bytecode.
Java Bytecode
Java Virtual
Machine
Any
Computer
38
Java Translation and Execution
Java source code
Java compiler
Java bytecode
39
39
Java is Compiled and Interpreted
Hardware and
Programmer
Operating System
40
41
42
Java Installation
43
Java Installation
44
Java Installation
45
Setting Path for Java
46
Setting Path for Java
47
Setting Path for Java
48
Setting Path for Java
49
Setting Path for Java
50
Setting Path for Java
51
Check in Command Prompt
52
Check in Command Prompt
53
Check in Command Prompt
54
First Java Program
55
First Java Program
In Java, the name of the source file must be the same as the
name of the class with a mandatory file extension of ".java".
Method in Java
58
59
Program Execution
60
61
62
63
//Example for printf
64
//Example
65
Naming Conventions
• Variables and method names:
– Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first word,
and capitalize the first letter of each subsequent word in
the name.
For example:- radius, area, computeArea.
• Class names:
– Capitalize the first letter of each word in the name.
Example:- FirstProgram, Sample, DemoBoxWeight.
• Constants:
– Capitalize all letters in constants, and use underscores
to connect words.
Example:- PI, MAX_VALUE.
UNIT-I 66
Identifiers
• An identifier is a sequence of characters that consist of
uppercase and lowercase letters, digits, underscores ( _ ),
and dollar signs ($).
• An identifier must start with a letter, an underscore (_), or a
dollar sign ($). It cannot start with a digit.
• An identifier cannot be a reserved word.
• An identifier cannot be true, false, or null.
• An identifier can be of any length.
UNIT-I 67
Comments
• Single-line //
• Multi-line /* */
• Documentation comment /** */
This type of comment is used to produce an HTML file that
documents your program.
UNIT-I 68
Separators
( ) Method definition and invocation, defining precedence in
enum
UNIT-I 70
Data Types
Java defines eight primitive data types:
byte, short, int, long, char, float, double and boolean.
These are put into four groups:
→ Integers
→ Floating-point numbers
→ Characters
→ Boolean
UNIT-I 71
Data Types
72
Integers:
UNIT-I 73
Floating-Point Types:
UNIT-I 74
Characters:
► In Java, the data type used to store characters is char.
► Java uses Unicode to represent characters.
► Unicode defines a fully international character set that can
represent all the characters found in all human languages.
Such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana,
Hangul and many more.
► For this purpose char is 16 bits width.
► The range of char is 65,536.
► The standard set of characters known as ASCII in Unicode
ranges from 0 to 255.
UNIT-I 75
Booleans:
► Java has a primitive type called boolean for logical values.
► It can have only one of two possible values, true or false.
► It requires one bit.
► When a boolean value is output by println( ), “true” or “false
is displayed.
► If b is boolean variable, then there is no need to write an if
statement like this:
if(b==true) …
► The outcome of a relational operator is boolean value.
UNIT-I 76
Literals
Integer Literals:
► Integer literals can be represented using any of the three
bases decimal, octal and hexadecimal.
► Any whole number is a decimal(base 10) number.
► Octal(base 8) values are denoted in Java by a leading zero.
Ex: 05, 012,0734
► Hexadecimal(base 16) values are denoted in Java by a
leading zero-x(0x or 0X). The range of hexadecimal digits is 0
Ex: 1234L,0x52dfL
UNIT-I 78
Floating-Point Literals:
UNIT-I 79
Boolean Literals:
► There are only two logical values that boolean can have, true
and false.
► The true literal in Java does not equal 1 nor does the false
literal equal 0.
UNIT-I 80
Character Literals:
A character literal is represented inside a pair of single
quotes.
All the visible ASCII characters can be directly entered
inside the quotes, such as ‘a’, ‘z’, ‘@’.
For characters that are impossible to enter directly, there are
several escape sequences to enter the character.
UNIT-I 81
82
Character Escape Sequence
UNIT-I 84
The Scope and Lifetime of Variables
►A scope determines what objects are visible to other parts of
your program.
► It also determines the lifetime of those objects.
► In Java, the two major scopes are those defined by a class
and those defined by a method.
UNIT-I 85
UNIT-I 86
Type Conversion and Casting
Java supports both automatic type conversion and casting.
UNIT-I 87
//Example
class Hello
{
public static void main(String[] args)
{
int i = 100;
// automatic type conversion
long l = i;
// automatic type conversion
float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
88
Casting Incompatible Types:
To create a conversion between two incompatible types, use
a cast. A cast is an explicit type conversion. The general
form is:
(target-type) value
This type of conversion is sometimes called a narrowing
conversion.
A different type of conversion will occur when a floating-point
value is assigned to an integer type: truncation.
Ex:- int i=257; b=(byte)i;
byte b;
double d=456.132; i=(int)d;
UNIT-I 89
Automatic Type Promotion in Expressions:
Java automatically promotes each byte or short operand to int
when evaluating an expression.
Ex:- byte a=5, b=10;
a=a*b; //error
int c=a*b;
a=(byte)(a*b);
In addition to the above, Java automatic type promotion rules
are:
1. If one of the operands is double, the whole expression is
promoted to double.
2. Otherwise, if one of the operands is float, the whole
expression is promoted to float.
3. Otherwise, if one of the operands is long, the whole
expression is promoted to long.
UNIT-I 90
//Java program to illustrate
explicit //type conversion
class Hello
//Java program to illustrate {
//incompatible data type for public static void main(String[] a)
explicit //type conversion {
class Hello double d = 100.04;
{ //explicit type casting
public static void main(String[] args) long l = (long)d;
{ //explicit type casting
double d = 100.04; int i = (int)l;
long l = d; System.out.println("Double value
int i = l; "+d);
} System.out.println("Long value
} "+l);
System.out.println("Int value "+i);
}
}
91
Operators
Arithmetic Operators
Bitwise Operators
Relational Operators
UNIT-I 92
Arithmetic Operators:
The operands of the arithmetic operators must be of a numeric
type. These can also be used on char types.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
UNIT-I 93
Bitwise Operators:
Java defines several bitwise operators which can be applied to the types,
long, int, short, char and byte. These operators act upon the individual bits
of their operands. Operator Description
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclisive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclisive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
UNIT-I 94
Relational Operators:
The relational operators determine the relationship that one operand
has to the other. The outcome of these operations is a boolean value.
Operator Description
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
UNIT-I 95
Boolean Logical Operators:
These operators operate only on boolean operands and result
a boolean value.
Operator Description
& Logical AND
| Logical OR
^ Logical XOR
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
UNIT-I 96
Operator Precedence:
() [] .
High
++ -- ~ !
* / %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
Low ?:
= Op=
UNIT-I 97
UNIT-I 98
Control Statements
Java’s control statements are put into three categories:
• Selection statements: if and switch.
• Iteration statements: for, while and do-while.
• Jump statements: break, continue and return.
UNIT-I 99
Selection statements
if
if-else
Nested ifs
The if-else-if ladder
switch
Nested switch Statements.
UNIT-I 100
Selection statements:
if The if-else-if ladder
Syntax Syntax:
if (condition) {
// block of code to be executed if if(condition1){
the condition is true }
//code to be executed if condition1 is
if-else
true
Syntax }else if(condition2){
if (condition) {
// block of code to be executed if //code to be executed if condition2 is
the condition is true } true
else {
}
// block of code to be executed if
the condition is false } else if(condition3){
UNIT-I 104
Iteration statements:
While
Syntax
while (condition) {
// code block to be for
executed Syntax
for (statement 1; statement 2; statement 3)
} {
do-while // code block to be executed
}
Syntax
Example
do {
for (int i = 0; i < 5; i++) {
// code block to be System.out.println(i);
executed }
}
while (condition);
105
Iteration statements:
For-Each Loop
"for-each" loop, is used exclusively to loop through elements in an array:
Syntax
for (type variableName : arrayName) {
// code block to be executed
}
Example
public class Hello {
public static void main(String[] args) {
String[] branch = {"CSE", "ECE", "EEE", "IT"};
for (String i : branch) {
System.out.println(i);
}
}
}
106
Jump Statements
break:
In java, the break statement has three uses,
• In a switch statement.
• To exit a loop.
• Can be used as a form of goto.
The general form of the third type of break is:
break label;
Label is the name of a label that identifies a block of code.
When this form of break executes control is transferred out of
the named block of code.
Java label is a valid identifier followed by a colon.
UNIT-I 107
Jump Statements
Example
108
Jump Statements
continue:
Used in loops.
Also used with label.
The general form of continue with label is:
continue label;
return:
The return statement is used to explicitly return from a
method.
UNIT-I 109
continue
Example
110
UNIT-I 111
Arrays
An array is a group of like-typed variables that are referred to
by a common name.
One-Dimensional Arrays
Multidimensional Arrays
UNIT-I 112
One-Dimensional Arrays:
The general form of a one-dimensional array declaration is:
type array-var[ ];
type[ ] array-var;
To allocate memory to an array new operator is used.
array-var=new type[size];
UNIT-I 113
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays.
Ex:- int twoDim1[ ][ ]=new int[4][5];
UNIT-I 114
115
Example of Java Array
class Hello{
public static void main(String args[]){
a[0]=10; //initialization
a[1]=20;
a[2]=30;
//traversing array
116
UNIT-I 117
Class Fundamentals
• A class defines a new data type.
UNIT-I 118
The general form of a class definition is:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list){
// body of method
}
type methodname2(parameter-list){
// body of method
}
// . . .
type methodnameM(parameter-list){
// body of method
}
} UNIT-I 119
Class Fundamentals
• The data (or) variables defined within a class are called instance
UNIT-I 120
Declaring Objects:
The object is defined in two-steps:
1. Declare a variable of the class type.
classname class-var;
2. Acquire an actual, physical copy of the object and assign it to that
variable using a new operator.
class-var=new classname( );
width
b1
height Box object
depth
null
b2
UNIT-I 122
The Scope and Lifetime of Variables
•Local variables
•Instance variables
•Class/Static variables
Local Variables
•These variable are created when the block in entered, or the function
is called and destroyed after exiting from the block or when the call
returns from the function.
•The scope of these variables exists only within the block in which the
variable is declared. i.e., we can access these variable only within that
block.
public static void main(String args[]) public static void main(String args[])
{ {
Hello obj = new Hello(); System.out.println("a = " + a);
obj.aValue(); }
} }
}
Instance Variables
// displaying marks
System.out.println("Marks :");
System.out.println(obj1.engMarks);
}
}
Static Variables:
class_name.variable_name;
//Example
class Emp {
// static variable name
public static String name = "Java";
}
public class Hello {
public static void main(String args[])
{
// accessing static variable without object
System.out.println(Emp.name + " is based on OOPS
Concepts");
}
}
UNIT-I 132
Constructors:
• A constructor initializes an object immediately upon creation.
• It has the same name as the class in which it resides.
• Similar to a method but does not have a return type.
• Automatically called immediately after the object creation, before new
operator completes.
• The constructor’s job is to initialize the internal state of an object.
• Constructors can be with no parameters (default) as well as with
parameters.
Ex:-
Box( ) { Box(double w, double h, double d) Box b1=new Box( );
width=10; {
height=20; width=w;
depth=30; height=h; Box b2=new Box(40,50,60);
} depth=d;
} UNIT-I 133
UNIT-I 134
Methods:
The general form of a method:
type name(parameter-list){
// body of method
}
Overloading Methods:
• In a class, if two or more methods are defined with the same name and
different parameter declarations, then the methods are said to be overloaded
and the process is referred to as method overloading.
• Method overloading is one of the ways that Java supports polymorphism.
• Variable-Length Arguments
UNIT-I 135
Variable-Length Arguments(Varargs):
UNIT-I 136
Overloading Varargs Methods:
UNIT-I 137
Varargs and Ambiguity:
void display(int ... a) void display(int a, int ... v)
{ {
System.out.print("Parameters:"); System.out.print("Parameters:"+a);
for(int x:a) for(int x:v)
System.out.print(" "+x); System.out.print(" "+x);
System.out.println(); System.out.println();
} }
void display(char ... ch) void display(int ... w)
{ {
System.out.print("Parameters:"); System.out.print("Parameters2:");
for(char x:ch) for(int x:w)
System.out.print(" "+x); System.out.print(" "+x);
System.out.println(); System.out.println();
} }
s1.display( ); s1.display(10);
UNIT-I 138
This Keyword:
‘this’ keyword can be used inside any method to refer to the current object.
class Rect { class Rect { class Rect {
int length,breadth; int length,breadth; int length,breadth;
void init(int a, int b){ void init(int length, void init(int length,
length=a; int breadth){
int breadth){
breadth=b; this.length=length;
length=length;
} this.breadth=breadth;
breadth=breadth;
} }
}
}
}
To create such a member, precede its declaration with the keyword static.
Such members can be accessed with the class name by the dot operator.
class Sample {
static int a=10; int c=Sample.a+Sample.b;
static int b; Sample.methodOne(5,6);
static void methodOne(int p, int q) {
System.out.println(“p=“+p+”q=“+q);
}
} UNIT-I 140
static variables:
To initialize static variables, declare a static block which get executed exactly
once, when the class is first loaded.
UNIT-I 141
static methods:
UNIT-I 142
final keyword:
final can be applied for variables, methods and classes.
UNIT-I 143
UNIT-I 144
Garbage Collection:
In java, objects are dynamically allocated by using the new operator.
Such objects are automatically destroyed, and their memory is released when
no references to the objects exists.
The technique that accomplishes this is called garbage collection.
Sometimes an object will need to perform some action when it is destroyed.
Java provides a mechanism called finalization using which we can define
specific actions that will occur when an object is just about to be reclaimed
by the garbage collector.
To add a finalizer to a class, simply define the finalize() method, which the
Java runtime calls this method whenever it is about to recycle an object.
protected void finalize( ) {
// finalization code
}
UNIT-I 145
UNIT-I 146
Nested and Inner Classes:
A class can be defined within another classes. Such classes are known as
nested classes.
The scope of a nested class is bounded by the scope of its enclosing class.
A nested class has access to the members, including private members, of
the class in which it is nested.
The enclosing class does not have access to the members of the nested class.
class A {
// members
class B {
//class B members
}
// members
}
UNIT-I 147
Nested and Inner Classes:
UNIT-I 148
static Nested Classes:
A static nested class is one which has the static modifier applied.
It must access the members of its enclosing class through an object.
class A {
// members
static class B {
//class B members
}
// members
}
UNIT-I 149
Non-static Nested Classes:
A non-static nested class is also known as inner class.
It has access to all the variables and methods of its outer class.
class A {
// members
class B {
//class B members
}
// members
}
UNIT-I 150
UNIT-I 151
Strings in Java:
A string is a sequence of characters.
We can still perform all types of string operations, but each time an existing
string is altered a new String object is created that contains the modifications.
UNIT-I 152
Constructors of String class:
String( )
String(char chars[ ])
String(char chars[ ], int startIndex, int numChars)
String(String strObj)
String(byte asciiChars[ ])
String(byte asciiChars[ ],int startIndex,int numChars)
String(StringBuffer strBufObj)
String(int codePoints[ ],int startIndex, int numChars) Added in J2SE 5
String(StringBuilder strBuildObj) Added in J2SE 5
UNIT-I 153
String Literals:
String s = ”abcdefghij”;
String Length:
int length( )
UNIT-I 154
String Concatenation:
The + operator concatenates two strings, producing a String object as the result.
Example1:
String age = “9”;
String s = “He is “ + age + “ years old. “;
System.out.println( s );
The O/P here is “He is 9 years old.”
Example2:
int age = 9;
String s = “He is “ + age + “ years old. “;
System.out.println( s );
UNIT-I 155
String Concatenation:
Example3:
String s = “abcdefghij “ + 20 + 30;
System.out.println( s );
The O/P here is “abcdefghij 2030”
Example4:
String s = “abcdefghij “ + (20 + 30);
System.out.println( s );
The O/P here is “abcdefghij 50”
UNIT-I 156
String Conversion and toString( ):
Java converts data into its string representation during concatenation by
calling one of the overloaded versions of the string conversion method
valueOf( ) defined by String class.
valueOf( ) is overloaded for all simple types and for type Object.
static String valueOf(int num)
We can override toString( ) and provide our own string representations for
objects.
UNIT-I 158
Example:
class String1
class Rect{ {
int length,breadth; public static void main(String args[])
Rect(int x,int y) { {
length=x; Rect r1=new Rect(10,20);
breadth=y; String s1=“Rect:”+r1;
} System.out.println(s1);
} Cube b1=new Cube(10,20,30);
class Cube { String s2=“Cube:”+b1;
int length,width,height; System.out.println(s2);
Cube(int x,int y,int z) { }
length=x; }
width=y; O/P :
height=z; Rect:Rect@82ba41
} Cube:Hai I am instance of Cube class
public String toString( ) {
return "Hai I am instance of Cube class";
}
}
UNIT-I 159
Character Extraction:
UNIT-I 160
String Comparision:
UNIT-I 161
Searching Strings:
int indexOf(int ch) for first occurrence
int lastIndexOf(int ch) for last occurrence
int indexOf(String str)
int lastIndexOf(String str)
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
UNIT-I 162
Modifying a String:
String substring(int startIndex)
String substring(int startIndex, int endIndex)
String trim( )
UNIT-I 163
Changing the Case of Characters within a String:
String toLowerCase( )
String toUpperCase( )
Joining Strings:
UNIT-I 164
Some other String Methods:
int codePointAt(int i) Added by J2SE 5
int codePointBefore(int i) “
int codePointCount(int start,int end) “
boolean contains(CharSequence str) “
boolean contentEquals(CharSequence str) “
boolean contentEquals(StringBuffer str)
static String format(String fmtstr,Object … args) “
static String format(Locale loc, String fmtstr, Object … args) “
boolean matches(String regExp)
int offsetByCodePoints(int start, int num) “
String replaceFirst(String regExp,String newStr)
String replaceAll(String regExp,String newStr)
String[ ] split(String regExp)
String[ ] split(String regExp, int max)
CharSequence subSequence(int startIndex, int stopIndex)
UNIT-I 165
UNIT-I 166
StringBuffer Constructors:
StringBuffer( ) 16 characters
StringBuffer(int size)
StringBuffer(String str) str+16 characters
StringBuffer(CharSequence chars)
UNIT-I 167
Methods:
int length( ) string length
int capacity( ) total allocated capacity
void ensureCapacity(int capacity) preallocate
void setLength(int len)
char charAt(int where)
void setChatAt(int where, char ch)
void getChars(int sourceStart,int sourceEnd,char target[ ],int
targetStart)
UNIT-I 168
Methods:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
StringBuffer reverse( )