C++ and Java

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 49

MODULE-V

STRING HANDLING
OUTLINE OF MODULE

 Introduction of String in java

 String methods

 String Buffer

 Utility classes
Strings in Java
String Handling
 String Handling provides a lot of concepts that can be
performed on a string such as concatenating string,
comparing string, substring etc.

 In Java, string is basically an immutable object.

 Generally string is a sequence of characters. But in java, string


is an object.
Introduction

String is a sequence of characters.

In the Java programming language, strings are objects.

Java provides a class called “String” in “java.lang” package to


create and manipulate strings.

The string value must be represented in “ ” (double cotes).


IMMUTABLE STRING IN JAVA
 In java, string objects are immutable. Immutable simply means
unmodifiable or unchangeable.

 Once string object is created its data or state can't be changed but a
new string object is created.

class Simple
{
public static void main(String args[])
{
String s="Sachin";
s.concat(" Tendulkar);
System.out.println(s);
}
}
ADVANTAGES OF IMMUTABILITY

Uses less memory.

String word1 = "Java"; String word1 = “Java";


String word2 = word1; String word2 = new String(word1);

word1 word1 “Java"

“Java" word2 “Java"


word2
Less efficient:
OK wastes memory
CREATE STRING OBJECT

 There are two ways to create String object:

 By string literal

 By new keyword
Creating String
Direct way to create a string

Variable
name

String s = “Good Morning!";

Data type defined in Variable


Java.lang value
Creating String
Another way to create a string using new keyword

Variable String class


Constructor
name

String s = new String(“Good Morning!“);

Data type defined new


Variable
in operator
value
Java.lang
Creating String
Another way to create a string

char msg[ ] = {‘’J,’A’,’V’,’A’};


String name = new String(msg);

Here, first we create a character array and pass that array as


argument to the string class constructor
EXAMPE
public class StringExample
{
public static void main(String args[])
{
String s1="java’;
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);
String s3=new String("example");
System.out.println(s1); OUTPUT:
Java
System.out.println(s2); strings
example
System.out.println(s3);
}
}
Methods in String Class

length()
concat()
charAt()
compareTo()
compareToIgnoreCase()

endsWith()

startsWith()
Equals()
Methods in String Class

equalsIgnoreCase()
indexOf(int ch)
indexOf(String str)
substring(int beginIndex)
toLowerCase()
toUpperCase()
trim()
STRING COMPARE
 We can compare string in java on the basis of content and
reference.

 There are three ways to compare string :


 By equals() method

 By = = operator

 By compareTo() method
STRING COMPARE BY EQUALS() METHOD

 The String equals() method compares the original content of


the string.

Two methods:

 equals(Object another) compare this string to the specified


object.

 equalsIgnoreCase(String another) compare this String to


another string, ignoring case.
STRING COMPARE BY EQUALS() METHOD
class Test
{
public static void main(String args[])
{
String s1=“Divya";
String s2=“Divya";
String s3=new String(“Divya");
String s4=“Sneha";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
STRING COMPARE BY EQUALSIGNORECASEMETHOD

class Test
{
public static void main(String args[])
{
String s1=“Dibya";
String s2=“DIBYA";
System.out.println(s1.equals(s2));//false
System.out.println(s1.equalsIgnoreCase(s3));//true
}
}
STRING COMPARE BY == OPERATOR
 The = = operator compares references not values.

class Test
{
public static void main(String args[])
{
String s1=“Dibya";
String s2=“Dibya";
String s3=new String(“Dibya");
System.out.println(s1==s2);//true (both refer to same instance)
System.out.println(s1==s3);//false( s3 refers to instance)
}
}
COMPARETO() METHOD
 The String compareTo() method compares values and returns
an integer value.
 Suppose s1 and s2 are two string variables. If:

s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value

class Test
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2)); //0
System.out.println(s1.compareTo(s3)); //1(because s1>s3)
System.out.println(s3.compareTo(s1)); //-1(because s3 < s1 )
}
}
CHARAT()
 charAt() method returns a char value at the given index
number. The index number starts value is 0.

public class CharAt


{
public static void main(String args[])
{
String name=“Techno";
char ch=name.charAt(4);
System.out.println(ch);
}
}
LENGTH()
 length() method length of the string. It returns count of total
number of characters.

public class Length


{
public static void main(String args[])
{
String s1=“Techno";
String s2=“Java";
System.out.println("string length is: "+s1.length());//6 is the length
System.out.println("string length is: "+s2.length());//4 is the length
}
}
SUBSTRING()
 public String substring(int startIndex)

 public String substring(int startIndex, int endIndex)

