Strings in Java, with examples

A string is a group of characters in Java. Letters, numbers, special characters, and whitespace are all acceptable character types for strings. The "java.lang.String" package in Java represents strings. There are numerous methods for working with strings in the String class.

How do I declare a string in Java?

To declare a string variable in Java, you must use the "String" keyword followed by the variable's name and an optional initial value.

String mystring = "Hello there, I'm Edwin";

We've declared a string variable called mystring and set its value to "Hello there, I'm Edwin"

However, you can also declare a string variable and assign a value to it later in the program. As an example:

String mystring;
mystring = "Hello there, I'm Edwin";

Java string example

Consider the following Java program as an example demonstrating the string:

Java Code
public class StringExample {
   public static void main(String[] args) {
      String mystring;
      mystring = "Hello there, I'm Edwin";
        
      System.out.println("The value of 'mystring': " + mystring);
   }
}
Output
The value of 'mystring': Hello there, I'm Edwin

This program declares a "StringExample" class with a single method named "main()." A string variable named "mystring" is declared and initialized with the value "Hello there, I'm Edwin" within the "main" method. The value of the variable "mystring" is then printed to the console using the "System.out.println()" method. Using the "+" operator, the string "The value of 'mystring': " is concatenated with the value of "mystring."

Receive string input

You can also use the "Scanner" class to allow the user to enter the string at run time, store that string value inside a variable, say x," and print the value back on the output console. As an example:

Java Code
import java.util.Scanner;

public class StringExample {
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
        
      System.out.println("Please enter a string: ");
      String x = scanner.nextLine();
        
      System.out.println("The value of x is: " + x);
   }
}
Output
Please enter a string: 
codescracker.com
The value of x is: codescracker.com

String concatenation

Either use the "concat()" method or the "+" operator to concatenate two strings in Java. As an example:

Java Code
public class StringConcatenationExample {
   public static void main(String[] args) {
      String str1 = "Codes";
      String str2 = "Cracker";
        
      // Using the + operator for concatenation
      String result1 = str1 + " " + str2;
      System.out.println("Using + operator: " + result1);
        
      // Using the concat() method for concatenation
      String result2 = str1.concat(" ").concat(str2);
      System.out.println("Using concat() method: " + result2);
   }
}
Output
Using + operator: Codes Cracker
Using concat() method: Codes Cracker

String length

Use the "length()" method to find the length of a string in Java. As an example:

Java Code
import java.util.Scanner;

public class StringLengthExample {
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
        
      System.out.println("Please enter a string: ");
      String my_string = scanner.nextLine();
        
      int length = my_string.length();
        
      System.out.println("The length of the string is: " + length);
   }
}
Output
Please enter a string: 
codescracker dot com
The length of the string is: 20

String comparison

Use the "equals()" method when you need to compare two strings in Java. As an example:

Java Code
import java.util.Scanner;

public class StringComparisonExample {
   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);
        
      System.out.println("Please enter the first string: ");
      String a = scanner.nextLine();
        
      System.out.println("Please enter the second string: ");
      String b = scanner.nextLine();
        
      boolean equal = a.equals(b);
        
      if (equal) {
         System.out.println("\nThe two strings are equal.");
      } else {
         System.out.println("\nThe two strings are not equal.");
      }
   }
}
Output
Please enter the first string:
codescracker
Please enter the second string:
codescracker

The two strings are equal.

And if you enter two strings that are not equal, say "codes" and "cracker," you will get the following output.

Please enter the first string:
codes
Please enter the second string:
cracker

The two strings are not equal.

Extract substring

Use the "substring()" method if you want to extract some part (a substring) from a given string. As an example:

Java Code
public class ExtractSubstringExample {
   public static void main(String[] args) {
      String originalString = "Hello, World!";
        
      String subString = originalString.substring(7, 12);
        
      System.out.println(subString);
   }
}
Output
World

We have a "String" variable "originalString" in this program that contains the string "Hello, World!." To extract a substring from the original string, we use the substring() method. The starting index (inclusive) and ending index (exclusive) of the substring to be extracted are passed to the substring() method.

In this example, we pass the arguments 7 and 12 to the substring() method, indicating that we want to extract a substring beginning at index 7 (the character "W" in "World") and ending at index 11 (which is the last "d" in "World"). The resulting substring is assigned to the variable "subString" and then printed to the console with the println() method.

String formatting

Before closing the discussion on the "string" in Java, I want to include one more example that demonstrates the use of "String.format()".

Java Code
public class FormatStringExample {
   public static void main(String[] args) {
      String my_name = "Edwin";
      int my_age = 32;
      
      String text = String.format("My name is %s and I am %d years old.", my_name, my_age);
      System.out.println(text);
   }
}
Output
My name is Edwin and I am 32 years old.

That is, the String.format() method in Java is used to format a string according to a format string and arguments. String.format() returns a string that has been formatted. The most popular format specifiers that can be used with Java's String.format() method are listed in the following table with its brief description:

Format specifier Description
%d Formats an integer value.
%f Formats a floating-point value.
%s Formats a string value.
%c Formats a character value.
%b Formats a boolean value.
%t Formats a date/time value.
%n Adds a newline character.
%e Formats a floating-point value in scientific notation.
%x Formats an integer value in hexadecimal.
%o Formats an integer value in octal.
%h Formats the hash code of an object.
%% Inserts a literal percent sign.

Java Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!