String Declaration and Initialization

Java: java String str1 = "Hello"; String str2 = new String("World"); char[] charArray = {'H', 'e', 'l', 'l', 'o'}; String str3 = new String(charArray);

TrackJava to Python Journey
Current SectionPython Basics
Progress10 of 19

1. String Declaration and Initialization

Java:

String str1 = "Hello";
String str2 = new String("World");
char[] charArray = {'H', 'e', 'l', 'l', 'o'};
String str3 = new String(charArray);

Python:

str1 = "Hello"
str2 = 'World'  # Single or double quotes both work
str3 = """Multi-line
string literal"""
str4 = "Hello " + "World"  # Concatenation

Key Differences:

  • Python doesn't distinguish between single and double quotes.
  • Python allows triple quotes for multi-line strings.
  • No explicit new keyword needed in Python.

2. String Immutability

Java:

String str = "Hello";
// str[0] = 'J';  // Error! Cannot modify individual characters
String newStr = str.replace('H', 'J');  // Creates new string
System.out.println(newStr);  // "Jello"
System.out.println(str);     // "Hello" (unchanged)

Python:

str = "Hello"
# str[0] = 'J'  # Error! Strings are immutable
new_str = str.replace('H', 'J')  # Creates new string
print(new_str)  # "Jello"
print(str)      # "Hello" (unchanged)

Characteristic:

  • Both strings are immutable; operations return new strings.

3. String Length

Java:

String str = "Hello";
System.out.println(str.length());  // 5 (method)

Python:

str = "Hello"
print(len(str))  # 5 (function)

4. Accessing Characters

Java:

String str = "Hello";
System.out.println(str.charAt(0));     // 'H'
System.out.println(str.charAt(4));     // 'o'
// System.out.println(str.charAt(5));  // Error: out of bounds

Python:

str = "Hello"
print(str[0])      # 'H'
print(str[4])      # 'o'
print(str[-1])     # 'o' (last character)
print(str[-5])     # 'H' (first character from end)
# print(str[5])    # Error: out of range

Key Difference:

  • Python supports negative indexing (from the end).

5. String Slicing (Python-Specific)

Python Only:

str = "Hello World"

print(str[0:5])      # "Hello"      (indices 0-4)
print(str[6:11])     # "World"      (indices 6-10)
print(str[:5])       # "Hello"      (from start to index 4)
print(str[6:])       # "World"      (from index 6 to end)
print(str[-5:])      # "World"      (last 5 characters)
print(str[::2])      # "HloWrd"     (every 2nd character)
print(str[::-1])     # "dlroW olleH" (reversed)

Java Equivalent (more verbose):

String str = "Hello World";
System.out.println(str.substring(0, 5));     // "Hello"
System.out.println(str.substring(6));        // "World"
System.out.println(new StringBuilder(str).reverse().toString());  // Reversed

6. String Concatenation

Java:

String firstName = "John";
String lastName = "Doe";

// Method 1: + operator
String fullName = firstName + " " + lastName;

// Method 2: concat()
String fullName2 = firstName.concat(" ").concat(lastName);

// Method 3: StringBuilder (for multiple concatenations)
StringBuilder sb = new StringBuilder();
sb.append(firstName).append(" ").append(lastName);
String fullName3 = sb.toString();

System.out.println(fullName);  // "John Doe"

Python:

first_name = "John"
last_name = "Doe"

# Method 1: + operator
full_name = first_name + " " + last_name

# Method 2: join() (more efficient for multiple strings)
full_name2 = " ".join([first_name, last_name])

# Method 3: f-strings (Python 3.6+, most Pythonic)
full_name3 = f"{first_name} {last_name}"

# Method 4: format()
full_name4 = "{} {}".format(first_name, last_name)

print(full_name)   # "John Doe"
print(full_name3)  # "John Doe"

7. String Formatting

Java:

String name = "Alice";
int age = 25;

