Lecture Notes: Java Strings

Jul 11, 2024

Lecture Notes: Java Strings

Introduction to Java Strings

  • Strings: Non-primitive data type, used extensively in Java.
    • Used to define text in programs (e.g., sentences, words, characters).
    • Can store textual data including spaces and special characters.
    • Memory and performance considerations.

Declaration and Definition of Strings

  • Declare a string using the String type.
    String name = "Tony";
    String fullName = "Tony Stark";
    String sentence = "My name is Tony Stark.";
    
  • Using spaces and special characters in strings.
    String phrase = "Hello, World!";
    

User Input and Scanner Class

  • Using Scanner class to get user input.
    Scanner scanner = new Scanner(System.in);
    String userName = scanner.nextLine();
    System.out.println("Your name is " + userName);
    
  • Important: Use nextLine() for full sentence input.
    scanner.nextLine() -> for full sentences
    scanner.next() -> for single words
    

String Concatenation

  • Concatenating two or more strings using the + operator.
    String firstName = "Tony";
    String lastName = "Stark";
    String fullName = firstName + " " + lastName;
    System.out.println(fullName);
    

String Length

  • Calculate the length of a string.
    int length = fullName.length();
    System.out.println("Length: " + length);
    

Access Characters in a String

  • Using charAt method to access specific characters in a string.
    for (int i = 0; i < fullName.length(); i++) {
      System.out.print(fullName.charAt(i));
    }
    

Comparing Strings

  • Comparing strings with compareTo method.
    int comparison = name1.compareTo(name2);
    
  • Returns:
    • Positive: name1 > name2
    • Zero: name1 == name2
    • Negative: name1 < name2
  • Example:
    if (comparison == 0) {
      System.out.println("Strings are equal");
    } else {
      System.out.println("Strings are not equal");
    }
    

Using equals for String Comparison

  • Difference between compareTo and equals
    if (string1.equals(string2)) {
      System.out.println("Strings are equal");
    }
    

Substrings

  • Extracting a substring from a string using the substring method.
    String part = sentence.substring(11, 15); // Extracts "Tony"
    String toEnd = sentence.substring(11); // Extracts "Tony Stark."
    

Immutability of Strings

  • Strings are immutable in Java.
    • Once created, their value cannot be changed.
    • Any modifications create a new string.

Summary

  • Review of key string functions: declaration, user input, concatenation, length, character access, comparison, and immutability.
  • Practice with the provided code snippets.
  • StringBuilder introduction in the next class.