String Exercises

Declare a String variable

Create a String variable named message and assign it the value “Hello from Java”. Print the value to the console.

Show answer:
String message = "Hello from Java";
System.out.println(message) // prints "Hello from Java"

How long is a String

Write a programme to count the number of characters in the String “Hello from Java”.

Show answer:
String message = "Hello from Java";
System.out.println(message.length()) // prints 15

Check for substring

Write a programme that checks if the string "hello java" contains the substring "java"

Show answer:
String greeting = "hello java";
System.out.println(greeting.contains("java")) // prints true

Watch the whitespace

Write a programme to remove the white space from ” hello “

Show answer:
"    hello      ".trim()  // returns "hello";

Check if two Strings are equal

Write a programme that compares if Strings “hello” and “mello” are equal.

Show answer:
"hello".equals("mello") // returns false;

Extract substring

Write a programme that extracts a substring starting from index 5 to the end of the string "Java Programming" using the substring() method.

Show answer:
String message = "Java Programming";
message.substring(3) // returns "Programming"

Replace a substring

Write a programme that replaces the word "world" in the string "hello world" with "Java"

Show answer:
String message = "hello world";
String newMessage = message.replace("world", "java")
System.out.println(newMessage) // prints "hello java"

Compare two Strings

Write a case insenstive programme that compares “HELLO” and “hello” for equality.

Show answer:
"HELLO".equalsIgnoreCase("hello") // returns true

Extract last name

Write a programme that extracts the last name from the full name string "John Doe“. Print the last name

Show answer:
String fullName = "John Doe";
int index = fullName.indexOf("D");
String lastName = fullName.substring(index);
System.out.println(lastName); // prints "Doe"


Leave a Reply

Your email address will not be published. Required fields are marked *

This site builds beginner confidence through fundamental coding concepts and regular practice. Java is the primary language, but the techniques apply across all programming languages.

Learn. Practice. Master

Categories