0% found this document useful (0 votes)
3 views

Unit-1-Intro To Java

Core java

Uploaded by

Aryan Gireesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Unit-1-Intro To Java

Core java

Uploaded by

Aryan Gireesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 96

Unit 1

Java Fundamentals

1 Asst. Prof. Rameshwari H.


A Short History of Java

Java is general-purpose , object oriented programming


language developed by Sun Microsystems of USA in
1991.

Java is initially called as Oak.It was renamed as “Java”


in 1995.

Java was developed by Five inventors, These inventors


are James Gosling,Chris Warth,Patrick Naughton,Ed
Frank and Mike Sheridan.

1 Asst. Prof. Rameshwari H.


Features of Java

Compiled &
Interpreted

1 Asst. Prof. Rameshwari H.


1.Simple:

Java is easy to learn and its syntax is quite simple, clean and
easy to understand.
removed many confusing and/or rarely-used features
e.g., explicit pointers, operator overloading etc.
No need to remove unreferenced objects because there is
Automatic Garbage Collection in java.

2.Object Oriented:
Java is object oriented language like c++,but it does not
support multiple inheritance.
Java can be easily extended as it is based on Object Model.

1 Asst. Prof. Rameshwari H.


3)Platform Independent:
Java code can be run on multiple platforms
e.g. Windows, Linux, Sun Solaris, Mac/OS etc. Java code is
compiled by the compiler and converted into byte code. This
byte code is a platform-independent code because it can be
run on multiple platforms i.e. Write Once and Run
Anywhere(WORA).

1 Asst. Prof. Rameshwari H.


4.Secure: Java is aimed to be used in networked and
distributed environments.

Java security’s components-


1.Class Loader: It adds security by separating the package
for the classes of the local file system from those that are
imported from network sources.
1 Asst. Prof. Rameshwari H.
2.Bytecode Verifier:
It checks the code fragments for illegal code that can
violate access right to objects and ensures java program
has compiled correctly.

3.Security Manager:
It implements security policy of JVM. It determines what
resources a class can access such as reading and writing
to the local disk.

1 Asst. Prof. Rameshwari H.


5)Robust:
Robust simply means strong.
Java uses strong memory management. There are lack
of pointers that avoids security problem.
There is automatic garbage collection in java.
There is exception handling and type checking
mechanism in java.

1 Asst. Prof. Rameshwari H.


6)Portable:
Java programs can easily work from one computer to
another.
The java code generates the byte code which can be executed
on any machine.

7)Architectural Neutral:
Compiler generates bytecodes, which can be executed by any
processor,nothing to do with particular computer
architecture.
hence a Java program is easy to intrepret on any machine.

1 Asst. Prof. Rameshwari H.


8)Compiled and Interpreted:
Usually a computer language is either compiled or
interpreted.
Java is two stage system. First, Java compiler translates
source code into bytecode instructions. Bytecode is not
machine instructions and hence,
In second stage,Java interpreter generates machine code
that can be directly executed by machine i.e running java
program.

1 Asst. Prof. Rameshwari H.


9)Distributed:
We can create distributed applications in java.
RMI and EJB(Enterprise Java Bean) are used for creating
distributed applications.
We may access files by calling the methods from any
machine on the internet.

10)High Performance:

Java gives high performance due to use of intermediate


bytecode.
Java is designed in such way that reduces the overheads at
runtime.

1 Asst. Prof. Rameshwari H.


11)Multithreaded:
Thread is light weight sub process.Multithreading means to
execute multiple thrads simultaneously.
Benefit of multithreading is that it utilizes same memory

12)Dynamic:
It supports Dynamic memory allocation due to this
memory wastage is reduce and improve performance
of the application.

1 Asst. Prof. Rameshwari H.


Types of Java Applications

There are mainly 4 type of applications that can be created using


java programming:
1) Standalone Application
It is also known as desktop application or window-based
application. An application that we need to install on every
machine such as media player, antivirus etc. AWT and Swing
are used in java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates
dynamic page, is called web application. Currently, servlet,
jsp, struts, jsf etc. technologies are used for creating web
applications in java.

1 Asst. Prof. Rameshwari H.


⦿3) Enterprise Application
An application that is distributed in nature, such as
banking applications etc. It has the advantage of high
level security, load balancing and clustering. In java, EJB
is used for creating enterprise applications.

⦿4) Mobile Application


An application that is created for mobile devices.
Currently Android and Java ME are used for creating
mobile applications.

1 Asst. Prof. Rameshwari H.


Comparison of Java and C++
C++ Java

C++ is Java is platform-independent.


platform-dependent.
C++ is mainly used for Java is mainly used for
system programming. application programming. It is
widely used in window,
web-based, enterprise and
mobile applications.
C++ supports goto Java doesn't support goto
statement. statement.
C++ supports multiple Java doesn't support multiple
inheritance. inheritance through class. It
can be achieved by interfaces
in java.
1
C++ supports operator
Asst. Prof. Rameshwari H.
Java does not support operator
overloading. overloading.
C++ is only compiled Java is compiled and interpreted
language. language
C++ supports structures and Java doesn't support structures
unions. and unions.

C++ doesn't have built-in Java has built-in thread support.


support for threads.

C++ doesn't support Java supports documentation


documentation comment. comment (/** ... */) to create
documentation for java source
code.
C++ supports pointers. Java supports pointer
You can write pointer internally. But you can't write
program in C++. the pointer program in java.

1 Asst. Prof. Rameshwari H.


Simple Java Program

Class Hello
{
public static void main(String args[])
{
System.out.println("Hello Java World");
}
}

To compile Java program: Javac Hello.java

To run java program : java Hello

1
Output: Hello Java World
Asst. Prof. Rameshwari H.
public keyword is an access modifier which represents
visibility, it means it is visible to all,hence it is accessible to
all other classes.

Static: The keyword static declares this method as one that


belong to the entire class.The core advantage of static method
is that there is no need to create object to invoke the static
method. The main method is executed by the JVM, so it
doesn't require to create object to invoke the main method. So
it saves memory.

void is the return type of the method, it means it doesn't


return any value.

main represents startup of the program.


1 Asst. Prof. Rameshwari H.
String args[] is used for command line argument.
Valid java main method signature

public static void main(String[] args)

public static void main(String []args)

public static void main(String args[])

public static void main(String... args)

static public void main(String[] args)

1 Asst. Prof. Rameshwari H.


System.out.println() is used print statement.

System is a class,out is object of System class and println()


is used to print data on screen.

1 Asst. Prof. Rameshwari H.


Difference between print() and println():

1.Print(): This method just prints output on screen. It does not


append newline character, hence after printing output, cursor
is on same line.

2.println(): This method prints output on screen.It always


append newline character to the end of string.It displays
message and cursor moves to next line.

1 Asst. Prof. Rameshwari H.


Java Virtual Machine:

1 Asst. Prof. Rameshwari H.


Java Development Kit

JDK comes with collection of tools that are used for


developing and running java program, They includes
following tools-

Java Tools:

javac - The Java Compiler


javac compiles Java programs.
❖Javac is the java compiler which compiles .java file into
.class file(i.e. bytecode).
❖If the prog. has syntax errors, javac reports them.
If the pro. Is error free, the output of this command is
.class file.
Syntax
1
javac filename.java
Asst. Prof. Rameshwari H.

E.g. javac prog.java


Java:
Java Interpreter. This command starts java runtime
environment, loads the specified .class file and
converts .class file into executable code.It interprets
code.

Syntax:
java classname

E.g.
java Hello

1 Asst. Prof. Rameshwari H.


Javap:
Javap tool disassembles compiled java files and print out a
representation of the java program.
it work exactelly reverse to the javac
Javap command displays information about fields,
constructor and methods present in a class file.

Syntax:
Javap classname

Options of javap:
-help
-l
-c
-s
-sysinfo
1 Asst. Prof. Rameshwari H.
-constants
-version
javadoc

It is a utility for generating HTML documentation


directly from java.

Syntax:
Javadoc source files

This command shows description of all classes,


methods and objects present in the given source file

1 Asst. Prof. Rameshwari H.


jdb
Jdb helps you find and fix bugs in java language
programs.
This debugger has limited functionality.
This command executes the main class file, which is
added to JDB for debugging.

Syntax :
Jdb classname
Class : Name of class to begin debugging.
E. g. jdb proj

1 Asst. Prof. Rameshwari H.


appletviewer
appletviewer is used to execute java applets.
Applets are small java programs which are executed
and displayed in a java compatible web browser.

Syntax:
Save your prog containing applet as prog.java
first compile your prog using command javac
prog.java
execute it using command – appletviewer
prog.class

1 Asst. Prof. Rameshwari H.


Java Program Structure

Documentation Section

Package Statement
Import Statement
Interface Statements
Class Definitions
Main Method class
{
Main Method Definition
}

