JAVA STRINGS
Even though String is a class, it is often used as if it were a data type:
String s;
Here, s is a variable of data type String.
Is String a Class or Data Type?
• String is a class in java.lang.
• In Java, all classes are also considered data types.
• So, String can be treated both as a class and a data type.
• A class is also called a user-defined data type.
Java Classes
String,
StringBuffer, and
StringBuilder
Creating Strings
There are three ways to create strings in Java:
•By assignment (literal)
String s1 = "Hello";
•By new operator
String s2 = new String("Hello");
•From a character array
char arr[] = {'c','h','a','i','r','s'};
Create a String object by passing the array name to it, as:
String s3 = new String(arr); //”chairs”
String s3 = new String(arr, 2, 3); // "air"
String Class Methods
• String concat(): Joins two strings and returns a new string.
String s1 = "Hello"; String s2 = “Java";
String s3 = s1.concat(s2); // “HelloJava”
The same can also be done using + operator: s1 + s2;
• int length(): Returns number of characters in the string.
s1.length(); "Hello".length() → 5
• char charAt(int i) : Returns character at given index.
s1.charAt(3); "Hello". charAt(3) → l
• int compareTo(String s): Lexicographic comparison (Case-sensitive)
Returns: 0 if equal positive if greater negative if smaller
s1. compareTo(s2); //“Apple”.compareTo(“Ball”);
• int compareToIgnoreCase(String s): Same as above, but ignores case.
String Class Methods
• boolean equals(String s): Checks if two strings have same content. Case-
sensitive.
"abc".equals("abc") → true
"abc".equals(“ABC") →false
• boolean equalsIgnoreCase(String s) : Same as above, but ignores case.
"abc".equals(“ABC") → true
• boolean startsWith(String s) : Checks if string begins with substring s
• boolean endsWith(String s): Checks if string ends with given substring s.
• int indexOf(String s) : Finds first occurrence of substring. Returns index
or -1.
s1=“This is Book” ; s2=“is”; int n=s1.indexOf(s2); //n=2
• int lastIndexOf(String s) : Finds last occurrence of substring.
String Class Methods
• String replace(char old, char new) : Replaces all occurrences of a character.
"Hello".replace('l','x'); // Hexxo
• String substring(int i): Returns substring from index i to end.
"Programming".substring(3) → 'gramming'
• String substring(int i, int j): Returns substring from i to j-1.
"Programming".substring(3,7) → 'gram'
• String toLowerCase() / String toUpperCase(): Converts case of all characters.
• String trim() : Removes leading and trailing spaces.
• void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) :Copies
characters from string to character array.
• String[] split(String delimiter) : Splits a string into multiple pieces at
delimiter, returns array.
String Class Example
public class StringExample
{
public static void main(String[] args)
{
String s = "Hello World";
System.out.println("Length: " + s.length());
System.out.println("CharAt(4): " + s.charAt(4));
System.out.println("Substring: " + s.substring(0,5));
System.out.println("Upper: " + s.toUpperCase());
}
}
String Class Overview
• = = compares references (memory addresses).
• equals() and compareTo() can be used in String comparison.
• String objects are immutable (cannot be modified).
• Any modification creates a new object.
• Strings are stored in String Constant Pool.
• String Constant Pool is a separate block of memory where the string
objects are held by JVM. If a string object is created directly using
assignment operator as: String s1=“Hello”, then it is stored in string
constant pool.
//String comparison using
class Strcompare
{
public static void main(String args[])
{
String sl= "Hello";
String s2= new String("Hello");
if(s1= = s2)
System.out.println("Both are same");
else
System.out.println("Not same");
}
Output: Not same
//String comparison using
class Strcompare
{
public static void main(String args[])
{
String sl = "Hello";
String s2 = "Hello";
if(s1= = s2)
System.out.println("Both are same");
else
System.out.println("Not same");
}
Output: Both are same
STRINGBUFFER CLASS
StringBuffer Overview
• Unlike String, StringBuffer objects are mutable.(Can be modified after
creation)
• Located in java.lang.
• Provides methods to modify string data directly.
Creating StringBuffer
• StringBuffer sb = new StringBuffer("Hello");
• StringBuffer sb2 = new StringBuffer(); // empty, default capacity 16
• StringBuffer sb3 = new StringBuffer(50); // capacity 50
StringBuffer Methods
StringBuffer append(x) → adds content at end
StringBuffer sb= new StringBuffer("Hello"); sb.append(" World") → 'Hello World'
StringBuffer insert(i, x) → inserts at position
sb.insert(5, " Java") → “Hello Java World”
StringBuffer delete(i, j) → deletes substring
StringBuffer replace(i, j, str) → replaces part with new string
StringBuffer reverse() → reverses sequence
int capacity() → current capacity
int ensureCapacity(n) → increases capacity if needed
int length() → number of characters
int indexOf(), int lastIndexOf(): Finds first, last occurrence of substring
StringBuffer substring(i, j) → extracts substring
StringBuffer Example
public class StringBufferExample
{
public static void main(String[] args)
{
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb);
sb.insert(5, " Java");
System.out.println(sb);
sb.reverse();
System.out.println(sb);
}
}
STRINGBUILDER CLASS
StringBuilder Overview
• Introduced in Java 5 (jdk1.5).
• Mutable: Similar to StringBuffer.
• Same as StringBuffer, but not synchronized.
• Faster performance.
• Suitable for single-threaded programs.
• Methods are same as StringBuffer.
StringBuilder Methods
• append(): new StringBuilder("Hi").append(" Java") → 'Hi Java'
• insert(): sb.insert(2, "Code")
• delete(): sb.delete(1,3)
• reverse(): sb.reverse()
StringBuilder Example
public class StringBuilderExample
{
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder("Hi");
sb.append(" Java");
System.out.println(sb);
sb.insert(2, "Code");
System.out.println(sb);
sb.reverse();
System.out.println(sb);
}
}
Comparison:
String vs StringBuffer vs StringBuilder
• String → Immutable, stored in String Pool
• StringBuffer → Mutable, Thread-safe (synchronized)
• StringBuilder → Mutable, Faster, Not thread-safe
• Use String when immutability is required.
• Use StringBuffer for multi-threaded applications.
• Use StringBuilder for single-threaded performance.
Comparison:
String vs StringBuffer vs StringBuilder
Conclusion
Strings are most often used in data transfer.
String class is immutable for security and sharing.
StringBuffer & StringBuilder are mutable for efficient
modifications.
• Use StringBuffer for multi-threaded safety, StringBuilder for
performance.