// Using String.format()
String message = String.format("Name: %s, Age: %d", name, age);
System.out.println(message);  // "Name: Alice, Age: 25"

// Using printf()
System.out.printf("Name: %s, Age: %d%n", name, age);

Python:

name = "Alice"
age = 25

# Method 1: f-strings (Python 3.6+, RECOMMENDED)
message = f"Name: {name}, Age: {age}"

# Method 2: format()
message2 = "Name: {}, Age: {}".format(name, age)

# Method 3: % formatting (older style)
message3 = "Name: %s, Age: %d" % (name, age)

# Method 4: print with variables
print(f"Name: {name}, Age: {age}")

print(message)   # "Name: Alice, Age: 25"

8. Case Conversion

Java:

String str = "Hello World";
System.out.println(str.toUpperCase());   // "HELLO WORLD"
System.out.println(str.toLowerCase());   // "hello world"
System.out.println(str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase());  // "Hello world"

Python:

str = "Hello World"
print(str.upper())        # "HELLO WORLD"
print(str.lower())        # "hello world"
print(str.capitalize())   # "Hello world"
print(str.title())        # "Hello World"
print(str.swapcase())     # "hELLO wORLD"

9. String Search and Replace

Java:

String str = "Hello World Hello";

// indexOf() - find position
System.out.println(str.indexOf("Hello"));      // 0
System.out.println(str.indexOf("World"));      // 6
System.out.println(str.indexOf("Xyz"));        // -1 (not found)

// contains()
System.out.println(str.contains("World"));     // true
System.out.println(str.contains("Xyz"));       // false

// replace()
System.out.println(str.replace("Hello", "Hi"));  // "Hi World Hi"

// replaceAll() with regex
System.out.println(str.replaceAll("[aeiou]", "*"));  // "H*llo W*rld H*llo"

Python:

str = "Hello World Hello"

# find() - find position
print(str.find("Hello"))      # 0
print(str.find("World"))      # 6
print(str.find("Xyz"))        # -1 (not found)

# index() - similar but raises error if not found
print(str.index("Hello"))     # 0

# count()
print(str.count("Hello"))     # 2
print(str.count("l"))         # 3

# in operator
print("World" in str)         # True
print("Xyz" in str)           # False

# replace()
print(str.replace("Hello", "Hi"))  # "Hi World Hi"

# Using regex (import re)
import re
print(re.sub("[aeiou]", "*", str))  # "H*llo W*rld H*llo"

10. String Splitting and Joining

Java:

String str = "apple,banana,orange";
String[] fruits = str.split(",");

for (String fruit : fruits) {
    System.out.println(fruit);  // apple, banana, orange
}

// Joining (Java 8+)
String joined = String.join("-", fruits);
System.out.println(joined);  // "apple-banana-orange"

Python:

str = "apple,banana,orange"

# split()
fruits = str.split(",")
print(fruits)  # ['apple', 'banana', 'orange']

for fruit in fruits:
    print(fruit)

# split with limit
parts = str.split(",", 2)  # Split into max 3 parts
print(parts)  # ['apple', 'banana', 'orange']

# join() - reverse of split
joined = "-".join(fruits)
print(joined)  # "apple-banana-orange"

# splitlines()
text = "line1\nline2\nline3"
lines = text.splitlines()
print(lines)  # ['line1', 'line2', 'line3']

11. Whitespace Operations

Java:

String str = "  Hello World  ";
System.out.println(str.trim());        // "Hello World" (remove leading/trailing)
System.out.println(str.strip());       // "Hello World" (Java 11+)
System.out.println(str.stripLeading());  // "Hello World  "
System.out.println(str.stripTrailing()); // "  Hello World"

Python:

str = "  Hello World  "
print(str.strip())        # "Hello World" (remove leading/trailing)
print(str.lstrip())       # "Hello World  " (remove leading)
print(str.rstrip())       # "  Hello World" (remove trailing)

12. String Checking Methods

Java:

String str = "Hello123";
System.out.println(str.startsWith("Hello"));   // true
System.out.println(str.endsWith("123"));       // true
System.out.println(str.equals("Hello123"));    // true
System.out.println(str.equalsIgnoreCase("hello123"));  // true

Python:

str = "Hello123"
print(str.startswith("Hello"))        # True
print(str.endswith("123"))            # True
print(str == "Hello123")              # True
print(str.lower() == "hello123")      # True

# Additional checks
print(str.isdigit())      # False (only digits)
print(str.isalpha())      # False (only letters)
print(str.isalnum())      # True  (letters and digits)
print(str.isupper())      # False (all uppercase)
print(str.islower())      # False (all lowercase)
print(str.isspace())      # False (only whitespace)

13. Practical Examples

Example 1: Parse CSV Data

Java:

String csvLine = "Alice,25,Engineer";
String[] parts = csvLine.split(",");
String name = parts[0];
int age = Integer.parseInt(parts[1]);
String role = parts[2];
System.out.println(name + " " + age + " " + role);  // Alice 25 Engineer

Python:

csv_line = "Alice,25,Engineer"
name, age, role = csv_line.split(",")
age = int(age)
print(f"{name} {age} {role}")  # Alice 25 Engineer

Example 2: Validate Email

Java:

String email = "user@example.com";
boolean isValid = email.matches("^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\\.[A-Z|a-z]{2,}$");
System.out.println(isValid);  // true

Python:

import re
email = "user@example.com"
pattern = r"^[A-Za-z0-9+_.-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$"
is_valid = bool(re.match(pattern, email))
print(is_valid)  # True

Example 3: Extract Words

Java:

String sentence = "The quick brown fox jumps";
String[] words = sentence.split(" ");
System.out.println(words.length);  // 5

// Count specific word
int count = 0;
for (String word : words) {
    if (word.equals("fox")) count++;
}
System.out.println(count);  // 1

Python:

sentence = "The quick brown fox jumps"
words = sentence.split()
print(len(words))  # 5

# Count specific word
count = words.count("fox")
print(count)  # 1

# Find index
index = words.index("fox")
print(index)  # 3

Example 4: String Repetition

Java:

String str = "ha";
String repeated = "";
for (int i = 0; i < 5; i++) {
    repeated += str;
}
System.out.println(repeated);  // "hahahahahaha"

Python:

str = "ha"
repeated = str * 5
print(repeated)  # "hahahahahaha"

14. Summary Table

  • Length

    • Java Method: .length()
    • Python Method/Operator: len()
    • Notes: Function vs method
  • Access character

    • Java Method: .charAt(i)
    • Python Method/Operator: [i] or [i:]
    • Notes: Python supports negative index
  • Substring

    • Java Method: .substring(start, end)
    • Python Method/Operator: [start:end]
    • Notes: Python slicing is more flexible
  • Case conversion

    • Java Method: .toUpperCase()
    • Python Method/Operator: .upper(), .title()
    • Notes: Python has more options
  • Search position

    • Java Method: .indexOf()
    • Python Method/Operator: .find(), .index()
    • Notes: Similar but different returns
  • Contains check

    • Java Method: .contains()
    • Python Method/Operator: in operator
    • Notes: Python syntax is simpler
  • Replace

    • Java Method: .replace()
    • Python Method/Operator: .replace()
    • Notes: Same functionality
  • Split

    • Java Method: .split()
    • Python Method/Operator: .split()
    • Notes: Similar behavior
  • Join

    • Java Method: String.join()
    • Python Method/Operator: str.join()
    • Notes: Different order of operations
  • Trim whitespace

    • Java Method: .trim()
    • Python Method/Operator: .strip()
    • Notes: Same functionality
  • Concatenation

    • Java Method: + or .concat()
    • Python Method/Operator: + or f"{}" or .join()
    • Notes: Python f-strings are modern
  • Formatting

    • Java Method: String.format()
    • Python Method/Operator: f"" or .format()
    • Notes: Python f-strings are preferred