CLASS STRING
Prepared by Marsel
date: 7.11.2025
What is a String?
A String in Java is a sequence of characters
Example: "Hello", "Java", "123"
Strings are objects, not primitive data types like int
or byte or char e.t.c
Created using String class in the [Link] package.
Example:
String name = "Hello world";
String is Immutable
Immutable means unchangeable
Once a String object is created, it cannot be modified
Every change creates a new String object
Like int for example:
int num=12;
num++;
[Link](num);
output:13
for string it is not available
Common strings operations
Method Description Example
length() Returns length "Hello".length() →5
charAt(int index) Returns character at position "Java".charAt(1) → 'a'
toUpperCase() Converts to uppercase "java".toUpperCase() → "JAVA"
toLowerCase() Converts to lowercase "JAVA".toLowerCase() → "java"
concat() Joins two strings "Hello".concat("World")
equals() Compares strings "a".equals("b")
substring() Extracts part of string "Hello".substring(1,3) → "el"
StringBuilder and StringBuffer
Both are used to create mutable (changeable) strings
StringBuilder – faster, not thread-safe
StringBuffer – slower, thread-safe
StringBuilder sb = new StringBuilder("Hello");
[Link]("_World");
[Link](sb);
output: Hello_World
Summary
Strings are objects that store text
They are immutable
Use methods for manipulation
For performance → use StringBuilder
Practice work
Task 1 — Count String Length Task 5 — Reverse a String
Write a program that prints the length of a given string. Write a program that reverses a string without using StringBuilder.
Example: Example:
Input: "Hello Java" Input: "Java"
Output: Length = 10 Output: "avaJ"
Task 2 — Convert Case Task 6 — Count Vowels
Convert the input string to uppercase and lowercase. Count how many vowels (a, e, i, o, u) are in the given string.
Example: Example:
Input: "Java" Input: "education"
Output: Output: 5 vowels
Uppercase: JAVA
Lowercase: java
Task 7 — Check Palindrome
Task 3 — Character at Index
Check if a string is a palindrome (reads the same
Ask the user to enter a string and an index, then print the character at that position.
backward).
Example:
Example:
Input: "Hello", 1
Input: "level"
Output: e
Output: Palindrome
Task 4 — Check Equality
Compare two strings entered by the user and print whether they are equal or not equal.
Use both:
equals()
==
and explain the difference.
Task 8 — Find Substring
Ask the user for two strings:
Main string
Word to search
Print whether the word exists in the main string using contains().
Example:
Input: "I love Java", "Java"
Output: Found
Task 9 — Replace Words
Replace all occurrences of the word "Java" with "Python" in a
given text.
Example:
Input: "Java is fun"
Output: "Python is fun"
Task 10 — Count Words
Count how many words are in a sentence (words are
separated by spaces).
Example:
Input: "Java is a powerful language"
Output: 5 words
P.s to get more information about strings u can use [Link]