String Fundamentals

Solve one Java logic problem at a time, then flip for the complete explanation and program.

0/180 Known filtered set
Difficulty
Read Full Guide Question: 1 of 180

Java Logic Development · Chapter 14 Companion Article

String Fundamentals

Fifteen foundational String-handling problems — reading input, manual length counting, character traversal, reversal, comparison, case conversion, and character/word counting — solved without relying on shortcut methods, followed by a comparison of core concepts: immutability, indexing, charAt() versus toCharArray(), String versus char, equals() versus ==, and StringBuilder for repeated modification. These fundamentals form the base for later string problems such as palindromes, anagrams, and substring algorithms.

1. Read a String

Concept

A String stores a sequence of characters. In Java, Scanner is commonly used to read string input from the console.

next() reads only one word, while nextLine() reads the complete line including spaces.

Problem Statement

Read a complete string entered by the user and print it.

Example Input

Output
Java Logic Development

Expected Output

Output
You entered: Java Logic Development

Hint

Use Scanner.nextLine() when the input can contain spaces.

Logic

  1. Create a Scanner object.
  2. Call nextLine() to read the complete input line.
  3. Store the result in a String.
  4. Print the stored string.

Why This Logic Works

nextLine() continues reading characters until the user presses Enter. Because it does not stop at whitespace, it is suitable for names, sentences, addresses, and other multi-word input.

Dry Run

Input:

Output
Java Logic Development

Execution:

  • scanner.nextLine() reads the complete line.
  • text becomes "Java Logic Development".
  • The program prints the value stored in text.

Java Program

Java
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        System.out.println("You entered: " + text);
        scanner.close();
    }
}

Program Output

For input:

Output
Java Logic Development

Output:

Output
You entered: Java Logic Development

Time Complexity

  • Reading: O(n)
  • Printing: O(n)

Here, n is the number of characters.

Space Complexity

O(n) for storing the input string.

Common Mistakes

  • Using next() when the input contains spaces.
  • Calling nextLine() immediately after nextInt() without consuming the remaining newline.
  • Forgetting that strings may be empty.

Interview Tip

Know the difference between:

  • next() → reads one token.
  • nextLine() → reads the complete line.

2. String Length Without length()

Concept

Normally, Java provides String.length(). To practice logic without using this method, the string can be converted into a character array and the characters can be counted manually.

Problem Statement

Find the number of characters in a string without calling String.length().

Example Input

Output
Java

Expected Output

Output
Length: 4

Hint

Convert the string to a character array and increase a counter for every character.

Logic

  1. Convert the string using toCharArray().
  2. Initialize count to 0.
  3. Traverse each character.
  4. Increment count.
  5. Print the final counter value.

Why This Logic Works

Every character in the original string becomes one element in the character array. Counting those elements gives the number of characters in the string without using String.length().

Dry Run

String:

Output
Java

Characters:

CharacterCount
J1
a2
v3
a4

Final length:

Output
4

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "Java";
        int count = 0;
        for (char ch : text.toCharArray()) {
            count++;
        }
        System.out.println("Length: " + count);
    }
}

Program Output

Output
Length: 4

Time Complexity

O(n)

Space Complexity

O(n) because toCharArray() creates a character array.

Alternative Approach

A character iterator such as text.chars() can also process the characters, but using a simple character array is easier for basic logic development.

Edge Case

For an empty string:

Output
""

The counter remains 0.

Common Mistake

Do not confuse:

  • string.length() → method.
  • array.length → field.

Interview Tip

If an interviewer specifically prohibits length(), confirm whether converting the string to a character array is allowed.

3. Character Traversal

Concept

Character traversal means visiting every character of a string one by one.

The most common approach uses:

Output
charAt(index)

String indexes start from 0.

Problem Statement

Traverse a string and print every character separately.

Example

String:

Output
Java

Expected output:

Output
J
a
v
a

Hint

Run a loop from index 0 to length() - 1.

Logic

  1. Start the loop with i = 0.
  2. Continue while i < text.length().
  3. Obtain the current character using text.charAt(i).
  4. Print the character.

Dry Run

For:

Output
Java
IndexcharAt(index)
0J
1a
2v
3a

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "Java";
        for (int i = 0; i < text.length(); i++) {
            System.out.println(text.charAt(i));
        }
    }
}

Program Output

Output
J
a
v
a

Time Complexity

O(n)

Space Complexity

O(1)

Important Detail

The last valid index is:

Output
text.length() - 1

For a four-character string, valid indexes are 0 through 3.

Common Mistake

Using:

Output
i <= text.length()

causes StringIndexOutOfBoundsException.

Correct condition:

Output
i < text.length()

Interview Tip

Character traversal is the foundation of many string problems such as palindrome checking, frequency counting, case conversion, filtering, and pattern matching.

4. Reverse a String

Concept

Reversing a string means arranging its characters from the last character to the first.

Example:

Output
Java → avaJ

Problem Statement

Reverse a string without using StringBuilder.reverse().

Example Input

Output
Java

Expected Output

Output
Reversed: avaJ

Hint

Start from the last index and move toward index 0.

Logic

  1. Create an empty StringBuilder.
  2. Start from text.length() - 1.
  3. Append each character to the result.
  4. Continue until index 0.
  5. Print the reversed value.

Why StringBuilder Is Used

Strings are immutable in Java. Repeatedly using result = result + ch creates multiple temporary String objects.

StringBuilder allows characters to be appended efficiently.

Dry Run

Original:

Output
Java
IndexCharacterResult
3aa
2vav
1aava
0JavaJ

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "Java";
        StringBuilder reversed = new StringBuilder();
        for (int i = text.length() - 1; i >= 0; i--) {
            reversed.append(text.charAt(i));
        }
        System.out.println("Reversed: " + reversed);
    }
}

Program Output

Output
Reversed: avaJ

Time Complexity

O(n)

Space Complexity

O(n)

Edge Cases

  • Empty string → empty result.
  • One character → unchanged.
  • Spaces and special characters are also reversed.

Example:

Output
Java 8! → !8 avaJ

Common Mistake

Starting from:

Output
text.length()

instead of:

Output
text.length() - 1

The first attempt accesses an invalid index.

Interview Tip

For an in-place reversal question, interviewers may ask you to convert the string to a character array and swap characters using two pointers.

5. Compare Two Strings

Concept

Java strings should normally be compared using equals() rather than ==.

equals() compares character content.

== compares object references.

Problem Statement

Check whether two strings contain exactly the same sequence of characters.

Example

Output
first = "Java"
second = "Java"

Expected output:

Output
Strings are equal

Hint

Compare length first and then compare corresponding characters.

Logic

To understand the comparison internally:

  1. Check whether both strings have the same length.
  2. Traverse their characters.
  3. Compare characters at the same indexes.
  4. If any characters differ, the strings are different.
  5. If all characters match, the strings are equal.

Dry Run

Strings:

Output
Java
Java
IndexFirstSecondMatch
0JJYes
1aaYes
2vvYes
3aaYes

All characters match.

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String first = "Java";
        String second = "Java";
        boolean equal = true;
        if (first.length() != second.length()) {
            equal = false;
        } else {
            for (int i = 0; i < first.length(); i++) {
                if (first.charAt(i) != second.charAt(i)) {
                    equal = false;
                    break;
                }
            }
        }
        if (equal) {
            System.out.println("Strings are equal");
        } else {
            System.out.println("Strings are not equal");
        }
    }
}

Program Output

Output
Strings are equal

Built-in Approach

For normal Java applications:

Output
first.equals(second)

For case-insensitive comparison:

Output
first.equalsIgnoreCase(second)

Time Complexity

O(n) in the worst case.

Space Complexity

O(1)

Common Mistake

Avoid:

Output
first == second

when the goal is content comparison.

Interview Tip

Be ready to explain why this can behave differently:

Output
String a = new String("Java");
String b = new String("Java");

a.equals(b) is true because the contents match, while a == b is false because they refer to different objects.

6. Convert Uppercase to Lowercase

Concept

Uppercase English letters A-Z can be converted to lowercase by applying the difference between uppercase and lowercase Unicode values.

For basic English letters:

Output
'a' - 'A' = 32

Problem Statement

Convert uppercase letters in a string to lowercase without using toLowerCase().

Example Input

Output
JAVA Logic

Expected Output

Output
java logic

Hint

Check whether a character is between 'A' and 'Z'.

Logic

