Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Strings in Java

Uploaded by

Kanika Bedi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Strings in Java

Uploaded by

Kanika Bedi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Strings in Java - Overview

A String in Java is a sequence of characters. In Java, strings are


objects, and they are instances of the String class. Unlike some
other programming languages, Java does not have a primitive
type for strings. Instead, strings are handled using the String
class, which comes with many built-in methods for
manipulating string data. The String class is available in java.lang
package.
Basic Concepts
1. String Declaration
o A string is declared using the String keyword.
String str = "Hello, World!";
2. String Literals and String Objects
o String literals are enclosed in double quotes (e.g.,
"Hello").
o String objects are instances of the String class, and
you can create them using the new keyword, but it is
not commonly done in simple programs.
o Example of creating a String object using the new
keyword:
String str = new String("Hello");
3. Immutability of Strings
o Strings in Java are immutable, which means once a
string is created, it cannot be changed. Any
modification creates a new string object.
4. Memory Efficiency
o Java uses a special memory area called the String
Pool to store string literals. If the same string literal is
used multiple times, Java refers to the string from the
pool, making it more memory-efficient.
String Methods in Java
The String class provides various built-in methods to manipulate
strings. Method names start with lowercase and then the
second word starts with uppercase letters. Eg: indexOf();
Some of the commonly used methods are:
1. Length of a String
o The length() method returns the number of
characters in a string.
o Example:
String str = "Hello";
int len = str.length(); // len will be 5
2. Concatenation of Strings
o You can concatenate (combine) two strings using the
+ operator or the concat() method.
o Example:
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2; // result = "Hello World"
Example : -
public class ConcatExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = " World";

// Using concat() method


String result = str1.concat(str2);

System.out.println(result); // Output: Hello World


}
3. Substring Extraction
o The substring() method is used to extract a part of a
string.
o Example:
String str = "Hello, World!";
String sub = str.substring(0, 5); // sub = "Hello"
4. Character Access
o The charAt() method returns the character at a
specified index in the string.
o Example:
String str = "Hello";
char ch = str.charAt(1); // ch = 'e'
5. String Comparison
o The equals() method compares the content of two
strings.
o The compareTo() method compares two strings
lexicographically.
o Example:
String str1 = "Hello";
String str2 = "hello";
boolean isEqual = str1.equals(str2); // returns false
int comparison = str1.compareTo(str2); // returns a negative
value (since 'H' < 'h')
6. Converting Case
o The toUpperCase() and toLowerCase() methods
convert all characters in the string to uppercase or
lowercase.
o Example:
String str = "Hello";
String upperStr = str.toUpperCase(); // "HELLO"
String lowerStr = str.toLowerCase(); // "hello"
7. Trimming Whitespace
o The trim() method removes leading and trailing
whitespace from a string.
o Example:
String str = " Hello World! ";
String trimmedStr = str.trim(); // "Hello World!"
8. Replacing Characters
o The replace() method is used to replace a character or
a substring with another.
o Example:
String str = "Hello, World!";
String newStr = str.replace("World", "Java"); // "Hello, Java!"
9. String Index Of
o The indexOf() method returns the index of the first
occurrence of a character or substring.
o Example:
String str = "Hello,World!";
int index = str.indexOf("World"); // index = 7
10. String Split
o The split() method splits a string into an array of
substrings based on a given delimiter.
o Example:
String str = "apple,banana,orange";
String[] fruits = str.split(","); // fruits = ["apple", "banana",
"orange"]
Common String Operations
1. String Conversion to Other Data Types
o Strings can be converted to other types (e.g., integers
or floating-point numbers) using methods like
Integer.parseInt(), Double.parseDouble(), etc.
o Example:
String numStr = "123";
int num = Integer.parseInt(numStr); // num = 123
2. String to StringBuffer/StringBuilder
o The StringBuffer or StringBuilder classes are used
when you need to perform frequent string
manipulations (e.g., append, insert, delete).
o Example:
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // sb = "Hello World"
String Exercises
Here are a few exercises that you might encounter in ICSE:
1. Reverse a String
o Write a Java program to reverse a given string.
java
Copy code
String str = "Hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed); // Output: "olleH"
2. Count Vowels in a String
o Write a Java program to count the number of vowels
in a given string.
String str = "Hello World";
int count = 0;
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
}
}
System.out.println("Vowel count: " + count);
3. Palindrome Check
o Write a program to check if a string is a palindrome
(i.e., reads the same forward and backward).
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
if (str.equals(reversed)) {
System.out.println(str + " is a palindrome");
} else {
System.out.println(str + " is not a palindrome");
}
Conclusion
Understanding strings in Java is crucial as they are used in
almost all Java programs. From basic operations like
concatenation and comparison to more advanced
manipulations, mastering string handling is an essential skill.
The Java String class provides many useful methods to perform
a variety of string operations, making it a versatile tool for any
Java programmer.
These topics, including the use of String methods and common
exercises, should provide a solid foundation for ICSE students to
tackle string-related problems in Java.

In Java, StringBuffer and StringBuilder are both classes used to


manipulate strings, particularly when there is a need for
mutable sequences of characters. Here’s a breakdown of the
differences, similarities, and typical use cases for each:
1. StringBuffer
 Thread-Safe: Methods in StringBuffer are synchronized,
making it thread-safe. This means multiple threads can
access it without causing data inconsistency. However, this
synchronization introduces a slight performance overhead.
 Performance: Slightly slower than StringBuilder because of
the synchronized methods.
 Use Case: Best suited for applications where threads may
access the same string buffer (e.g., in multithreaded
environments).
StringBuffer buffer = new StringBuffer("Hello");
buffer.append(" World!");
System.out.println(buffer); // Output: Hello World!

2. StringBuilder
 Not Thread-Safe: Methods in StringBuilder are not
synchronized, so it’s not thread-safe. This makes it faster
than StringBuffer but means it should not be used where
multiple threads might access it simultaneously.
 Performance: Generally faster than StringBuffer because
there is no synchronization overhead.
 Use Case: Ideal for single-threaded applications or where
thread safety is not a concern.
StringBuilder builder = new StringBuilder("Hello");
builder.append(" World!");
System.out.println(builder); // Output: Hello World!
3. Similarities between StringBuffer and StringBuilder
 Mutability: Both StringBuffer and StringBuilder are
mutable, meaning you can change their contents without
creating new objects (unlike String, which is immutable).
 Methods: Both classes have similar methods, such as
append(), insert(), delete(), reverse(), and replace().
 Initial Capacity: Both classes have an initial capacity of 16
characters (unless specified), and they automatically
expand as needed.
4. When to Use Which
 Use StringBuffer if:
o Your application is multithreaded.
o You require thread-safe operations on strings.
 Use StringBuilder if:
o You’re working in a single-threaded environment or
don’t require thread safety.
o You need faster performance for frequent string
manipulations.
Example Comparison
Here’s a simple performance comparison:
public class StringBufferBuilderDemo {
public static void main(String[] args) {
int n = 100000;

// StringBuilder
long startTime = System.nanoTime();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < n; i++) {
builder.append("a");
}
long endTime = System.nanoTime();
System.out.println("Time taken by StringBuilder: " +
(endTime - startTime) + " ns");
// StringBuffer
startTime = System.nanoTime();
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < n; i++) {
buffer.append("a");
}
endTime = System.nanoTime();
System.out.println("Time taken by StringBuffer: " +
(endTime - startTime) + " ns");
}
}
In general, for most cases in single-threaded applications,
StringBuilder is preferred due to its better performance.

You might also like