1 Asst. Prof. Rameshwari H.


Java Tokens

Smallest individual units in a prog are known as tokens.

The compiler recognizes them for building up expressions and


statements.

Java includes 5 types of tokens. They are:

Reserved Words
Identifiers
Literals
Operators
Separators

1 Asst. Prof. Rameshwari H.


Keywords

abstract boolean break byte


case catch char class
const * continue default do
double else extends final
finally float for goto *
if implements import instanceof
int interface long native
new package private protected
public return short static
strictfp super switch synchronized
this throw throws transient
try void volatile while

1 Asst. Prof. Rameshwari H.


Identifiers

All Java components require names.

Name used for classes, methods, interfaces and variables are


called Identifier.

Identifier must follow some rules.

Here are the rules:


▪All identifiers start with a letter ( a to z or A to Z )
▪After the first character, an identifier can have any
combination of characters.
▪A Java keyword cannot be used as an identifier.
Identifiers in Java are case sensitive, foo and Foo are two
different identifiers.

1 Asst. Prof. Rameshwari H.


Literals

Literals in Java are a sequence of characters (digits, letters, and


other characters) that represent constant values to be stored in
variables.

Java language specifies five major types of literals.


Integer literals int d = 100;
Floating literals float f=3.5;
Character literals char c=‘a’;
String literals String s= "This is a string“;
Boolean literals boolean chosen = true;

1 Asst. Prof. Rameshwari H.


Data Types

Java language has a rich implementation of data types. Data types


specify size and the type of values that can be stored in an
identifier.

In java, data types are classified into two catagories :


Primitive Data type
Non-Primitive Data type

1 Asst. Prof. Rameshwari H.


1 Asst. Prof. Rameshwari H.
Data Size(in Range Example
type bits)
byte 8 -128 to +127 byte b=10;

Short 16 -32768 to 32767. short s=11;

Int 32 -2147483648 to int i=10;


2147483647
long 64 -9,223,372,036,854,775, long l=100012;
808 to
9,223,372,036,854,775,8
07

1 Asst. Prof. Rameshwari H.


This group includes float, double

Data type Size(i Example


n bits)
float 32 float ff=10.3f;
double 64 double
db=11.123;

1 Asst. Prof. Rameshwari H.


Char:

This group represent char, which represent symbols in a


character set, like letters and numbers.

char : It is 16 bit unsigned unicode character.


Range 0 to 65,535.

example: char c='a';

1 Asst. Prof. Rameshwari H.


boolean

This group represent boolean, which is a special type for


representing true/false values.

It requires only 1 bit memory allocation.


example:
boolean b=true;

1 Asst. Prof. Rameshwari H.


Variables

Variable is name of reserved area allocated in memory. It is


used to store data value.
int data=50;//Here data is variable

Types of Variable
There are three types of variables in java
1.local variable
2.instance variable
3.static variable

1 Asst. Prof. Rameshwari H.


Types of Variable

Local Variable
A variable that is declared inside the method is called
local variable.

Instance Variable
A variable that is declared inside the class but outside
the method is called instance variable.

Static variable
A variable that is declared as static is called static
variable. It cannot be local.

1 Asst. Prof. Rameshwari H.


Example to understand types of variable

class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}//end of class

1 Asst. Prof. Rameshwari H.


Operators:
Simple Assignment Operator
= Simple assignment operator

Arithmetic Operators
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator

1 Asst. Prof. Rameshwari H.


Unary Operators

+ Unary plus operator; indicates positive value (numbers


are positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical complement operator; inverts the value of a
boolean

1 Asst. Prof. Rameshwari H.


Equality and Relational Operators

== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to

1 Asst. Prof. Rameshwari H.


Logical Operator

&& Logical-AND
|| Logical-OR
! Logical NOT

Conditional Operators

?: Ternary (shorthand for if-then-else statement)

1 Asst. Prof. Rameshwari H.


Bitwise and Bit Shift Operators

~ Unary bitwise complement


<< Signed left shift
>> Signed right shift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR

1 Asst. Prof. Rameshwari H.


Built – in Packages:

1 Asst. Prof. Rameshwari H.


Built-in Packages

These packages consist of a large number of classes which are a part of


Java API.Some of the commonly used built-in packages are:

1) java.lang: Contains language support classes(e.g classed which defines


primitive data types, math operations). This package is automatically
imported.

2) java.io: Contains classed for supporting input / output operations.

3) java.util: Contains utility classes which implement data structures


like Linked List, Dictionary and support ; for Date / Time operations.

4) java.applet: Contains classes for creating Applets.

5) java.awt: Contain classes for implementing the components for


graphical user interfaces (like button , ;menus etc).

6) java.net: Contain classes for supporting networking operations.

1 Asst. Prof. Rameshwari H.


Bult-in Packages and Classes

Java.io package

Accepting input from console


using BufferedReader class

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

1 Asst. Prof. Rameshwari H.


import java.io.*;

class inputdemo1
{
public static void main(String args[]) throws IOException
{

BufferedReader br = new BufferedReader(new


InputStreamReader(System.in));

System.out.print("Enter your name: ");


String name = br.readLine();

System.out.println("Welcome " + name);


}
}
1 Asst. Prof. Rameshwari H.
Accepting input from console
using Scanner class

1 Asst. Prof. Rameshwari H.


import java.util.*;
class inputdemo2
{
public static void main(String args[])
{
int rno;
Double fee;
String name;
Scanner sc = new Scanner(System.in);
System.out.print("Enter your Rno: ");
rno=sc.nextInt();

System.out.print("Enter your name: ");


name=sc.next();

System.out.println("Student Information: ");


System.out.println("Rno: "+rno+"\tName: "+name);
1
} Asst. Prof. Rameshwari H.

}
Command Line Arguments

The java command-line argument is an argument i.e. passed at the


time of running the java program.

The arguments passed from the console can be received in the java
program and it can be used as an input.

So, it provides a convenient way to check the behavior of the


program for the different values.

You can pass N (1,2,3 and so on) numbers of arguments from the
command prompt.

1 Asst. Prof. Rameshwari H.


Type Casting:

It is used to store value of one data type into a variable of


another data type..

Syntax:
Data_type variable1=(Data_type)variable2;

Eg:
int x=10;
byte y=(byte)x; //Casting into smaller type results into loss of data.

Float z=(float)x; //No loss of data

1 Asst. Prof. Rameshwari H.


Control Statements

•If statement

•Switch statement

•While and do while statement

•For statement

1 Asst. Prof. Rameshwari H.


If statement

if(condition)
{
Block of statements
}
else
{
Block of statements
}

1 Asst. Prof. Rameshwari H.


Switch
switch(choice)
{
case 1: _______________
Break;
case 2: _______________
Break;
.
.
case n: _______________
Break;
default: _______________
Break;
}

1 Asst. Prof. Rameshwari H.


While loop

While(condition)
{
____________________
____________________
____________________
}

Entry controlled loop

1 Asst. Prof. Rameshwari H.


Do… while loop

do
{
______________________
______________________
}while(cond);

Exit Controlled Loop

1 Asst. Prof. Rameshwari H.


//Program to display fibonnaci series upto given limit.
class fibbo
{
public static void main(String args[])
{
int n,f0=0,f1=1,f2,i=3;
n=Integer.parseInt(args[0]);
System.out.print(f0+"\t"+f1+"\t");
do
{
f2=f0+f1;
System.out.print(f2+"\t");
f0=f1;
f1=f2;
i++;
}while(i<=n);

1
} Asst. Prof. Rameshwari H.

}
For loop

for(initialization; condition; incr/decr)


{

Block Statements;

1 Asst. Prof. Rameshwari H.


//Program to check given number is prime or not.
import java.util.*;
class primedemo
{
public static void main(String args[])
{
int n,i,flag=0;
System.out.println("Enter number: ");
Scanner sc=new Scanner(System.in);
n=sc.nextInt();
for(i=2;i<n;i++)
{
if(n%i==0)
{
flag=1;
break;
}
}
if(flag==0)
System.out.println("Number is prime");
else
System.out.println("Number is not prime");
1} Asst. Prof. Rameshwari H.

}
Break Statement
The break statement breaks out of a loop. It jumps out of
the current iteration and ends the immediate loop.

Syntax:
break;

1 Asst. Prof. Rameshwari H.


//break demo
class breakdemo
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{
System.out.println(i);

if(i==6)
break;
}
}
}

1 Asst. Prof. Rameshwari H.


Continue Statement in Java programming :
Skip Part of Loop

Continue Statement in Java is used to skip the part of loop.


Unlike break statement it does not terminate the loop ,
instead it skips the remaining part of the loop and control
again goes to check the condition again.

Syntax:
Continue;

1 Asst. Prof. Rameshwari H.