For every character:

  1. Check ch >= 'A' && ch <= 'Z'.
  2. If true, calculate the corresponding lowercase character.
  3. Leave lowercase letters and other characters unchanged.

Dry Run

Input:

Output
JAVA Logic
CharacterActionResult Character
JConvertj
AConverta
VConvertv
AConverta
spaceKeepspace
LConvertl
oKeepo
gKeepg
iKeepi
cKeepc

Result:

Output
java logic

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "JAVA Logic";
        StringBuilder result = new StringBuilder();
        for (char ch : text.toCharArray()) {
            if (ch >= 'A' && ch <= 'Z') {
                ch = (char) (ch + ('a' - 'A'));
            }
            result.append(ch);
        }
        System.out.println(result);
    }
}

Program Output

Output
java logic

Time Complexity

O(n)

Space Complexity

O(n)

Practical Approach

Production code normally uses:

Output
text.toLowerCase()

Manual conversion is mainly useful for understanding character operations.

Important Limitation

The manual 'A' to 'Z' logic handles basic English alphabet characters only. Java's built-in Unicode-aware APIs should be preferred when international text must be handled correctly.

Interview Tip

Explain the difference between learning ASCII-style case conversion and writing Unicode-aware application code.

7. Convert Lowercase to Uppercase

Concept

Lowercase English characters can be converted to uppercase by subtracting the character-value difference between 'a' and 'A'.

Problem Statement

Convert lowercase English letters to uppercase without using toUpperCase().

Example Input

Output
java Logic

Expected Output

Output
JAVA LOGIC

Hint

Only modify characters between 'a' and 'z'.

Logic

  1. Traverse every character.
  2. Check whether the character is lowercase.
  3. Convert lowercase characters to uppercase.
  4. Preserve existing uppercase letters, spaces, digits, and symbols.

Dry Run

Input:

Output
java Logic
CharacterConverted
jJ
aA
vV
aA
spacespace
LL
oO
gG
iI
cC

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "java Logic";
        StringBuilder result = new StringBuilder();
        for (char ch : text.toCharArray()) {
            if (ch >= 'a' && ch <= 'z') {
                ch = (char) (ch - ('a' - 'A'));
            }
            result.append(ch);
        }
        System.out.println(result);
    }
}

Program Output

Output
JAVA LOGIC

Time Complexity

O(n)

Space Complexity

O(n)

Edge Case

Input:

Output
java123!

Result:

Output
JAVA123!

Digits and symbols remain unchanged.

Common Mistake

Do not convert every character blindly. Applying arithmetic to digits or special characters changes them into unrelated characters.

Interview Tip

The key requirement is the range check:

Output
ch >= 'a' && ch <= 'z'

before performing the conversion.

8. Toggle Character Case

Concept

Case toggling changes:

  • Uppercase → lowercase.
  • Lowercase → uppercase.
  • Non-alphabetic characters → unchanged.

Example:

Output
JaVa123 → jAvA123

Problem Statement

Toggle the case of every alphabetic character in a string.

Hint

Use separate conditions for uppercase and lowercase letters.

Logic

For each character:

  1. If it is between 'A' and 'Z', convert it to lowercase.
  2. Else if it is between 'a' and 'z', convert it to uppercase.
  3. Otherwise, copy it unchanged.

Dry Run

Input:

Output
JaVa 8!
CharacterTypeResult
JUppercasej
aLowercaseA
VUppercasev
aLowercaseA
spaceOtherspace
8Other8
!Other!

Result:

Output
jAvA 8!

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "JaVa 8!";
        StringBuilder result = new StringBuilder();
        for (char ch : text.toCharArray()) {
            if (ch >= 'A' && ch <= 'Z') {
                ch = (char) (ch + ('a' - 'A'));
            } else if (ch >= 'a' && ch <= 'z') {
                ch = (char) (ch - ('a' - 'A'));
            }
            result.append(ch);
        }
        System.out.println(result);
    }
}

Program Output

Output
jAvA 8!

Time Complexity

O(n)

Space Complexity

O(n)

Common Mistake

Using two independent if statements can accidentally convert a character twice.

For example, after converting uppercase J to lowercase j, a second lowercase check could convert it back.

Using if followed by else if avoids this problem.

Interview Tip

