πŸ”€ Strings and Character Arrays in Java – A Complete Beginner’s Guide

When learning programming, one of the first types of data we work with is text. A person’s name, a city, an email address, or even a password is nothing but a collection of characters.

In Java, text can be stored in two different ways:

  • βœ… Character Arrays (char[])
  • βœ… Strings (String)

Although both are used to store text, they work differently and are used for different purposes.

In this blog, we’ll learn:

  • βœ… What are Characters?
  • βœ… What is a Character Array?
  • βœ… What is a String?
  • βœ… Difference between Character Arrays and Strings
  • βœ… Common String Operations
  • βœ… Java Programs with Examples
  • βœ… Time Complexity of Common Operations

Let’s begin!


πŸ“Œ What is a Character?

A character is a single letter, digit, symbol, or special character.

Examples:

'A'
'B'
'Z'
'5'
'@'
'#'
'$'

In Java, a character is represented using the char data type.

Example:

char ch = 'A';

System.out.println(ch);

Output

A

Notice that characters are enclosed within single quotes (‘ ‘).


πŸ“Œ What is a Character Array?

A Character Array is an array that stores multiple characters.

Instead of storing numbers,

int numbers[] = {10,20,30};

we store characters.

char letters[] = {'J','A','V','A'};

Memory representation:

Index

0    1    2    3

+----+----+----+----+
| J  | A  | V  | A  |
+----+----+----+----+

Each element occupies one position in the array.


πŸ’» Java Program: Character Array

public class CharacterArrayDemo {

    public static void main(String[] args) {

        char letters[] = {'J','A','V','A'};

        for(int i = 0; i < letters.length; i++) {
            System.out.print(letters[i]);
        }

    }

}

Output

JAVA

πŸ“Œ What is a String?

A String is a sequence of characters treated as a single object.

Instead of writing

char letters[] = {'J','A','V','A'};

we simply write

String language = "JAVA";

A String makes it much easier to store and manipulate text.


πŸ’» Java Program: String

public class StringDemo {

    public static void main(String[] args) {

        String language = "JAVA";

        System.out.println(language);

    }

}

Output

JAVA

Notice that Strings are enclosed within double quotes (” “).


πŸ“Š Character Array vs String

Suppose we want to store the word HELLO.

Character Array

char word[] = {'H','E','L','L','O'};

Visualization

+----+----+----+----+----+
| H  | E  | L  | L  | O  |
+----+----+----+----+----+

String

String word = "HELLO";

Visualization

"HELLO"

Both store the same text, but a String provides many built-in methods that make programming much easier.


πŸ€” Character Array vs String

Character ArrayString
Stores individual charactersStores complete text
Uses char[]Uses String
Characters accessed using indexesCharacters also accessed using indexes
Limited built-in functionalityMany built-in methods
Mutable (elements can be changed)Immutable (cannot be modified after creation)
Slightly faster for low-level operationsEasier to use in real-world applications

πŸ“Œ Accessing Characters

Every character has an index.

Example:

JAVA

Index

0 1 2 3

Using a Character Array

char letters[] = {'J','A','V','A'};

System.out.println(letters[2]);

Output

V

Using a String

String word = "JAVA";

System.out.println(word.charAt(2));

Output

V

πŸ“Œ Finding the Length

Character Array

char letters[] = {'J','A','V','A'};

System.out.println(letters.length);

Output

4

String

String word = "JAVA";

System.out.println(word.length());

Output

4

Notice the difference.

For arrays,

letters.length

For Strings,

word.length()

The String version is a method, so parentheses are required.


πŸ”„ Traversing a Character Array

public class TraverseCharacterArray {

    public static void main(String[] args) {

        char letters[] = {'J','A','V','A'};

        for(int i = 0; i < letters.length; i++) {

            System.out.println(letters[i]);

        }

    }

}

Output

J
A
V
A

πŸ”„ Traversing a String

public class TraverseString {

    public static void main(String[] args) {

        String word = "JAVA";

        for(int i = 0; i < word.length(); i++) {

            System.out.println(word.charAt(i));

        }

    }

}

