Ugenz Academy/Tutorial

Strings

12 min read2,286 words

Reading progress

Keep learning

Java String

Introduction

A String in Java is a sequence of characters used to store text.

For example:

String name = "Anuradha"; String city = "Janakpur";

Java provides the String class in the java.lang package. Because java.lang is automatically imported, we do not need to write an import statement for String.

Creating a String

There are two common ways to create a String.

1. Using String Literal

String name = "Anuradha";

This is the most common way to create a String.

Example

public class StringExample { public static void main(String[] args) { String name = "Anuradha"; System.out.println(name); } }

Output

Anuradha

2. Using the new Keyword

String name = new String("Anuradha");

Example

public class StringExample { public static void main(String[] args) { String name = new String("Anuradha"); System.out.println(name); } }

Output

Anuradha

String Syntax

String variableName = "text";

Example:

String message = "Hello Java";

String is Immutable

Strings in Java are immutable.

This means that once a String object is created, its contents cannot be changed.

Example:

String name = "Anu"; name = name + " Mandal"; System.out.println(name);

Output

Anu Mandal

The original "Anu" String was not modified. A new String value was created and assigned to name.

String Length

The length() method returns the number of characters in a String.

Syntax

string.length();

Example

public class StringLength { public static void main(String[] args) { String name = "Anuradha"; System.out.println(name.length()); } }

Output

8

Accessing Characters

The charAt() method is used to access a character at a specific index.

Syntax

string.charAt(index);

Example:

String name = "Java"; System.out.println(name.charAt(0)); System.out.println(name.charAt(2));

Output

J v

String indexes start from 0.

String: J a v a Index: 0 1 2 3

String Concatenation

Concatenation means joining two or more Strings.

The + operator can be used to concatenate Strings.

Example

String firstName = "Anuradha"; String lastName = "Mandal"; String fullName = firstName + " " + lastName; System.out.println(fullName);

Output

Anuradha Mandal

concat() Method

The concat() method joins one String with another String.

Example

String firstName = "Hello "; String lastName = "Java"; String result = firstName.concat(lastName); System.out.println(result);

Output

Hello Java

Comparing Strings

Strings should generally be compared using equals() rather than ==.

Using equals()

String a = "Java"; String b = "Java"; System.out.println(a.equals(b));

Output

true

equals() compares the contents of the Strings.

Using equalsIgnoreCase()

This method compares Strings without considering uppercase and lowercase differences.

String a = "Java"; String b = "JAVA"; System.out.println(a.equalsIgnoreCase(b));

Output

true

== vs equals()

==equals()
Compares references for objectsCompares String contents
Used for reference identityUsed for logical equality
Not recommended for comparing String textRecommended for String content

Example:

String a = new String("Java"); String b = new String("Java"); System.out.println(a == b); System.out.println(a.equals(b));

Output:

false true

Converting Case

Java provides methods for converting a String to uppercase or lowercase.

toUpperCase()

String name = "java"; System.out.println(name.toUpperCase());

Output:

JAVA

toLowerCase()

String name = "JAVA"; System.out.println(name.toLowerCase());

Output:

java

Removing Extra Spaces

The trim() method removes leading and trailing whitespace.

String name = " Anuradha "; System.out.println(name.trim());

Output

Anuradha

For modern Java code, strip() is another option and handles Unicode whitespace more broadly:

String name = " Anuradha "; System.out.println(name.strip());

Checking the Beginning and End

startsWith()

Checks whether a String starts with a specified value.

String name = "Anuradha"; System.out.println(name.startsWith("Anu"));

Output:

true

endsWith()

Checks whether a String ends with a specified value.

String name = "Anuradha"; System.out.println(name.endsWith("dha"));

Output:

true

Searching in a String

contains()

Checks whether a String contains a specific sequence.

String message = "Welcome to Java"; System.out.println(message.contains("Java"));

Output:

true

indexOf()

Returns the index of the first occurrence of a character or String.

String text = "Hello Java"; System.out.println(text.indexOf("Java"));

Output:

6

If the value is not found, indexOf() returns -1.

lastIndexOf()

Returns the index of the last occurrence.

String text = "Java Java"; System.out.println(text.lastIndexOf("Java"));

Output:

5

Extracting Part of a String

The substring() method extracts part of a String.

Syntax