This question tests character classification, conditional ordering, and conversion logic in a single traversal.

9. Count Characters

Concept

Character counting finds how many characters are present in a string.

Depending on the requirement, spaces may either be included or excluded. The requirement must therefore be clear.

Here, every character including spaces is counted.

Problem Statement

Count the total number of characters in a string without using String.length().

Example Input

Output
Java 8

Expected Output

Output
Characters: 6

Hint

Traverse the characters and increment one counter for each character encountered.

Logic

  1. Initialize count = 0.
  2. Convert the string to a character array.
  3. Visit each character.
  4. Increment count.
  5. Print the result.

Dry Run

Input:

Output
Java 8

Characters:

Output
J a v a [space] 8
CharacterCount
J1
a2
v3
a4
space5
86

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "Java 8";
        int count = 0;
        for (char ch : text.toCharArray()) {
            count++;
        }
        System.out.println("Characters: " + count);
    }
}

Program Output

Output
Characters: 6

Time Complexity

O(n)

Space Complexity

O(n) because toCharArray() creates an array.

Variation: Ignore Spaces

The condition can be changed to:

Output
if (ch != ' ') {
    count++;
}

Common Mistake

Do not assume that "character count" always means alphabetic characters. A character may also be a digit, whitespace, punctuation mark, or symbol.

Interview Tip

Clarify whether the interviewer wants:

  • Total characters.
  • Characters excluding spaces.
  • Alphabetic characters only.
  • Unicode code points rather than Java char values.

10. Count Vowels

Concept

The English vowels are:

Output
a, e, i, o, u

Their uppercase forms should normally be counted as well.

Problem Statement

Count the vowels present in a string.

Example Input

Output
Java Programming

Expected Output

Output
Vowels: 5

Hint

Convert the current character to lowercase before comparing it with the five vowels.

Logic

  1. Initialize count = 0.
  2. Traverse the string.
  3. Convert each character to lowercase using Character.toLowerCase().
  4. Check whether it is a, e, i, o, or u.
  5. Increment the counter when a vowel is found.

Dry Run

Input:

Output
Java Programming

Vowels encountered:

Output
a
a
o
a
i

Total:

Output
5

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "Java Programming";
        int count = 0;
        for (char ch : text.toCharArray()) {
            char current = Character.toLowerCase(ch);
            if (current == 'a' || current == 'e' || current == 'i' || current == 'o' || current == 'u') {
                count++;
            }
        }
        System.out.println("Vowels: " + count);
    }
}

Program Output

Output
Vowels: 5

Time Complexity

O(n)

Space Complexity

O(n) because of the character array.

Edge Cases

Input:

Output
12345

Result:

Output
Vowels: 0

Input:

Output
AEIOU

Result:

Output
Vowels: 5

Common Mistake

Checking only lowercase vowels causes uppercase vowels to be ignored.

Interview Tip

For repeated vowel checking in larger problems, a Set<Character> may improve readability. For only five vowels, direct comparisons are simple and efficient.

11. Count Consonants

Concept

A consonant is an alphabetic character that is not a vowel.

Digits, spaces, and special characters must not be counted as consonants.

Problem Statement

Count consonants in a string containing letters, digits, spaces, or symbols.

Example Input

Output
Java 8!

Expected Output

Output
Consonants: 2

Hint

First check that the character is a letter. Then verify that it is not a vowel.

Logic

For each character:

  1. Convert it to lowercase.
  2. Check whether it is between 'a' and 'z'.
  3. Check that it is not one of a, e, i, o, u.
  4. Increment the consonant counter.

Why Both Conditions Are Required

Checking only "not a vowel" would incorrectly count:

  • Spaces.
  • Digits.
  • Symbols.

as consonants.

Dry Run

Input:

Output
Java 8!
CharacterLetter?Vowel?Consonant Count
JYesNo1
aYesYes1
vYesNo2
aYesYes2
spaceNoNo2
8NoNo2
!NoNo2

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "Java 8!";
        int count = 0;
        for (char ch : text.toCharArray()) {
            char current = Character.toLowerCase(ch);
            boolean isLetter = current >= 'a' && current <= 'z';
            boolean isVowel = current == 'a' || current == 'e' || current == 'i' || current == 'o' || current == 'u';
            if (isLetter && !isVowel) {
                count++;
            }
        }
        System.out.println("Consonants: " + count);
    }
}

