String Features
2 min readNov 10, 2023
In Java, a String
is a class that represents a sequence of characters. It is one of the most commonly used classes in Java, and it is part of the java.lang
package, so you don't need to import anything special to use it.
Here are some basic operations and features related to String
in Java:
Creating Strings:
- You can create a string using the
String
literal or thenew
keyword.
String str1 = "Hello, World!";
String str2 = new String("Hello, World!");
String Concatenation:
- You can concatenate strings using the
+
operator.
String firstName = "Akash";
String lastName = "Sheikh";
String fullName = firstName + " " + lastName; // Results in "Akash Sheikh"
String Length:
- You can get the length of a string using the
length()
method.
String str = "Java";
int length = str.length(); // Results in 4
Accessing Characters:
- You can access individual characters in a string using the
charAt()
method.
char firstChar = str.charAt(0); // Gets the first character 'J'
Substring:
- You can extract a substring from a string using the
substring()
method.
String part = str.substring(1, 3); // Gets the substring from index 1 to 2 ("av")
String Comparison:
- You can compare strings using the
equals()
method for content comparison orcompareTo()
for lexicographical comparison.
String str1 = "Java";
String str2 = "Java";
boolean isEqual = str1.equals(str2); // true
Immutable Nature:
- Strings in Java are immutable, meaning their values cannot be changed after they are created. Operations that seem to modify strings actually create new string objects.
String Formatting:
- You can format strings using methods like
printf()
orformat()
for more complex formatting.
String formattedString = String.format("Hello, %s!", "World");
System.out.println(formattedString); // Outputs: "Hello, World!"
String Methods:
- The
String
class provides various methods for manipulating strings, such astoUpperCase()
,toLowerCase()
,trim()
, and more.
String str = " Java Programming ";
String trimmedStr = str.trim(); // Removes leading and trailing whitespaces
String upperCaseStr = str.toUpperCase();
String lowerCaseStr = str.toLowerCase();
These are just some basic features of the String
class in Java. There's much more you can do with strings in Java, depending on your specific needs.
-Akash Sheikh
Jr. Software Engineer at Nitto Digital Services and Analytics Ltd.