Skip to main content

Introduction to Java Strings

What is a String in Java?

In Java, a String is a sequence of characters. It is one of the most commonly used data types in Java, and it's used to store textual data. String in Java is an object, unlike other basic data types like int, float, double, etc.

Creating a String

There are two ways of creating a String in Java:

  1. String Literal: Here, a String is created just like a regular variable.
String example = "Hello, World!";
  1. Using the new keyword: This method creates a String in Java just like any other object.
String example = new String("Hello, World!");

String Methods

There are several methods you can use with String objects. Here are a few:

  1. length(): This method will return the length of a String.
String example = "Hello, World!";
int length = example.length(); // length = 13
  1. toUpperCase() and toLowerCase(): These methods will convert all the characters in a String to upper case or lower case, respectively.
String example = "Hello, World!";
String upperCase = example.toUpperCase(); // upperCase = "HELLO, WORLD!"
String lowerCase = example.toLowerCase(); // lowerCase = "hello, world!"
  1. contains(): This method checks if a String contains a specified sequence of characters.
String example = "Hello, World!";
boolean containsWorld = example.contains("World"); // containsWorld = true
  1. equals(): This method compares two String objects to check if they are equal.
String example1 = "Hello, World!";
String example2 = "Hello, World!";
boolean isEqual = example1.equals(example2); // isEqual = true

String Concatenation

In Java, you can concatenate or combine two String objects using the + operator.

String hello = "Hello, ";
String world = "World!";
String helloWorld = hello + world; // helloWorld = "Hello, World!"

Immutable Strings

One important thing to note about String objects in Java is that they are immutable. This means once a String object is created, it cannot be changed.

If you perform an operation that seems to modify a String, like concatenation or replacement, what's actually happening is a new String object is being created with the modified value. The original String remains unchanged.

String original = "Hello, World!";
String modified = original.replace("World", "Java");

// The values of original and modified are:
// original = "Hello, World!"
// modified = "Hello, Java!"

In the above example, the original String remains unaltered even after the replacement operation.

These are the basics of String objects in Java. Understanding these concepts will help you handle textual data in your Java programs.