Program Output

Output
Consonants: 2

Time Complexity

O(n)

Space Complexity

O(n)

Alternative Approach

Java provides:

Output
Character.isLetter(ch)

This is preferable when Unicode alphabetic characters must also be handled.

Common Mistake

This condition is incomplete:

Output
if (!isVowel) {
    count++;
}

It also counts non-letter characters.

Interview Tip

A good answer clearly separates character classification from vowel checking.

12. Count Digits

Concept

A string may contain alphabetic characters and numeric characters together.

Example:

Output
Java17Version8

Digits are:

Output
1, 7, 8

Problem Statement

Count numeric digits present inside a string.

Example Input

Output
Java17Version8

Expected Output

Output
Digits: 3

Hint

A decimal digit lies between '0' and '9'.

Logic

  1. Initialize count = 0.
  1. Traverse every character.
  1. Check:

ch >= '0' && ch <= '9'

  1. Increment the counter whenever the condition is true.

Dry Run

Input:

Output
Java17Version8

Relevant characters:

CharacterDigit?Count
JNo0
aNo0
vNo0
aNo0
1Yes1
7Yes2
VNo2
...No2
8Yes3

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "Java17Version8";
        int count = 0;
        for (char ch : text.toCharArray()) {
            if (ch >= '0' && ch <= '9') {
                count++;
            }
        }
        System.out.println("Digits: " + count);
    }
}

Program Output

Output
Digits: 3

Time Complexity

O(n)

Space Complexity

O(n)

Built-in Alternative

Java also provides:

Output
Character.isDigit(ch)

This handles a broader range of Unicode digit characters.

Important Difference

Counting digits is different from counting numbers.

For:

Output
Java123Test45

Digit count:

Output
5

Number groups:

Output
2

The numbers are 123 and 45.

Interview Tip

Clarify whether the problem asks for individual digits or complete numeric sequences.

13. Count Special Characters

Concept

For this problem, a special character is a character that is:

  • Not an English letter.
  • Not a digit.
  • Not whitespace.

Examples include:

Output
@ # $ % & ! ?

Problem Statement

Count special characters in a string while ignoring letters, digits, and spaces.

Example Input

Output
Java@2026#Dev!

Expected Output

Output
Special characters: 3

Hint

Count a character only when it does not belong to the letter, digit, or whitespace categories.

Logic

For every character:

  1. Check whether it is alphabetic.
  2. Check whether it is a digit.
  3. Check whether it is whitespace.
  4. If none of these conditions is true, count it as special.

Dry Run

Input:

Output
Java@2026#Dev!

Special characters:

CharacterSpecial?Count
JNo0
aNo0
vNo0
aNo0
@Yes1
2No1
0No1
2No1
6No1
#Yes2
DNo2
eNo2
vNo2
!Yes3

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "Java@2026#Dev!";
        int count = 0;
        for (char ch : text.toCharArray()) {
            if (!Character.isLetterOrDigit(ch) && !Character.isWhitespace(ch)) {
                count++;
            }
        }
        System.out.println("Special characters: " + count);
    }
}

Program Output

Output
Special characters: 3

Time Complexity

O(n)

Space Complexity

O(n)

Edge Case

Input:

Output
Java 2026

Result:

Output
Special characters: 0

The space is deliberately excluded from the special-character count.

Common Mistake

Counting every non-alphanumeric character as special without deciding whether spaces should be included.

Interview Tip

State the definition of "special character" before coding because requirements can vary between problems.

14. Count Words

Concept

A word is a consecutive sequence of non-whitespace characters.

Consider:

Output
Java   Logic Development

There are three words even though several spaces appear between them.

A robust solution should therefore not assume exactly one space between words.

Problem Statement

Count the number of words in a string without using split().

Example Input

Output
Java   Logic Development

Expected Output

Output
Words: 3

Hint

Count a word when a non-whitespace character appears immediately after whitespace or at the beginning of the string.

Logic

Use a boolean variable named inWord.

  1. Set inWord = false.
  2. Traverse every character.
  3. If the character is not whitespace and inWord is false:
  • A new word has started.
  • Increment count.
  • Set inWord = true.
  1. If whitespace is found:
  • Set inWord = false.
  1. Continue until the string ends.