Output

J
A
V
A

βœ‚οΈ Converting to Uppercase

String name = "ajay";

System.out.println(name.toUpperCase());

Output

AJAY

πŸ”‘ Converting to Lowercase

String name = "JAVA";

System.out.println(name.toLowerCase());

Output

java

πŸ” Comparing Strings

String s1 = "Java";
String s2 = "Java";

System.out.println(s1.equals(s2));

Output

true

Always use equals() to compare the contents of two Strings.


πŸ”— Concatenating Strings

Concatenation means joining two Strings.

String first = "Hello";
String second = "World";

System.out.println(first + " " + second);

Output

Hello World

βœ‚οΈ Extracting Part of a String

The substring() method extracts a portion of a String.

String language = "Programming";

System.out.println(language.substring(0,7));

Output

Program

πŸ“¦ Why Are Strings Immutable?

One of the most important properties of a String is that it is immutable.

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

Example

String name = "Java";

name = "Python";

Here, the original String "Java" is not modified.

Instead, Java creates a new String object containing "Python" and updates the reference variable.

This design improves security, performance, and memory management.


πŸ’» Complete Java Program

public class StringOperations {

    public static void main(String[] args) {

        String name = "Ajay";

        System.out.println("Length : " + name.length());

        System.out.println("Uppercase : " + name.toUpperCase());

        System.out.println("Lowercase : " + name.toLowerCase());

        System.out.println("First Character : " + name.charAt(0));

        System.out.println("Substring : " + name.substring(1,4));

    }

}

Output

Length : 4

Uppercase : AJAY

Lowercase : ajay

First Character : A

Substring : jay

🌍 Real-Life Applications

Strings are used everywhere.

Examples include:

  • πŸ‘€ Student names
  • πŸ“§ Email addresses
  • πŸ”‘ Passwords
  • 🌐 Website URLs
  • πŸ“± Mobile numbers (stored as Strings)
  • πŸ’¬ Chat messages
  • πŸ“ Documents
  • πŸ” Search keywords

Almost every software application uses Strings extensively.


⚠️ Common Mistakes

❌ Using Single Quotes for Strings

Wrong

String name = 'Ajay';

Correct

String name = "Ajay";

❌ Using Double Quotes for Characters

Wrong

char ch = "A";

Correct

char ch = 'A';

❌ Comparing Strings Using ==

Wrong

if(s1 == s2)

Correct

if(s1.equals(s2))

== compares object references, whereas equals() compares the actual contents of the Strings.


⏱️ Time Complexity of Common Operations

OperationTime Complexity
Access CharacterO(1)
Find LengthO(1)
Traverse StringO(n)
Compare Strings (equals)O(n)
Concatenation (+)O(n)
Convert to UppercaseO(n)
Convert to LowercaseO(n)
Extract SubstringO(n) (overall, depending on implementation and size)

πŸ“ Key Takeaways

  • A Character represents a single symbol and is stored using the char data type.
  • A Character Array stores multiple characters in contiguous memory locations.
  • A String stores an entire sequence of characters as a single object.
  • Characters use single quotes (‘ ‘), whereas Strings use double quotes (” “).
  • Strings provide many built-in methods such as length(), charAt(), equals(), substring(), toUpperCase(), and toLowerCase().
  • Character Arrays are mutable, while Strings are immutable.
  • Traversing a String or Character Array takes O(n) time.

🎯 Final Thoughts

Understanding Strings and Character Arrays is essential because almost every software application processes text in some form. While Character Arrays help us understand how text is stored internally, Strings provide a much simpler and more powerful way to work with textual data in Java.

As you continue your Data Structures and Algorithms journey, you’ll use Strings in searching, pattern matching, recursion, dynamic programming, and many other advanced topics. A strong understanding of Strings today will make learning these concepts much easier in the future.

In the next blog, we’ll explore Linear Search, where we’ll learn how to search for an element in an array step by step using Java.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *