Labs ICT
โญ Pro Login

Strings

Strings in Java are not primitive types โ€” they are objects. But they are so fundamental that we use them in almost every program we write. A String is just a sequence of characters. "Hello", "Java is cool", even "123" โ€” all strings.

Creating and Concatenating Strings

You create a string by putting text in double quotes. To join strings together, use the + operator. This is called concatenation.

public class Main {
  public static void main(String[] args) {
    String firstName = "Zainab";
    String lastName = "Abdullahi";
    String fullName = firstName + " " + lastName;
    System.out.println(fullName);
  }
}

See how we added a space in between by concatenating " "? That is the most common way to combine strings. You can also concatenate strings with other types โ€” Java is smart enough to convert numbers to strings for you.

String message = "You have " + 3 + " new messages";

Useful String Methods

Strings come with a bunch of built-in methods. Here are the ones you will use most:

public class Main {
  public static void main(String[] args) {
    String text = "Java Programming";
    System.out.println(text.length());
    System.out.println(text.charAt(0));
    System.out.println(text.substring(5));
    System.out.println(text.substring(5, 11));
  }
}

Let me explain what each one does:

  • length() โ€” returns how many characters are in the string
  • charAt(index) โ€” gives you the character at a specific position. Remember, Java starts counting at 0, not 1
  • substring(start) โ€” returns everything from the start index to the end
  • substring(start, end) โ€” returns characters from start up to (but not including) end

More Handy Methods

Here are a few more you will use constantly:

public class Main {
  public static void main(String[] args) {
    String name = "  Musa Ibrahim  ";
    System.out.println(name.toUpperCase());
    System.out.println(name.toLowerCase());
    System.out.println(name.trim());
    System.out.println(name.contains("Ibrahim"));
  }
}

toUpperCase() and toLowerCase() change the case. trim() removes whitespace from both ends โ€” super useful for cleaning user input. contains() checks if a string contains a specific sequence.

๐Ÿงช Quick Quiz

What does "Java".length() return?