Tutorials Home   >   Programming Basics   >   Strings

Strings

Strings in Programming

1. What is a String?

In programming, a string is a sequence of characters used to represent text. Characters can include letters, numbers, symbols, or spaces. Strings are one of the most commonly used data types in programming because almost all programs need to handle text, like names, messages, or files.

Think of a string as a sentence written in a box where each character has a specific position, starting from 0 (this is called indexing).

Example in Python:

name = "Alice"

Here, name is a string containing the characters A, l, i, c, e.


2. Creating Strings

Strings can be created in several ways depending on the programming language:

a) Python

  • Single quotes: 'Hello'

  • Double quotes: "Hello"

  • Triple quotes (for multi-line strings): '''Hello''' or """Hello"""

greeting = "Hello, World!"
multiline = """This is
a string that
spans multiple lines."""

b) Java

In Java, strings are objects of the String class and are created with double quotes:

String greeting = "Hello, World!";

3. String Operations

Strings can be manipulated in many ways. These are called string operations or methods.

a) Accessing Characters

Strings are indexed, meaning each character has a position starting from 0.

name = "Alice"
print(name[0]) # Output: A
print(name[4]) # Output: e

In Java:

String name = "Alice";
System.out.println(name.charAt(0)); // Output: A

b) String Length

name = "Alice"
print(len(name)) # Output: 5

In Java:

System.out.println(name.length()); // Output: 5

c) Concatenation (Joining Strings)

first_name = "Alice"
last_name = "Smith"
full_name = first_name + " " + last_name
print(full_name) # Output: Alice Smith

In Java:

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

d) Repetition

Python allows repeating strings with *:

print("Ha" * 3) # Output: HaHaHa

e) Slicing (Substrings)

Python allows extracting a portion of a string using slicing:

text = "Programming"
print(text[0:6]) # Output: Progra
print(text[3:]) # Output: gramming
print(text[:5]) # Output: Progr

Java uses substring:

String text = "Programming";
System.out.println(text.substring(0, 6)); // Output: Progra

4. Common String Methods

Strings come with many built-in methods for manipulation.

Operation Python Example Java Example
Convert to uppercase text.upper() text.toUpperCase()
Convert to lowercase text.lower() text.toLowerCase()
Remove whitespace text.strip() text.trim()
Replace text text.replace("old", "new") text.replace("old", "new")
Split string text.split() text.split(" ")
Check start text.startswith("Pro") text.startsWith("Pro")
Check end text.endswith("ing") text.endsWith("ing")

Example in Python:

text = " Hello, World! "
print(text.upper()) # HELLO, WORLD!
print(text.strip()) # Hello, World!
print(text.replace("World", "Python")) # Hello, Python!

5. String Immutability

In many programming languages (Python, Java), strings are immutable. This means once a string is created, it cannot be changed. Any operation that seems to modify a string actually creates a new string.

text = "Hello"
text.upper()
print(text) # Output: Hello (original string unchanged)

To actually change it:

text = text.upper()
print(text) # Output: HELLO

6. String Formatting

String formatting allows combining variables and text in a readable way.

Python Examples

  • Using f-strings (Python 3.6+):

name = "Alice"
age = 20
print(f"My name is {name} and I am {age} years old.")
  • Using format():

print("My name is {} and I am {} years old.".format(name, age))

Java Examples

String name = "Alice";
int age = 20;
System.out.printf("My name is %s and I am %d years old.\n", name, age);

7. Escape Sequences

Escape sequences allow you to include special characters in strings, like newlines or tabs.

Escape Meaning
\n New line
\t Tab
\\ Backslash
\" Double quote inside a string
\' Single quote inside a string

Example in Python:

print("Hello\nWorld") # Output:
# Hello
# World

Example in Java:

System.out.println("Hello\tWorld"); // Output: Hello World

8. Best Practices for Using Strings

  1. Use descriptive variable names – first_name is better than x.

  2. Use string methods instead of manual loops for efficiency.

  3. Avoid unnecessary string concatenation in loops (especially in Java; use StringBuilder).

  4. Keep strings readable – Use multi-line strings for long text.

  5. Validate user input when working with strings to prevent errors.


9. Summary

Strings are sequences of characters that are essential for handling text in programming. Key points:

  • Strings can be created with quotes (single, double, or triple).

  • Strings are immutable in Python and Java.

  • You can access, concatenate, slice, and manipulate strings using built-in operations and methods.

  • String formatting and escape sequences make text more readable and user-friendly.

  • Strings are used in almost all programs, from simple greetings to file handling and web applications.

Mastering strings is crucial because text is everywhere in programming, and effective string handling improves program clarity and functionality.