String Class and Creation of String in Java
In Java, the String class is used to create and manipulate strings. A string represents a sequence of characters and is widely used in Java programs.
Definition of String
A string in Java is an object that represents a sequence of character values. Java provides the String class to handle text data easily.
Java also has the primitive type char for single characters, but for storing multiple characters (like names), the String class is used.
Ways to Create String in Java
There are two ways to create a String object:
- Using String Literal
- Using new keyword
1. Using String Literal
A string literal is created using double quotes. The string is stored in a special memory area called the String Constant Pool in the heap.
String s1 = "Hello";
String str1 = "Scaler";
String str2 = "Scaler"; // no new object created
2. Using new Keyword
When a string is created using the new keyword, a new object is always created in heap memory, outside the string constant pool.
String stringName = new String("value");
String s2 = new String("Program");
Example Program
class TestString {
public static void main(String[] args) {
String s1 = "Personal"; // literal
String s2 = new String("Computer"); // new keyword
String s3 = s1 + s2; // concatenation
System.out.println(s3);
}
}
StringBuffer Class in Java
The StringBuffer class in Java is used to create mutable (modifiable) string objects. Unlike the String class, the content of a StringBuffer object can be changed without creating a new object, which makes it memory efficient.
Definition
The StringBuffer class is used for storing a mutable sequence of characters and allows efficient modification of strings. It provides methods for appending, deleting, and updating the sequence.
Why StringBuffer is Needed
In the String class, whenever we modify a string, a new object is created, which causes memory wastage. But in StringBuffer, the original object is modified without allocating new memory. This property is called mutability.
Syntax
StringBuffer objectName = new StringBuffer();
- Mutable (can be modified)
- Memory efficient
- Stored in heap memory
- Faster than String for frequent modifications
- Provides many built-in methods
Common Methods of StringBuffer
1. append() Method
Used to add data at the end of the existing sequence.
SyntaxStringBuffer.append(data);
Example
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World");
System.out.println(sb);
2. capacity() Method
Returns the current capacity of the StringBuffer object. Default capacity is 16 bytes.
Syntaxint capacity();
3. Other Useful Operations
StringBuffer also supports insert(), delete(), replace(), and reverse(), which help in efficient string manipulation.
Example Program
class TestBuffer {
public static void main(String[] args) {
StringBuffer sb = new StringBuffer("Java");
sb.append(" Programming");
System.out.println(sb);
}
}
Various String Methods for String and StringBuffer Class
Java provides many built-in methods in the String and StringBuffer classes to manipulate character data such as comparing, searching, modifying, and formatting strings.
The String class provides methods to operate on immutable strings.
boolean equals(Object another)
Example
String s1 = "Sachin";
String s2 = "Sachin";
System.out.println(s1.equals(s2));
Compares the contents of two strings.
boolean equalsIgnoreCase(String another)
Example
String s1 = "Ram";
String s2 = "rAm";
System.out.println(s1.equalsIgnoreCase(s2));
Compares strings ignoring case.
int compareTo(String str)
Example
String s1 = "Sachin";
String s2 = "Sachin";
System.out.println(s1.compareTo(s2));
Returns 0 if equal, positive if greater, negative if smaller.
int length()
Example
String s = "Sachin";
System.out.println(s.length());
Returns number of characters.
char charAt(int index)
Example
String s = "Sachin";
System.out.println(s.charAt(0));
Returns character at given index.
String toUpperCase()
String toLowerCase()
Example
String s = "Sachin";
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
Converts the string to all uppercase or all lowercase.
String trim()
Example
String s = " Sachin ";
System.out.println(s.trim());
Removes leading and trailing spaces.
String substring(int start, int end)
Example
String s = "SachinTendulkar";
System.out.println(s.substring(0, 6));
Extracts part of string.
String concat(String another)
Example
String s1 = "Sachin ";
String s2 = "Tendulkar";
System.out.println(s1.concat(s2));
Joins two strings.
StringBuffer is mutable and efficient for frequent modifications.
StringBuffer append(data)
Example
StringBuffer sb = new StringBuffer("Hello");
sb.append(" Java");
System.out.println(sb);
Adds data at the end.
StringBuffer insert(int index, data)
Example
StringBuffer sb = new StringBuffer("Hello");
sb.insert(5, " World");
System.out.println(sb);
Inserts data at specified position.
StringBuffer delete(int start, int end)
Example
StringBuffer sb = new StringBuffer("Hello World");
sb.delete(5, 11);
System.out.println(sb);
Removes characters from range.
StringBuffer replace(int start, int end, String str)
Example
StringBuffer sb = new StringBuffer("Hello World");
sb.replace(6, 11, "Java");
System.out.println(sb);
Replaces characters from start to end with the given string.
StringBuffer reverse()
Example
StringBuffer sb = new StringBuffer("Java");
sb.reverse();
System.out.println(sb);
Reverses the character sequence of the StringBuffer.
int capacity()
Example
StringBuffer sb = new StringBuffer();
System.out.println(sb.capacity());
Default capacity is 16 bytes.
Exception Handling in Java
Exception handling in Java is a powerful mechanism used to handle runtime errors so that the normal flow of the program can be maintained. An exception is an abnormal condition that disrupts program execution.
What is Exception Handling?
Exception handling is the process of handling runtime errors such as ArithmeticException, IOException, etc., to prevent program termination and allow the remaining code to execute normally.
Keywords Used in Exception Handling
Java provides five main keywords:
trycatchfinallythrowthrows
The try block is used to enclose the code that may generate an exception. It must be followed by either catch or finally.
Syntaxtry {
// code that may throw exception
}
Example
try {
int a = 10 / 0;
}
The catch block is used to handle the exception generated in the try block. It must be placed immediately after the try block.
Syntaxcatch(ExceptionType e) {
// handling code
}
Example
catch(ArithmeticException e) {
System.out.println("Exception handled");
}
Important Points: Multiple catch blocks are allowed. Only one catch block executes at a time.
The finally block is used to execute important code such as closing files or releasing resources. It executes whether an exception occurs or not.
Syntaxfinally {
// cleanup code
}
Example
finally {
System.out.println("Always executed");
}
The throw keyword is used to explicitly throw an exception by the programmer. It is mainly used to create custom exceptions.
Syntaxthrow new ExceptionType("message");
Example
if(age < 18) {
throw new ArithmeticException("Not eligible");
}
The throws keyword is used in the method declaration to declare that a method may throw exceptions. It informs the caller about possible exceptions.
SyntaxreturnType methodName() throws ExceptionType
Example
void readFile() throws IOException {
// code
}
Simple Program Using Exception Handling Keywords
class ExceptionDemo {
static void checkAge(int age) throws ArithmeticException {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
} else {
System.out.println("Eligible to vote");
}
}
public static void main(String[] args) {
try {
checkAge(16);
}
catch (ArithmeticException e) {
System.out.println("Caught Exception: " + e.getMessage());
}
finally {
System.out.println("Program finished");
}
}
}
Program finished