public class Substring


{
public static void main(String args[])
{
String s1="Techno";
System.out.println(s1.substring(2,4));//returns chn
System.out.println(s1.substring(2));//returns chno
}
}
CONTAINS()
 contains() method searches the sequence of characters in this
string.
 It returns true if sequence of char values are found in this string
otherwise returns false.
String_var_name. contains(Char sequence)
class Contains OUTPUT:
{ true
true
public static void main(String args[]) false
{
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}
}
REPLACE()
 replace() method returns a string replacing all the old char to
new char or CharSequence

Syntax:
String.replace(char oldChar, char newChar)
class Replace
{
public static void main(String args[])
{
String s1=" java";
String replaceString=s1.replace('a','e');//replaces all occur of 'a' to 'e'
System.out.println(replaceString);
}}
TRIM()
 The trim() method in java removes the spaces and returns
the omitted string.

class StringTrim
{
public static void main(String args[])
{
String s1=" Hello ";
System.out.println(s1.trim()+" Tech ");//with trim()
}
Output:
} Hello Tech
INDEXOF()
 indexOf() method returns index of given character value or
substring. If it is not found, it returns -1.

No. Method Description

1 int indexOf(int ch) returns index position for the given char value

returns index position for the given char value and


2 int indexOf(int ch, int fromIndex)
from index

3 int indexOf(String substring) returns index position for the given substring

returns index position for the given substring and


4 int indexOf(String substring, int fromIndex)
from index
class IndexOf
{
public static void main(String args[])
{
Output:

String s1="this is index of example"; 2 8

int index1=s1.indexOf("is");//returns the index of is substring

int index2=s1.indexOf("index");//returns the index of index substring

System.out.println(index1+" "+index2);//2 8
}
}
TOLOWERCASE(),
 toLowerCase() method converts all characters of the string
into lower case letter.

public class StringLower


{
public static void main(String args[])
{
String s1=“Techno";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}

2
}
9
TOUPPERCASE()
 toUpperCase() method converts all characters of the string into
upper case letter

public class StringUpper


{
public static void main(String args[])
{
String s1=“Techno";
String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}
}
VALUEOF()
 valueOf() method converts different types of values into string

 By the help of string valueOf() method, you can convert int to


string, long to string, boolean to string, character to string, float to
string, double to string, object to string and char array to string.

String str1 = String.valueOf(10);

3
1
VALUEOF()

public class StringValueOf


{
public static void main(String args[])
{
int value=30;
String s1=String.valueOf(value);
System.out.println(s1+10);//concatenating string with 10
}
OUTPUT:
}
3010

3
2
STARTSWITH()

 startsWith() method checks if this string starts with given


prefix

 It returns true if this string starts with given prefix else returns
false.

Syntax: startsWith(String prefix)


Or
startsWith(String prefix, int offset)

 prefix -- the prefix to be matched.

 offset -- where to begin looking in the string.


3
3
STARTSWITH()
public class Test
{
public static void main(String args[])
{
String Str = new String("Welcome to our Tutorials");
System.out.println(Str.startsWith("Welcome") );
System.out.println(Str.startsWith("Tutorials") );
System.out.println(Str.startsWith("Tutorials", 16) );
}
} Output:
Return Value :true
Return Value :false
Return Value :true

3
4
ENDSWITH()
 endsWith() method checks if this string ends with given
suffix.
 Syntax: endsWith(String suffix);

public class EndsWith Output:


{ True

public static void main(String args[])


{
String s1=“Java byBala;
System.out.println(s1.endsWith(“a")); //true
}
}
3
5
STRINGBUFFER CLASS
 StringBuffer is a class in Java that represents a mutable
sequence of characters.

 It provides an alternative to the immutable String class,


allowing you to modify the contents of a string without
creating a new object.
CREATION OF STRINGBUFFER CLASS
 StringBuffer(): creates an empty string buffer with an initial
capacity of 16.

StringBuffer Buffer_name=new StringBuffer();

 StringBuffer(String str): creates a string buffer with the


specified string.

StringBuffer Buffer_name=new StringBuffer(String);

 StringBuffer(int capacity): creates an empty string buffer


with the specified capacity as length.

StringBuffer Buffer_name=new StringBuffer(n);


METHODS OF JAVA STRINGBUFFER CLASS
 append()-Used to add text at the end of the existing text.

 length()-Returns the length of the string

 Setlength()-used to set new length for the created String buffer

 Capacity()-to find out the total allocated capacity(current).

 setCharAt()-Used to change the char at the specified index.

 delete()-Deletes a sequence of characters from the invoking object

 insert()-Inserts text at the specified index position

 reverse()-Reverse the characters within a StringBuffer object

 replace()-Replace one set of characters with another set inside a StringBuffer object
1. APPEND() METHOD
 The append() method concatenates the given new string at
the end of the calling StringBuffer.
 Syntax:

Buffer_Name.append(String);
Example:
class A
Output
{
public static void main(String args[]) Hello Java

{
StringBuffer sb = new StringBuffer("Hello ");
sb.append("Java"); // now original string is changed
System.out.println(sb);
}
}
2. LENGTH() METHOD
 Returns the length of the string

 Syntax:
Buffer_Name.length(String);

 Example:

import java.io.*;
class Main
{
public static void main(String args[])
{
StringBuffer sb= new StringBuffer("Java");
System.out.println(“The length String is:"+sb.length());
} OUPUT
}
The length String is: 4
SETLENGTH()
 Syntax:
Buffer_Name.setLength();

import java.io.*;
class Main
{
public static void main(String args[])

StringBuffer sb= new StringBuffer("Java");


System.out.println("The length String is:"+sb.length());
sb.setLength(3);
System.out.println("The SetlengthOutput
String is:"+sb);
}
} The length String is: 4

The Set length String is: Ja


CAPACITY() METHOD
 The capacity() method returns the current capacity value.

 The default capacity of the buffer is 16.

 If the number of character increases from its current capacity,


it increases the capacity by (oldcapacity*2)+2.

 For example if your current capacity is 16, it will be


(16*2)+2=34.

 Syntax:
Buffer_Name.capacity();
EXAMPE:
Output
import java.io.*; 16
class Main 16
{ 34
public static void main(String args[])
{
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity()); // default 16

sb.append("Hello");
System.out.println(sb.capacity()); // now 16

sb.append("java is my fav ");


System.out.println(sb.capacity());// Now (16*2)+2=34
}
}
SETCHARAT() METHOD
Syntax:
Buffer_Name.setCharAt(index_value,character);

import java.io.*;
class Main
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("JAVA");
sb.setCharAt(2,'H');
System.out.println(sb); Output
}
JAHA
}
INSERT() METHOD
 The insert() method inserts the given string with this string at the given
position.

 Syntax:
Buffer_Name.insert(start_ index,String);

 Example:
import java.io.*;
class A
Output
{
public static void main(String args[]) Hello Java
{
StringBuffer sb = new StringBuffer(“ Java");
sb.insert(0, “Hello");
System.out.println(sb);
}
}
DELETE() METHOD
 The deletes the string from the specified begin Index to endIndex-1.

 Syntax:

Buffer_Name.delete(start_ index,end_index);

Example:

import java.io.*;
class Main Output
{
public static void main(String args[]) Hlo
{
StringBuffer sb = new StringBuffer("Hello");
sb.delete(1, 3);
System.out.println(sb);
}
}
REVERSE() METHOD
 The reverse() method used to reverses the string.

 Syntax:
Buffer_Name.reverse ();

import java.io.* ;
class Main
Output
{
public static void main(String args[]) olleH
{
StringBuffer sb = new StringBuffer("Hello");
System.out.println(sb.reverse());
}
}
REPLACE() METHOD
 The replace() method used to replace given string from specified
starting index and ending Index-1.

 Syntax:
Buffer_Name.replace (start_index,end_index,string);
 Example:
import java.io.*;
class A
{
public static void main(String args[])
{
StringBuffer sb = new StringBuffer("Hello");
sb.replace(1, 3, "Java");
System.out.println(sb);
}
}
sb.replace(0,5,"HAI");
import java.lang.*; System.out.println(sb);
class Main
{ sb.delete(0,3);
public static void main(String args[]) System.out.println(sb);
{
StringBuffer sb=new StringBuffer("HELLO "); sb.reverse();
System.out.println(sb);
System.out.println(sb.length());
sb.reverse();
System.out.println(sb.capacity()); System.out.println(sb);
}}
System.out.println(sb);
OUTPUT
sb.append(" JAVA"); 6
22
System.out.println(sb);
HELLO
HELLO JAVA
sb.insert(6,"PROGRAMMING"); HELLO PROGRAMMING JAVA
System.out.println(sb); HAI PROGRAMMING JAVA
PROGRAMMING JAVA
AVAJ GNIMMARGORP
PROGRAMMING JAVA

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy