S01L11 – String basics

Strings basics in Java

Strings are one of the most commonly used data types in Java, representing sequences of characters. They are objects that contain methods for manipulating text, such as comparing, searching, and extracting substrings. Understanding how to use Strings effectively is essential for any Java developer. In this article, we will explore the basics of Strings, their properties, and common operations, providing a strong foundation for beginners.

1. What is a String in Java?

A String in Java is a sequence of characters enclosed in double quotes. Unlike primitive data types, Strings are objects in Java, and they are immutable, meaning their value cannot be changed once created.

1.1. Creating Strings

Strings can be created using string literals or the new keyword:

Both methods create a String object, but using string literals is more common and efficient.

2. Common String Methods

Java provides a variety of methods for String manipulation. Here are some of the most commonly used:

  • length(): Returns the number of characters in the String.
  • charAt(int index): Returns the character at the specified index.
  • substring(int beginIndex, int endIndex): Returns a new String that is a substring of the original String.
  • equals(String anotherString): Compares two Strings for equality.

2.1. Example Usage

These methods are essential for performing basic operations on Strings.

3. String Concatenation

String concatenation is the process of joining two or more strings together. This can be done using the + operator or the concat() method:

Both approaches will produce the output “John Doe”.

4. String Immutability

As mentioned earlier, Strings in Java are immutable. This means that once a String object is created, it cannot be modified. Any modification operations, such as concatenation or replacement, create a new String object. For example:

Here, the original String remains unchanged, and a new String with the concatenated value is created.

Let’s go through the provided example code to see some basic String operations in action.

Code

Code Explanation

  • String var1 = “Chaand \u00f1”; initializes var1 with the string “Chaand ñ”.
  • String var2 = “100”; sets var2 to a numeric string “100”.
  • int var3 = 10; initializes an integer variable var3.
  • //System.out.println(Integer.parseInt(var2)+10); is a commented line that would parse var2 to an integer and add 10.
  • System.out.println(var1); prints var1.

Output and Explanation

The output demonstrates how Unicode characters can be included in strings and how strings are displayed in Java.

Conclusion

Strings are fundamental to programming in Java, providing powerful methods for text manipulation. By understanding their properties and common operations, you can effectively use Strings in various applications. Mastering Strings is a critical step in your journey as a Java developer.