string.substring(startIndex);

Example:

String text = "Hello Java"; System.out.println(text.substring(6));

Output:

Java

You can also specify the ending index:

String text = "Hello Java"; System.out.println(text.substring(0, 5));

Output:

Hello

The ending index is exclusive.

Replacing Characters or Text

The replace() method replaces characters or sequences.

String text = "I like Java"; String result = text.replace("Java", "Python"); System.out.println(result);

Output:

I like Python

Replacing Using Regular Expressions

The replaceAll() method can replace text using a regular expression.

Example:

String text = "Java123"; String result = text.replaceAll("[0-9]", ""); System.out.println(result);

Output:

Java

Splitting a String

The split() method divides a String into an array.

Example:

String names = "Ram,Sita,Hari"; String[] result = names.split(","); for (String name : result) { System.out.println(name); }

Output:

Ram Sita Hari

Checking Empty Strings

isEmpty()

Returns true if the String has zero characters.

String text = ""; System.out.println(text.isEmpty());

Output:

true

isBlank()

Returns true if the String is empty or contains only whitespace.

String text = " "; System.out.println(text.isBlank());

Output:

true

Comparing Strings with compareTo()

The compareTo() method compares two Strings lexicographically.

String a = "Apple"; String b = "Banana"; System.out.println(a.compareTo(b));

A negative value means a comes before b.

Important: compareTo() does not necessarily return only -1, 0, or 1; it returns a negative, zero, or positive integer.

Converting Other Data Types to String

The String.valueOf() method can convert values into Strings.

int number = 100; String text = String.valueOf(number); System.out.println(text);

Output:

100

Another common method is:

String text = Integer.toString(100);

Converting String to Number

The Integer.parseInt() method converts a String into an integer.

String text = "100"; int number = Integer.parseInt(text); System.out.println(number + 50);

Output:

150

Other common conversions include:

double price = Double.parseDouble("99.50"); float value = Float.parseFloat("10.5"); long number = Long.parseLong("100000");

If the String does not contain a valid number, these parsing methods can throw NumberFormatException.

String and Character Array

A String can be converted into a character array using toCharArray().

String text = "Java"; char[] letters = text.toCharArray(); for (char letter : letters) { System.out.println(letter); }

Output:

J a v a

StringBuilder

StringBuilder is useful when we need to perform many modifications to text.

Unlike String, a StringBuilder object is mutable.

Example

public class StringBuilderExample { public static void main(String[] args) { StringBuilder text = new StringBuilder("Hello"); text.append(" Java"); System.out.println(text); } }

Output

Hello Java

Common StringBuilder Methods

MethodPurpose
append()Adds text
insert()Inserts text
delete()Deletes characters
replace()Replaces characters
reverse()Reverses the text
length()Returns length

Example

StringBuilder text = new StringBuilder("Java"); text.append(" Programming"); System.out.println(text); text.reverse(); System.out.println(text);

StringBuffer

StringBuffer is similar to StringBuilder, but its methods are synchronized.

It can be useful when multiple threads need synchronized access to the same mutable character sequence.

For many single-threaded applications, StringBuilder is preferred because it generally has less synchronization overhead.

Example:

StringBuffer text = new StringBuffer("Hello"); text.append(" Java"); System.out.println(text);

Output:

Hello Java

String vs StringBuilder vs StringBuffer

FeatureStringStringBuilderStringBuffer
MutableNoYesYes
Can modify existing objectNoYesYes
Thread synchronizationNot applicableNoYes
Suitable for frequent modificationsLess suitableSuitableSuitable
Common useNormal textFrequently changing textThread-safe mutable text

String Pool

Java maintains a special area called the String Pool for String literals.

Example:

String a = "Java"; String b = "Java";

The JVM can reuse the same pooled String object for these identical literals.

However:

String c = new String("Java");

explicitly creates a distinct String object.

For comparing String contents, use:

a.equals(b)

rather than relying on ==.

Escape Characters in Strings

Escape sequences are used to represent special characters.

Escape SequenceMeaning
\nNew line
\tTab
\"Double quote
\'Single quote
\\Backslash
\rCarriage return
\bBackspace

Example

public class EscapeExample { public static void main(String[] args) { System.out.println("Hello\nJava"); System.out.println("Name:\tAnuradha"); System.out.println("\"Java Programming\""); } }

Output

Hello Java Name: Anuradha "Java Programming"

Taking String Input

The Scanner class can be used to take String input from the user.

next()

Reads one token.

Scanner sc = new Scanner(System.in); System.out.print("Enter your name: "); String name = sc.next(); System.out.println("Name = " + name);

If the user enters:

Anuradha Mandal

next() reads only:

Anuradha

nextLine()

Reads the complete line.

Scanner sc = new Scanner(System.in); System.out.print("Enter your full name: "); String name = sc.nextLine(); System.out.println("Name = " + name);

If the user enters:

Anuradha Mandal

the complete name is stored.

Important nextInt() and nextLine() Issue

When using nextInt() followed by nextLine(), the newline left by nextInt() can cause nextLine() to read an empty line.

Example:

Scanner sc = new Scanner(System.in); System.out.print("Enter age: "); int age = sc.nextInt(); sc.nextLine(); System.out.print("Enter name: "); String name = sc.nextLine(); System.out.println(name);

The extra:

sc.nextLine();

consumes the leftover newline.

Complete String Example

import java.util.Scanner; public class StringDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter your full name: "); String name = sc.nextLine(); System.out.print("Enter your city: "); String city = sc.nextLine(); System.out.println("\nStudent Information"); System.out.println("-------------------"); System.out.println("Name: " + name); System.out.println("City: " + city); System.out.println("Name Length: " + name.length()); System.out.println("Uppercase: " + name.toUpperCase()); sc.close(); } }

Example Output

Enter your full name: Anuradha Mandal Enter your city: Janakpur Student Information ------------------- Name: Anuradha Mandal City: Janakpur Name Length: 15 Uppercase: ANURADHA MANDAL

Common String Methods

MethodDescriptionExample
length()Returns number of characterstext.length()
charAt()Returns character at indextext.charAt(0)
equals()Compares contentsa.equals(b)
equalsIgnoreCase()Compares ignoring casea.equalsIgnoreCase(b)
toUpperCase()Converts to uppercasetext.toUpperCase()
toLowerCase()Converts to lowercasetext.toLowerCase()
trim()Removes leading/trailing whitespacetext.trim()
strip()Removes Unicode whitespacetext.strip()
contains()Checks for a sequencetext.contains("Java")
startsWith()Checks beginningtext.startsWith("Ja")
endsWith()Checks endingtext.endsWith("va")
indexOf()Finds first occurrencetext.indexOf("a")
lastIndexOf()Finds last occurrencetext.lastIndexOf("a")
substring()Extracts part of Stringtext.substring(2)
replace()Replaces texttext.replace("A", "B")
split()Splits into an arraytext.split(",")
isEmpty()Checks whether length is zerotext.isEmpty()
isBlank()Checks whether empty/whitespacetext.isBlank()
concat()Joins Stringsa.concat(b)
toCharArray()Converts to char[]text.toCharArray()

Advantages of String

  1. Easy to store and manipulate text.
  2. Provides many built-in methods.
  3. Strings are immutable, which helps with safe sharing of String values.
  4. String literals can be reused through the String Pool.
  5. Works easily with user input and output.
  6. Supports searching, comparing, replacing, and extracting text.

Disadvantages of String

  1. String objects are immutable.
  2. Repeatedly creating new Strings can be inefficient for heavy text modification.
  3. == can cause incorrect results when used to compare String contents.
  4. Large amounts of repeated String concatenation can create many temporary objects.

For frequent modifications, use StringBuilder when appropriate.

Real-Life Applications of Strings

Strings are used for:

  • Student names
  • Addresses
  • Email addresses
  • Passwords
  • Usernames
  • Messages
  • File names
  • Website URLs
  • Search queries
  • Text processing
  • Data validation

Summary

A String is used to store text in Java.

Important points:

  • String is a class in Java.
  • Strings are immutable.
  • String indexes start from 0.
  • Use length() to find the number of characters.
  • Use charAt() to access a character.
  • Use equals() to compare String contents.
  • Use substring() to extract part of a String.
  • Use replace() to replace text.
  • Use split() to divide a String into an array.
  • Use StringBuilder when frequent text modification is required.
  • Use nextLine() when you need to read a complete line of input.

Keep learning. Keep building. Keep growing.

© 2026 Ugenz Academy