0% found this document useful (0 votes)
3 views5 pages

Java String

Uploaded by

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

Java String

Uploaded by

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

Java Strings Tutorial

October 2025

A comprehensive guide to working with strings in Java

1 Introduction to Strings
In Java, a string is a sequence of characters used to represent text. Strings are objects
of the String class, part of the java.lang package, and are immutable (cannot be
changed once created).

2 Creating Strings
Strings can be created in multiple ways:
• Using String Literal (stored in the string pool for memory efficiency):
1 String str1 = " Hello , World ! " ;

• Using new Keyword (creates a new object in heap memory):


1 String str2 = new String ( " Hello , World ! " ) ;

• From a Character Array:


1 char [] charArray = { ’J ’ , ’a ’ , ’v ’ , ’a ’ };
2 String str3 = new String ( charArray ) ; // " Java "

Note: String literals are preferred for efficiency, as they reuse instances from the string
pool.

3 String Immutability
Strings are immutable in Java, meaning their content cannot be modified after creation.
Operations that appear to modify a string create a new string.
Example:
1 String str = " Hello " ;
2 str = str . concat ( " World " ) ; // Creates a new string
3 System . out . println ( str ) ; // Output : Hello World

1
Java Strings Tutorial 2

4 Common String Methods


The String class provides a variety of methods for manipulating strings. Below are some
commonly used methods:

Method Description Example


length() Returns the length of the string "Hello".length() → 5
charAt(int Returns the character at the spec- "Hello".charAt(1) → ’e’
index) ified index
substring(int Returns a substring "Hello".substring(1, 3)
begin, int → "el"
end)
toLowerCase() Converts to lower/upper case "Hello".toUpperCase()
/ → "HELLO"
toUpperCase()
trim() Removes leading/trailing whites- " Hi ".trim() → "Hi"
pace
replace(char Replaces all occurrences of a char- "Hello".replace(’l’,
old, char acter ’p’) → "Heppo"
new)
Checks if string contains a sub-
contains(CharSequence "Hello".contains("ell")
s) string → true
equals(Object Compares strings for equality "Hello".equals("hello")
obj) → false
Case-insensitive comparison
equalsIgnoreCase(String "Hello".equalsIgnoreCase("hello")
str) → true
Checks if string starts with prefix
startsWith(String "Hello".startsWith("He")
prefix) → true
endsWith(String Checks if string ends with suffix "Hello".endsWith("lo")
suffix) → true
indexOf(String Returns index of first occurrence "Hello".indexOf("l") →
str) of substring 2
split(String Splits string into an array based "a,b,c".split(",") →
regex) on regex ["a", "b", "c"]

Table 1: Common String Methods

5 Example Program
Below is a sample Java program demonstrating string operations:
1 public class StringExample {
2 public static void main ( String [] args ) {
3 String str = " Hello , Java ! " ;
4

5 // Basic operations
6 System . out . println ( " Original : " + str ) ;
7 System . out . println ( " Length : " + str . length () ) ; // 15
Java Strings Tutorial 3

8 System . out . println ( " Trimmed : " + str . trim () ) ; // " Hello ,
Java !"
9 System . out . println ( " Uppercase : " + str . toUpperCase () ) ;
// " HELLO , JAVA ! "
10 System . out . println ( " Substring : " + str . substring (2 , 7) ) ;
// " Hello "
11

12 // Searching and replacing


13 System . out . println ( " Contains ’ Java ’: " +
str . contains ( " Java " ) ) ; // true
14 System . out . println ( " Replace ’ Java ’ with ’ World ’: " +
str . replace ( " Java " , " World " ) ) ; // " Hello , World ! "
15

16 // Splitting
17 String [] words = str . trim () . split ( " ," ) ;
18 System . out . println ( " Split result : " ) ;
19 for ( String word : words ) {
20 System . out . println ( word ) ; // " Hello " , " Java !"
21 }
22 }
23 }

6 StringBuilder and StringBuffer


For heavy string manipulations, use StringBuilder (non-thread-safe, faster) or StringBuffer
(thread-safe, slower).
Example:
1 StringBuilder sb = new StringBuilder ( " Hello " ) ;
2 sb . append ( " World " ) ; // Modifies StringBuilder
3 System . out . println ( sb . toString () ) ; // " Hello World "

7 String Concatenation
Strings can be concatenated using:
• The + operator: String result = "Hello" + " World";
• The concat() method: String result = "Hello".concat(" World");
• For performance in loops, use StringBuilder:
Example:
1 StringBuilder sb = new StringBuilder () ;
2 for ( int i = 0; i < 5; i ++) {
3 sb . append ( i ) ;
4 }
5 System . out . println ( sb . toString () ) ; // "01234"
Java Strings Tutorial 4

8 String Comparison
• Use equals() for content comparison.
• Use == for reference comparison.
• Use compareTo() for lexicographical comparison.
Example:
1 String s1 = " Hello " ;
2 String s2 = new String ( " Hello " ) ;
3 System . out . println ( s1 . equals ( s2 ) ) ; // true ( same content )
4 System . out . println ( s1 == s2 ) ; // false ( different objects )
5 System . out . println ( s1 . compareTo ( " hello " ) ) ; // negative
( case - sensitive )

9 String Pool
Java maintains a string pool to optimize memory. String literals are stored in the pool,
and identical literals reuse the same object.
Example:
1 String s1 = " Hello " ;
2 String s2 = " Hello " ;
3 System . out . println ( s1 == s2 ) ; // true ( same string pool
reference )

10 Common Use Cases


• Input Validation:
1 String input = " test@example . com " ;
2 if ( input . trim () . contains ( " @ " ) ) {
3 System . out . println ( " Valid email format " ) ;
4 }

• Parsing:
1 String data = " John ,25 , Developer " ;
2 String [] parts = data . split ( " ," ) ;
3 System . out . println ( " Name : " + parts [0] + " , Age : " +
parts [1]) ; // Name : John , Age : 25

11 Best Practices
• Use string literals over new String() for efficiency.
• Use StringBuilder for dynamic string building in loops.
Java Strings Tutorial 5

• Avoid null strings to prevent NullPointerException.


• Use equals() or equalsIgnoreCase() for comparisons, not ==.

Conclusion
This tutorial covers the essentials of working with strings in Java, including creation,
manipulation, and best practices. For further exploration, consider advanced topics like
regular expressions or performance optimization with strings.

Created on October 2025

You might also like