Why This Logic Works

A word is counted only when entering a new sequence of non-space characters. Multiple consecutive spaces therefore do not increase the word count.

Dry Run

Input:

Output
Java   Logic Development
Current PartActionWord Count
JStart word1
avaContinue word1
spacesLeave word1
LStart word2
ogicContinue word2
spaceLeave word2
DStart word3
evelopmentContinue word3

Final count:

Output
3

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "Java   Logic Development";
        int count = 0;
        boolean inWord = false;
        for (char ch : text.toCharArray()) {
            if (!Character.isWhitespace(ch)) {
                if (!inWord) {
                    count++;
                    inWord = true;
                }
            } else {
                inWord = false;
            }
        }
        System.out.println("Words: " + count);
    }
}

Program Output

Output
Words: 3

Time Complexity

O(n)

Space Complexity

O(n) because toCharArray() creates an array.

Edge Cases

Empty string:

Output
""

Result:

Output
Words: 0

Only spaces:

Output
"     "

Result:

Output
Words: 0

Leading and trailing spaces:

Output
"  Java Logic  "

Result:

Output
Words: 2

Alternative Approach

A convenient Java solution is:

Output
text.trim().split("\\s+")

However, the manual traversal approach provides better logic practice and avoids creating an array of words.

Common Mistake

Using:

Output
spaces + 1

This fails when:

  • There are multiple spaces.
  • The string starts with spaces.
  • The string ends with spaces.
  • The string is empty.

Interview Tip

The state-based inWord technique is useful for parsing and scanning problems beyond simple word counting.

15. Remove Spaces

Concept

Removing spaces means building a new string that contains all required characters except space characters.

Example:

Output
Java Logic Development

becomes:

Output
JavaLogicDevelopment

Problem Statement

Remove spaces from a string without using replace().

Example Input

Output
Java Logic Development

Expected Output

Output
JavaLogicDevelopment

Hint

Append a character to the result only when it is not a space.

Logic

  1. Create an empty StringBuilder.
  2. Traverse every character.
  3. Check whether ch != ' '.
  4. Append only non-space characters.
  5. Print the result.

Dry Run

Input:

Output
Java Logic
CharacterActionResult
JKeepJ
aKeepJa
vKeepJav
aKeepJava
spaceSkipJava
LKeepJavaL
oKeepJavaLo
gKeepJavaLog
iKeepJavaLogi
cKeepJavaLogic

Java Program

Java
public class Main {
    public static void main(String[] args) {
        String text = "Java Logic Development";
        StringBuilder result = new StringBuilder();
        for (char ch : text.toCharArray()) {
            if (ch != ' ') {
                result.append(ch);
            }
        }
        System.out.println(result);
    }
}

Program Output

Output
JavaLogicDevelopment

Time Complexity

O(n)

Space Complexity

O(n)

Built-in Alternative

To remove ordinary space characters:

Output
text.replace(" ", "")

To remove different kinds of whitespace using regular expressions:

Output
text.replaceAll("\\s+", "")

Important Difference

The manual condition:

Output
ch != ' '

removes only the standard space character.

It does not remove tabs or newline characters.

For general whitespace handling, use:

Output
!Character.isWhitespace(ch)

Common Mistake

Using trim() when the requirement is to remove every space.

trim() removes leading and trailing spaces, not spaces in the middle.

Example:

Output
" Java Logic ".trim()

becomes:

Output
"Java Logic"

not:

Output
"JavaLogic"

Interview Tip

Clarify whether the requirement is to:

  • Remove all spaces.
  • Remove all whitespace.
  • Remove leading/trailing spaces.
  • Replace repeated spaces with one space.

These are different string-processing problems.

String Fundamentals: Logic Comparison

