0% found this document useful (0 votes)
0 views9 pages

Basic String class

NOTES

Uploaded by

akileshwari R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views9 pages

Basic String class

NOTES

Uploaded by

akileshwari R
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Basic String class

 Strings, which are widely used in Java programming, are a sequence of characters. In Java programming
language, strings are treated as objects.
 The Java platform provides the String class to create and manipulate strings.

Creating Strings

String greeting = "Hello world!";

 Whenever it encounters a string literal in your code, the compiler creates a String object with its value
in this case, "Hello world!".
 As with any other object, you can create String objects by using the new keyword and a constructor.
 The String class has 11 constructors that allow you to provide the initial value of the string using
different sources, such as an array of characters.

Example to Create Strings in Java

public class StringDemo {


public static void main(String args[]) {
char[] h= { 'h', 'e', 'l', 'l', 'o', '.' };
String helloStr = new String(h);
System.out.println( helloStr );
}}
Output
hello.

 Note − The String class is immutable, so that once it is created a String object cannot be changed. If
there is a necessity to make a lot of modifications to Strings of characters, then you should use String
Buffer & String Builder Classes.

String Length

 Methods used to obtain information about an object are known as accessor methods. One accessor
method that you can use with strings is the length() method, which returns the number of characters
contained in the string object.
 The following program is an example of length(), method String class.

public class StringDemo {


public static void main(String args[]) {
String palind = "Dot saw I was Tod";
int len = palind.length();
System.out.println( "String Length is : " + len );
}}
Output
String Length is : 17
Concatenating Strings
The String class includes a method for concatenating two strings −
string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use the concat()
method with string literals, as in −
"My name is ".concat("Zara");

Strings are more commonly concatenated with the + operator, as in −


"Hello," + " world" + "!"
which results in − "Hello, world!"

Example to Concatenate Strings in Java


public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
Output
Dot saw I was Tod

Creating Format Strings


 You have printf() and format() methods to print output with formatted numbers. The String class has an
equivalent class method, format(), that returns a String object rather than a PrintStream object.
 Using String's static format() method allows you to create a formatted string that you can reuse, as
opposed to a one-time print statement. For example, instead of −

Example to Create Formatted Strings in Java


System.out.printf("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);

You can write −


String fs;
fs = String.format("The value of the float variable is " +
"%f, while the value of the integer " +
"variable is %d, and the string " +
"is %s", floatVar, intVar, stringVar);
System.out.println(fs);
Java String Class Methods

S.No. Method & Description

char charAt(int index)


1
This method returns the char value at the specified index.

int codePointAt(int index)


2
This method returns the character (Unicode code point) at the specified index.

int codePointBefore(int index)


3
This method returns the character (Unicode code point) before the specified index.

int codePointCount(int beginIndex, int endIndex)


4
This method returns the number of Unicode code points in the specified text range of this String.

int compareTo(String anotherString)


5
This method compares two strings lexicographically.

int compareToIgnoreCase(String str)


6
This method compares two strings lexicographically, ignoring case differences.

String concat(String str)


7
This method concatenates the specified string to the end of this string.

boolean contains(CharSequence s)
8
This method ceturns true if and only if this string contains the specified sequence of char values.

boolean contentEquals(CharSequence cs)


9
This method compares this string to the specified CharSequence.

boolean contentEquals(StringBuffer sb)


10
This method compares this string to the specified StringBuffer.

static String copyValueOf(char[] data)


11
This method returns a String that represents the character sequence in the array specified.

static String copyValueOf(char[] data, int offset, int count)


12
This method returns a String that represents the character sequence in the array specified.

boolean endsWith(String suffix)


13
This method tests if this string ends with the specified suffix.

boolean equals(Object anObject)


14
This method compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)


15
This method compares this String to another String, ignoring case considerations.
static String format(Locale l, String format, Object... args)
16
This method returns a formatted string using the specified locale, format string, and arguments.

static String format(String format, Object... args)


17
This method returns a formatted string using the specified format string and arguments.

byte[] getBytes()
18 This method encodes this String into a sequence of bytes using the platform's default charset,
storing the result into a new byte array.

byte[] getBytes(Charset charset)


19 This method encodes this String into a sequence of bytes using the given charset, storing the
result into a new byte array.

byte[] getBytes(String charsetName)


20 This method encodes this String into a sequence of bytes using the named charset, storing the
result into a new byte array.

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)


21
This method copies characters from this string into the destination character array.

int hashCode()
22
This method returns a hash code for this string.

int indexOf(int ch)


23
This method returns the index within this string of the first occurrence of the specified character.

int indexOf(int ch, int fromIndex)


24 This method returns the index within this string of the first occurrence of the specified character,
starting the search at the specified index.

int indexOf(String str)


25
This method returns the index within this string of the first occurrence of the specified substring.

int indexOf(String str, int fromIndex)


26 This method returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.

String intern()
27
This method returns a canonical representation for the string object.

boolean isEmpty()
28
This method returns true if, and only if, length() is 0.

int lastIndexOf(int ch)


29
This method returns the index within this string of the last occurrence of the specified character.

30 int lastIndexOf(int ch, int fromIndex)


This method returns the index within this string of the last occurrence of the specified character,
searching backward starting at the specified index.

int lastIndexOf(String str)