//continue demo
class continuedemo
{
public static void main(String args[])
{
int i;
for(i=1;i<=10;i++)
{

if(i%2==0)
continue;
System.out.println(i);
}
}
}

1 Asst. Prof. Rameshwari H.


Array
An array is a group of elements of same types that are
referred by a common name.

Arrays can be of any type created and may have one or


more dimensions.

A specific element in an array is accessed by its index.

1 Asst. Prof. Rameshwari H.


One Dimensional Arrays
► An 1D array means an one dimensional array.
► An array element is declared using brackets
► For example:
► //declare an integer array using the brackets
int[] Array;

► //allocate memory for 5 integers


Array = new int[5];
► //first element
Array[0] = 10;
► //second element
1 Array[1] = 20;
Asst. Prof. Rameshwari H.
Multi Dimensional Arrays
► In Java, multidimensional arrays are actually
arrays of arrays.
► To declare a multidimensional array variable,
specify each additional index using another set
of square brackets.
► For example, the following declares a
two-dimensional array variable called twoD.
► int twoD[][] = new int[4][5];
► This allocates a 4 by 5 array and assigns it
to twoD. Internally this matrix is
implemented as an array of arraysof int.
1 Asst. Prof. Rameshwari H.
Strings

❖string is a sequence of characters. But in java, string is an


object that represents a sequence of characters.

example:

char[] ch={‘w’,’e’,’l’,’c’,’o’,’m’,’e’'};

String s=new String(ch);

1 Asst. Prof. Rameshwari H.


How to create String object?
There are two ways to create String object:
1) By string literal
2)By new keyword

1.By String Literal:

Java String literal is created by using double quotes.

For Example:

String s="welcome";

1 Asst. Prof. Rameshwari H.


2. By new keyword

String s=new String("Welcome");

1 Asst. Prof. Rameshwari H.


class stringdemo
{
public static void main(String args[])
{
String s1="Welcome“;

char ch[]={'H','e','l','l','o'};

String s2=new String(ch);

String s3=new String("World");

System.out.println(s1);
System.out.println(s2);
System.out.println(s3);

}
}1 Asst. Prof. Rameshwari H.
StringBuffer
StringBuffer is a peer class of String that provides much of
the functionality of strings.
The major difference between the String and StringBuffer is
that String class creates string of fixed length, StringBuffer
creates strings of flexible length that can be modified in terms of
both length and content.

StringBuffer Constructors

StringBuffer( )
StringBuffer(int size)
StringBuffer(String str)
1 Asst. Prof. Rameshwari H.
String StringBuffer

1.StringBuffer class is
1.String class is immutable.
mutable.

2.String is slow and consumes


more memory when you 2.StringBuffer is fast and
concat too many strings consumes less memory when
because every time it creates you concat strings.
new instance.
3. String class overrides the
equals() method of Object StringBuffer class doesn't
class. So you can compare the override the equals() method
contents of two strings by of Object class
equals() method.
1 Asst. Prof. Rameshwari H.
No. String StringBuffer

1) The String class is The StringBuffer class


immutable. is mutable.
2) String is slow and StringBuffer is fast and
consumes more memory consumes less memory
when we concatenate when we concatenate t
too many strings strings.
because every time it
creates new instance.

3) String class overrides StringBuffer class


the equals() method of doesn't override the
Object class. So you can equals() method of
compare the contents of Object class.
two strings by equals()
method.

4) String class is slower StringBuffer class is


while performing faster while performing
concatenation operation. concatenation operation.

5) String class uses String StringBuffer uses Heap


constant pool. memory

1 Asst. Prof. Rameshwari H.


Methods of string class

String Length():
length():This method returns the number of characters
contained in the string object.

Example:

String p = “Welcome";
int len = p.length();

It returns length 7.

1 Asst. Prof. Rameshwari H.


charAt(i)

It returns the ith character in the string, counting from 0.

String p = “Welcome";
char c = p.charAt(3);

Output: c

1 Asst. Prof. Rameshwari H.


getChars()

If you need to extract more than one character at a time, you


can use the getChars( ) method. :

Syntax:

void getChars( int sourceStart, int sourceEnd, char target[ ], int


targetStart)

1 Asst. Prof. Rameshwari H.


class getchardemo
{
public static void main(String args[])
{
String s = "This is a demo of the getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println(buf);
}
}

Output:demo

1 Asst. Prof. Rameshwari H.


equals( )
To compare two strings for equality, use equals( ).

Syntax:

boolean equals(Object str)