ProblemCore TechniqueMain Java FeatureTime
Read a StringInput handlingnextLine()O(n)
Length Without length()Manual countingtoCharArray()O(n)
Character TraversalIndex traversalcharAt()O(n)
Reverse StringReverse traversalStringBuilderO(n)
Compare StringsCharacter comparisoncharAt() / equals()O(n)
Uppercase to LowercaseCharacter conversionRange checkO(n)
Lowercase to UppercaseCharacter conversionRange checkO(n)
Toggle CaseClassification + conversionif-elseO(n)
Count CharactersCounterCharacter traversalO(n)
Count VowelsClassificationCharacter comparisonO(n)
Count ConsonantsLetter + vowel checksConditionsO(n)
Count DigitsCharacter classification'0' to '9'O(n)
Count Special CharactersMulti-category filteringCharacter methodsO(n)
Count WordsState trackinginWord flagO(n)
Remove SpacesFilteringStringBuilderO(n)

Important String Fundamentals

String Immutability

Java String objects are immutable. Once a string object is created, its contents cannot be modified.

For example:

Output
String text = "Java";
text = text + " Logic";

The original "Java" object is not modified. A new string value is produced.

For repeated modifications inside loops, StringBuilder is generally more appropriate.

String Indexing

For:

Output
String text = "Java";

Indexes are:

IndexCharacter
0J
1a
2v
3a

The valid range is:

Output
0 to text.length() - 1

Accessing an index outside this range throws StringIndexOutOfBoundsException.

charAt() vs toCharArray()

Use charAt() when working directly with positions:

Output
char ch = text.charAt(i);

Use toCharArray() when a simple enhanced for loop is convenient:

Output
for (char ch : text.toCharArray()) {
    // Process character
}

toCharArray() creates an additional array, while charAt() can access the original string directly.

String vs char

A char stores one UTF-16 code unit:

Output
char ch = 'J';

A String stores a sequence:

Output
String text = "Java";

Single quotes are used for char.

Double quotes are used for String.

Correct:

Output
char ch = 'A';
String text = "A";

Incorrect:

Output
char ch = "A";
String text = 'A';

equals() vs ==

Use:

Output
first.equals(second)

for string content comparison.

Use:

Output
first == second

only when you intentionally want to check whether both references point to the same object.

StringBuilder for Repeated Modification

Avoid repeatedly doing this inside a large loop:

Output
result = result + ch;

Each concatenation may create another string object.

Prefer:

Output
StringBuilder result = new StringBuilder();
result.append(ch);

After processing:

Output
String finalText = result.toString();

This technique is especially useful for:

  • Reversing.
  • Removing characters.
  • Filtering.
  • Case conversion.
  • Rearranging strings.

Character Utility Methods

Java's Character class contains useful methods for real application code.

Common examples:

Output
Character.isLetter(ch)
Character.isDigit(ch)
Character.isLetterOrDigit(ch)
Character.isWhitespace(ch)
Character.isUpperCase(ch)
Character.isLowerCase(ch)
Character.toUpperCase(ch)
Character.toLowerCase(ch)

Manual 'A' to 'Z' checks are valuable for understanding logic, while these methods are usually preferable when broader character support is required.

Common String Logic Mistakes

  1. Using == instead of equals() for content comparison.
  2. Accessing index text.length() with charAt().
  3. Forgetting that indexing starts at 0.
  4. Using next() when complete-line input is required.
  5. Counting digits and symbols as consonants.
  6. Ignoring uppercase vowels.
  7. Assuming one space always represents one word boundary.
  8. Using trim() when all internal spaces must be removed.
  9. Concatenating immutable strings repeatedly inside large loops.
  10. Forgetting that an empty string has no valid character index.
  11. Modifying characters without checking their valid range.
  12. Treating all non-letters as special characters without defining how spaces should be handled.
  13. Assuming a Java char always represents an entire visible Unicode character.

Interview-Focused String Fundamentals

A learner should be able to explain and implement these operations without depending completely on built-in methods:

  • Traverse a string from left to right.
  • Traverse from right to left.
  • Access a character by index.
  • Count characters manually.
  • Compare corresponding characters.
  • Classify letters, digits, spaces, and symbols.
  • Detect uppercase and lowercase characters.
  • Convert character case.
  • Build a new string from selected characters.
  • Maintain a counter during traversal.
  • Maintain state while detecting words.
  • Use StringBuilder for repeated modifications.
  • Explain why String is immutable.
  • Explain equals() versus ==.
  • Handle empty strings and whitespace correctly.

These fundamentals form the base for later string problems such as palindrome checking, anagram detection, character frequency, duplicate removal, substring problems, word reversal, compression, rotation, and interview-style string algorithms.

Question Hint