Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 3.5Strings in Java

A string is a collection of characters such as letters, numbers or symbols. Strings are used to store text such as names, messages or any other textual data. In Java, strings are objects of the String class.

For example:

Java
String name = "Jamie";
System.out.println(name);
Jamie

Strings can contain letters, digits, spaces and punctuation marks. Like arrays, strings have positions (called indices) that start at 0.

Substring

A substring is a smaller part of a larger string. In Java, the substring() method is used to extract part of a string. There are two ways to use this method:

  • substring(startIndex) – returns everything from the given index to the end.
  • substring(startIndex, endIndex) – returns everything from startIndex up to (but not including) endIndex.
Java
String text = "Hello world";

String part1 = text.substring(6);        // "world"
String part2 = text.substring(0, 5); // "Hello"

Trim

The trim() method removes any extra spaces from the beginning and end of a string. It is useful for cleaning user input.

Java
String s = "  Hello Java  ";
System.out.println("Before trim: [" + s + "]");
System.out.println("After trim: [" + s.trim() + "]");
Before trim: [  Hello Java  ]
After trim: [Hello Java]

Contains

The contains() method checks whether one string contains another. It returns true if it finds the substring, or false if it does not.

Java
String sentence = "My name is Jack";

boolean hasJack = sentence.contains("Jack");
boolean hasBob  = sentence.contains("Bob");

System.out.println(hasJack); // true
System.out.println(hasBob);  // false

Length

The length() method returns the number of characters in a string.

Java
String name = "Jamie";
System.out.println("Length of name: " + name.length());
Length of name: 5

Concatenation

Concatenation means joining two or more strings together. This can be done using the + operator or the concat() method.

Java
String greeting = "Hello";
String language = "Java";

String message1 = greeting + " " + language;     // "Hello Java"
String message2 = greeting.concat(" ").concat(language); // "Hello Java"

Changing case

Strings can be changed to all uppercase or all lowercase using toUpperCase() or toLowerCase(). These methods do not modify the original string but return a new one.

Java
String phrase = "Hello Java";

System.out.println(phrase.toLowerCase()); // "hello java"
System.out.println(phrase.toUpperCase()); // "HELLO JAVA"

Comparing strings

Strings cannot be compared using == because that checks if two string objects are the same in memory. To compare their contents, use equals() for a case-sensitive comparison, or equalsIgnoreCase() to ignore capitalisation.

Java
String word1 = "Hello";
String word2 = "hello";

System.out.println(word1.equals(word2));             // false
System.out.println(word1.equalsIgnoreCase(word2)); // true

Accessing individual characters

Each character in a string can be accessed using charAt(index). Remember that indices start at 0.

Java
String word = "Java";
System.out.println(word.charAt(0)); // 'J'
System.out.println(word.charAt(3)); // 'a'

Searching within strings

The indexOf() method searches a string for a character or substring and returns the first index where it appears. If it cannot find it, it returns -1.

Java
String sentence = "My name is Jamie";
System.out.println(sentence.indexOf("Jamie"));  // 11
System.out.println(sentence.indexOf("Bob"));    // -1

Replacing text

Use replace() to replace one part of a string with another.

Java
String text = "I love Python";
String newText = text.replace("Python", "Java");
System.out.println(newText); // "I love Java"

Splitting strings

The split() method divides a string into parts using a given separator and returns an array of strings.

Java
String sentence = "red,green,blue";
String[] colours = sentence.split(",");

System.out.println(colours[0]); // red
System.out.println(colours[1]); // green
System.out.println(colours[2]); // blue

Other useful String methods

  • startsWith(prefix) – returns true if the string begins with the given text.
  • endsWith(suffix) – returns true if the string ends with the given text.
  • isEmpty() – returns true if the string has no characters.
  • toCharArray() – converts the string into a character array.
  • repeat(n) – repeats the string n times (Java 11+).

Worked example

The following example uses several of the methods above to process a user's input name.

Java
String fullName = "  Jamie Balfour  ";

// Remove spaces
fullName = fullName.trim();

// Convert to uppercase
fullName = fullName.toUpperCase();

// Split first and last name
String[] parts = fullName.split(" ");

System.out.println("First name: " + parts[0]);
System.out.println("Last name: " + parts[1]);
First name: JAMIE
Last name: BALFOUR
Feedback 👍
Comments are sent via email to me.