equalsIgnoreCase( ): To perform a comparison that ignores


case differences
When it compares two strings, it considers A-Z to be the same
as a-z.

Syntax:

boolean equalsIgnoreCase(String str)


1 Asst. Prof. Rameshwari H.
class equalsDemo
{
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1 + " equals " + s2 + " -> " +s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " +s1.equals(s3));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
}
}

1 Asst. Prof. Rameshwari H.


concat( )

You can concatenate two strings using concat( ), shown here:


String concat(String str)

This method creates a new object that contains the invoking


string with the contents of str appended to the end.

concat( ) performs the same function as +. For example,

String s1 = "one";
String s2 = s1.concat("two");
puts the string “onetwo” into s2. I

1 Asst. Prof. Rameshwari H.


replace():

This method replaces all occurrences of one character in the


invoking string with another character. It has the following
general form:

String replace(char original, char replacement)

Here, original specifies the character to be replaced by the


character specified by replacement.

The resulting string is returned. For example,

String s = "Hello".replace('l', 'w');

Output: Hewwo
1 Asst. Prof. Rameshwari H.
substring( )
You can extract a substring using substring( ). It has two
forms.
Syntax of first form:
String substring(int startIndex)
Here, startIndex specifies the index at which the substring
will begin

The second form of substring( ) allows you to specify both


the beginning and ending index of the substring:

String substring(int startIndex, int endIndex)

String str = "Hello";


String a = str.substring(1); // a is "ello" (i.e. starting at
index 1)
String b = str.substring(2,4); // b is "llo"
1 Asst. Prof. Rameshwari H.
Searching Strings
■ indexOf( ) Searches for the first occurrence of a character or
substring.

■ lastIndexOf( ) Searches for the last occurrence of a character


or substring.

To search for the first occurrence of a character, use

int indexOf(int ch)

To search for the last occurrence of a character, use

int lastIndexOf(int ch)

String s = "Hello How r u?";


System.out.println("indexOf(H) = " +s.indexOf('H'));
1 Asst. Prof. Rameshwari H.
System.out.println("lastIndexOf(H) = " +s.lastIndexOf('H'));
Methods of StringBuffer:

insert(): Inserts the string representation of the argument into the StringBuffer at the specified position
For example= StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " World"); // sb now contains "Hello World“

append(): Appends the string representation of the argument to the StringBuffer


For example= StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // sb now contains "Hello World“

delete(): Removes the characters in a substring of this sequence

For example= StringBuffer sb = new StringBuffer("Hello World");


sb.delete(5, 11); // sb now contains "Hello"

1 Asst. Prof. Rameshwari H.


length( ) and capacity( )
The current length of a StringBuffer can be found via the length( ) method,
while the total allocated capacity can be found through the capacity( )
method.

Syntax:

int length( )
int capacity( )

1 Asst. Prof. Rameshwari H.


// StringBuffer length vs. capacity.
class StringBufferDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}

Output:

buffer = Hello
length = 5
capacity = 21
1 Asst. Prof. Rameshwari H.
insert( ):

The insert( ) method inserts one string into another. It is


overloaded to accept values of all the simple types, plus Strings
and Objects. Like append( ), it calls String.valueOf( ) to obtain
the string representation of the value it is called with.

Constructors:

StringBuffer insert(int index, String str)


StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

1 Asst. Prof. Rameshwari H.


invoking StringBuffer object.
The following sample program inserts “like” between “I” and
“Java”:
// Demonstrate insert().

class insertDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}

Output:
1 Asst. Prof. Rameshwari H.

I like Java!
reverse( )
You can reverse the characters within a StringBuffer object
using reverse( ).

Syntax:

StringBuffer reverse( )

This method returns the reversed object on which it was called.


The following program
demonstrates reverse( ):
// Using reverse() to reverse a StringBuffer.

1 Asst. Prof. Rameshwari H.


class ReverseDemo
{
public static void main(String args[])
{
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}

Output:

abcdef
fedcba

1 Asst. Prof. Rameshwari H.


delete( ) and deleteCharAt( )

This ability to delete characters using the methods delete( )


and deleteCharAt( ).

These methods are shown here:

StringBuffer delete(int startIndex, int endIndex)


StringBuffer deleteCharAt(int loc)

1 Asst. Prof. Rameshwari H.


class deleteDemo
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
/*
After delete: This a test.
After deleteCharAt: his a test.*/

1 Asst. Prof. Rameshwari H.

You might also like