UNIT-I BASICS Java Programming
UNIT-I BASICS Java Programming
M. Hari Prasad
Asst. Prof.
Dept. of AI
Anurag University
UNIT-I 1
2 UNIT-I
Contents
Introduction this, static, final keyword
History of Java Garbage collection
Java buzzwords Nested and Inner Classes
Identifiers, Comments String handling.
Separators, Keywords
Data Types, Variables
Scope and life time of variables
Type conversion and casting
Arrays
Operators
Control statements
Classes and objects
Constructors
Methods
3 UNIT-I
4 UNIT-I
Programs
Computer programs, known as software, are instructions to the
computer.
5 UNIT-I
Programming Languages
Machine Language :
Assembly Language :
High-Level Language :
6 UNIT-I
Programming Languages
Machine Language :
Machine language is a set of primitive instructions built into every
computer.
The instructions are in the form of binary code, so you have to enter
binary codes for various instructions.
The programs are highly difficult to read and modify.
For example:
1101101010011010
7 UNIT-I
Programming Languages
Assembly Language :
Assembly languages were developed to make programming easy.
Since the computer cannot understand assembly language, a
program called assembler is used to convert assembly language
programs into machine code. For example, to add two numbers, we
write an instruction in assembly code like this:
ADDF3 R1, R2, R3
8 UNIT-I
Programming Languages
High-Level Language :
The high-level languages are English-like and easy to learn and
program. For example, the following is a high-level language
statement that computes the area of a circle with radius 5:
area = 5 * 5 * 3.1415;
9 UNIT-I
Programming Languages
High-Level Language :
COBOL (COmmon Business Oriented Language)
FORTRAN (FORmula TRANslation)
BASIC (Beginner All-purpose Symbolic Instructional Code)
Pascal (named for Blaise Pascal)
Ada (named for Ada Lovelace)
C (whose developer designed B first)
Visual Basic (Basic-like visual language developed by Microsoft)
Delphi (Pascal-like visual language developed by Borland)
C++ (an object-oriented language, based on C)
Java (We use it in this course)
10 UNIT-I
Compiling Source Code
A program written in a high-level language is called a source program.
Since a computer cannot understand a source program. Program
called a compiler is used to translate the source program into a
machine language program called an object program.
The object program is often then linked with other supporting library
code before the object can be executed on the machine.
11 UNIT-I
12 UNIT-I
Java’s History
• B led to C,
– C evolved into C++, and
•C++ set the stage for Java
• Much of the character of Java is inherited from
these two languages.
• From C, Java derives its syntax.
• Many of Java’s object-oriented features were
influenced by C++.
UNIT-I 13
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
14
Java’s History
• Java was conceived at Sun Microsystems, Inc. in 1991 by
James Gosling,
Patrick Naughton,
Chris Warth,
Ed Frank, and
Mike Sheridan.
UNIT-I 15
Motivation
1. Platform-independent (architecture neutral)
language that could be used to create
software to be embedded in various
consumer electronic devices, such as
microwave ovens and remote controls. Code
that would run on a variety of CPUs under
differing environments.
2. World Wide Web
UNIT-I 16
Motivation
Java,
• is a programmer’s language
• is cohesive and logically consistent.
• gives the programmer, full control.
UNIT-I 17
JDK Versions
Version
Java SE Version Release Date
Number
JDK 1.0 (Oak) 1 Jan-96
JDK 1.1 1.1 Feb-97
J2SE 1.2 (Playground) 1.2 Dec-98
J2SE 1.3 (Kestrel) 1.3 May-00
J2SE 1.4 (Merlin) 1.4 Feb-02
J2SE 5.0 (Tiger) 1.5 Sep-04
Java SE 6 (Mustang) 1.6 Dec-06
Java SE 7 (Dolphin) 1.7 Jul-11
Java SE 8 1.8 Mar-14
Java SE 9 9 September, 21st 2017
Java SE 10 10 March, 20th 2018
Java SE 11 11 September, 25th 2018
Java SE 12 12 March, 19th 2019
Java SE 13 13 September, 17th 2019
Java SE 14 14 March, 17th 2020
Java SE 15 15 September, 15th 2020
Java SE 16 16 March, 16th 2021
Java SE 17 17
Expected on Sept. 2021
18 UNIT-I
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.
19 UNIT-I
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.
20 UNIT-I
Java is Compiled and Interpreted
Hardware and
Programmer
Operating System
21 UNIT-I
Java Translation and Execution
Java source code
Java compiler
Java bytecode
Java
Java interpreter Java interpreter Java interpreter
interpreter
for Windows for Mac for Razr v2
for Linux
22 UNIT-I
22
23 UNIT-I
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
24 UNIT-I
Characteristics of Java
• Java Is Simple Because Java inherits the
• Java Is Object-Oriented C/C++ syntax and many of the
• Java Is Distributed 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
25 UNIT-I
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
• Java Is Secure traditional procedural programming
techniques.
• Java Is Architecture-Neutral
• Java Is Portable One of the central issues in software
development is how to reuse code.
• Java's Performance Object-oriented programming provides
• Java Is Multithreaded great flexibility, modularity, clarity, and
reusability through encapsulation,
• Java Is Dynamic inheritance, and polymorphism.
26 UNIT-I
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
• Java Is Secure Invocation(RMI)
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
27 UNIT-I
Characteristics of Java
• Java Is Simple Java enables the creation of
cross-platform programs by compiling
• Java Is Object-Oriented into an intermediate representation
• Java Is Distributed called 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
28 UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
Java compilers can detect many problems
• Java Is Distributed that would first show up at execution time
• Java Is Interpreted in other languages.
29 UNIT-I
Characteristics of Java
• Java Is Simple By using a Java-compatible web
browser, we can safely download Java
• Java Is Object-Oriented applets without fear of viral infection or
• Java Is Distributed malicious intent.
30 UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
Write once, run anywhere
• Java Is Interpreted With a Java Virtual Machine (JVM), you
• Java Is Robust can write one program that will run on
any platform.
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
31 UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
Because Java is architecture neutral, Java
• Java Is Interpreted programs are portable.
• Java Is Robust They can be run on any platform without
being recompiled.
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
32 UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed The Just-in-time compilers allow the
• Java Is Interpreted platform-independent Java programs to be
executed with nearly the same run-time
• Java Is Robust performance as conventional compiled
• Java Is Secure programs
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
33 UNIT-I
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
• Java Is Secure operating system to enable multithreading.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
34 UNIT-I
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 objects at
• Java Is Robust run time. This makes it possible to dynamically
link code in a safe and expedient manner.
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
35 UNIT-I
OOP Principles
Encapsulation:
Inheritance:
Polymorphism:
36 UNIT-I
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 will
Inheritance: be shared by a set of objects.
The data defined by the class are referred to as
member variables or instance variables.
Polymorphism: The code that operates on that data is referred to as
member methods or just methods.
37 UNIT-I
OOP Principles
Encapsulation:
Polymorphism:
38 UNIT-I
OOP Principles
Encapsulation:
Inheritance:
39 UNIT-I
40 UNIT-I
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.
41 UNIT-I
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.
42 UNIT-I
Comments
Three types of comments
• Single-line //
• Multi-line /* */
• Documentation comment /** */
This type of comment is used to produce an HTML file that
documents your program.
43 UNIT-I
Separators
() Method definition and invocation, defining precedence in
expressions, in control statements and type casting.
{ } Initializing arrays, define blocks of code for classes,
methods and local scopes.
[ ] Declare array types, dereference array types.
; Terminates statements.
, In variable declaration, in for statement.
. To separate package names from sub packages and
classes and to separate a variable or method from a
reference variable.
44 UNIT-I
Keywords
Keywords are reserved words recognized by Java that cannot
be used as identifiers.
Java defines 50 keywords as follows:
enum
45 UNIT-I
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
46 UNIT-I
Integers:
47 UNIT-I
Floating-Point Types:
48 UNIT-I
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 of 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.
49 UNIT-I
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.
50 UNIT-I
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 or0X). The range of hexadecimal digits is 0
to 9 and A to F (a to f) for 10 to 15.
Ex: 0x12, 0X45, 0X1B
51 UNIT-I
Integer Literals:
Ex: 1234L,0x52dfL
52 UNIT-I
Floating-Point Literals:
53 UNIT-I
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.
54 UNIT-I
Character Literals:
A character literal is represented inside a pair of single quotes.
All of 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.
55 UNIT-I
Character Escape Sequence
56 UNIT-I
Variables
Declaring a Variable:
In Java, all variables must be declared before they can be used.
57 UNIT-I
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.
58 UNIT-I
59 UNIT-I
Type Conversion and Casting
Java supports both automatic type conversion and casting.
Java’s Automatic Conversions:
When one type of data is assigned to another type of variable, an
automatic type conversion will take place if the following two
conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes
place.
Ex:- int to long, byte to int, float to double …
60 UNIT-I
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 some times called a narrowing
conversion.
A different type of conversion will occur when a floating-point
value is assigned to an integer type: truncation.
61 UNIT-I
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.
62 UNIT-I
63 UNIT-I
Arrays
An array is a group of like-typed variables that are referred to by a
common name.
One-Dimensional Arrays
Multidimensional Arrays
64 UNIT-I
One-Dimensional Arrays:
65 UNIT-I
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays.
Ex:- int twoDim1[ ][ ]=new int[4][5];
66 UNIT-I
67 UNIT-I
Operators
Arithmetic Operators
Bitwise Operators
Relational Operators
68 UNIT-I
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
69 UNIT-I
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
70 UNIT-I
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
71 UNIT-I
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
72 UNIT-I
Operator Precedence:
() [] .
High ++ -- ~ !
* / %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
Low = Op=
73 UNIT-I
74 UNIT-I
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.
75 UNIT-I
Selection statements:
if
if-else
Nested ifs
The if-else-if ladder
switch
Nested switch Statements.
76 UNIT-I
Iteration statements:
while
do-while
for
77 UNIT-I
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.
78 UNIT-I
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.
79 UNIT-I
80 UNIT-I
Class Fundamentals
• A class defines a new data type.
81 UNIT-I
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
}
}
82 UNIT-I
Class Fundamentals
• The data (or) variables defined within a class are called instance
variables because each instance (object) of the class contains its own
copy of these variables.
• The code is contained within methods.
• Collectively, the methods and variables defined within a class are called
members of the class.
83 UNIT-I
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
85 UNIT-I
86 UNIT-I
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; width=w;
height=20; height=h;
depth=30; depth=d; Box b2=new Box(40,50,60);
} }
87 UNIT-I
88 UNIT-I
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
89 UNIT-I
Variable-Length Arguments(Varargs):
A method can have normal parameters along with a variable-length parameter. The
variable-length parameter must be the last parameter declared by the method.
Ex:- void display(int a, int … p)
void test(boolean a, boolean b, double c, char … d)
90 UNIT-I
Overloading Varargs Methods:
91 UNIT-I
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);
92 UNIT-I
93 UNIT-I
The 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; length=length; this.length=length;
} breadth=breadth; this.breadth=breadth;
} } }
} }
94 UNIT-I
static keyword:
Normally, a class member must be accessed only with an object of its class.
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);
}
}
95 UNIT-I
static variables:
To initialize static variables, declare a static block which get executed exactly
once, when the class is first loaded.
96 UNIT-I
static methods:
97 UNIT-I
final keyword:
final can be applied for variables, methods and classes.
98 UNIT-I
99 UNIT-I
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.
class A {
// members
class B {
//class B members
}
// members
}
102 UNIT-I
Nested and Inner Classes:
103 UNIT-I
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
}
104 UNIT-I
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
}
105 UNIT-I
106 UNIT-I
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.
The classes String, StringBuffer and StringBuilder are defined in java.lang package.
All are final.
107 UNIT-I
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
108 UNIT-I
String Literals:
String s = ”abcdefghij”;
String Length:
int length( )
109 UNIT-I
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 );
110 UNIT-I
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”
111 UNIT-I
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.
113 UNIT-I
Example:
115 UNIT-I
String Comparision:
116 UNIT-I
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)
117 UNIT-I
Modifying a String:
String substring(int startIndex)
String substring(int startIndex, int endIndex)
String trim( )
118 UNIT-I
Changing the Case of Characters within a String:
String toLowerCase( )
String toUpperCase( )
119 UNIT-I
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)
120 UNIT-I
121 UNIT-I
StringBuffer Constructors:
StringBuffer( ) 16 characters
StringBuffer(int size)
StringBuffer(String str) str+16 characters
StringBuffer(CharSequence chars)
122 UNIT-I
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)
Ensures that the capacity of the buffer is at least equal to the specified minimum.
The new capacity is the larger of:
a. The minimumCapacity argument.
b. Twice the old capacity, plus 2.
123 UNIT-I
Methods:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)
StringBuffer reverse( )
124 UNIT-I
THANK YOU
UNIT-I 125