31 This method returns the index within this string of the rightmost occurrence of the specified
substring.

int lastIndexOf(String str, int fromIndex)


32 This method returns the index within this string of the last occurrence of the specified substring,
searching backward starting at the specified index.

int length()
33
This method returns the length of this string.

boolean matches(String regex)


34
This method tells whether or not this string matches the given regular expression.

int offsetByCodePoints(int index, int codePointOffset)


35 This method returns the index within this String that is offset from the given index by
codePointOffset code points.

boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
36
This method tests if two string regions are equal with case ignored.

boolean regionMatches(int toffset, String other, int ooffset, int len)


37
This method tests if two string regions are equal.

String replace(char oldChar, char newChar)


38 This method returns a new string resulting from replacing all occurrences of oldChar in this
string with newChar.

String replace(CharSequence target, CharSequence replacement)


39 This method replaces each substring of this string that matches the literal target sequence with
the specified literal replacement sequence.

String replaceAll(String regex, String replacement)


40 This method replaces each substring of this string that matches the given regular expression
with the given replacement.

String replaceFirst(String regex, String replacement)


41 This method replaces the first substring of this string that matches the given regular expression
with the given replacement.

String[] split(String regex)


42
This method splits this string around matches of the given regular expression.

String[] split(String regex, int limit)


43
This method splits this string around matches of the given regular expression.
boolean startsWith(String prefix)
44
This method tests if this string starts with the specified prefix.

boolean startsWith(String prefix, int toffset)


45 This method tests if the substring of this string beginning at the specified index starts with the
specified prefix.

CharSequence subSequence(int beginIndex, int endIndex)


46
This method returns a new character sequence that is a subsequence of this sequence.

String substring(int beginIndex)


47
This method returns a new string that is a substring of this string.

String substring(int beginIndex, int endIndex)


48
This method returns a new string that is a substring of this string.

char[] toCharArray()
49
This method converts this string to a new character array.

String toLowerCase()
50 This method converts all of the characters in this String to lower case using the rules of the
default locale.

String toLowerCase(Locale locale)


51 This method converts all of the characters in this String to lower case using the rules of the given
Locale.

String toString()
52
This method returns the string itself.

String toUpperCase()
53 This method converts all of the characters in this String to upper case using the rules of the
default locale.

String toUpperCase(Locale locale)


54 This method converts all of the characters in this String to upper case using the rules of the given
Locale.

String trim()
55
This method returns a copy of the string, with leading and trailing whitespace omitted.

static String valueOf(boolean b)


56
This method returns the string representation of the boolean argument.

static String valueOf(char c)


57
This method returns the string representation of the char argument.

58 static String valueOf(char[] data)


This method returns the string representation of the char array argument.

static String valueOf(char[] data, int offset, int count)


59
This method Returns the string representation of a specific subarray of the char array argument.

static String valueOf(double d)


60
This method returns the string representation of the double argument.

static String valueOf(float f)


61
This method returns the string representation of the float argument.

static String valueOf(int i)


62
This method returns the string representation of the int argument.

static String valueOf(long l)


63
This method returns the string representation of the long argument.

static String valueOf(Object obj)


64
This method returns the string representation of the Object argument.

String Buffer Class

 The Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class
in Java is the same as the String class except it is mutable, i.e., it can be changed.
 Note: Java StringBuffer class is thread-safe, i.e., multiple threads cannot access it simultaneously. So, it
is safe and will result in an order.

Methods of the StringBuffer class

Modifier and Type Method Description

public synchronized append(String s) It is used to append the specified string to this


StringBuffer string. The append() method is overloaded like
append(char), append(boolean), append(int),
append(float), append(double), etc.

public synchronized insert(int offset, String s) It is used to insert the specified string into this
StringBuffer string at the specified position. The insert()
method is overloaded like insert(int, char),
insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double), etc.

public synchronized replace(int startIndex, int It is used to replace the string from the
StringBuffer endIndex, String str) specified startIndex and endIndex.
public synchronized delete(int startIndex, int It is used to delete the string from the
StringBuffer endIndex) specified startIndex and endIndex.

public synchronized reverse() is used to reverse the string.


StringBuffer

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity is at least


minimumCapacity) equal to the given minimum.

public char charAt(int index) It is used to return the character at the


specified position.

public int length() It is used to return the length of the string, i.e.
total number of characters.

public String substring(int beginIndex) It is used to return the substring from the
specified beginIndex.

public String substring(int beginIndex, It is used to return the substring from the
int endIndex) specified beginIndex and endIndex.

What is a mutable String?


 A String that can be modified or changed is known as a mutable String. StringBuffer and StringBuilder
classes are used for creating mutable strings.

1) StringBuffer Class append() Method


 The append() method concatenates the given argument with this String.

class Main {
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
} }
Output:

Hello Java

2) StringBuffer insert() Method


The insert() method inserts the given String into this string at the given position.
class Main {
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
Output:

HJavaello

3) StringBuffer replace() Method


The replace() method replaces the given String from the specified beginIndex and endIndex.

class Main {
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
Output:

HJavalo

4) StringBuffer delete() Method


The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex.

class Main {
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
} }
Output:
Hlo
5) StringBuffer reverse() Method
The reverse() method of the StringBuffer class reverses the current String.
class Main {
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH } }
Output:

olleH

You might also like