Strings in Java

Mannan Ul Haq
0
In Java, a String is an object of the 'java.lang.String' class, which represents a sequence of characters. Strings in Java are immutable, meaning once a String object is created, it cannot be changed. Every modification to a String results in a new String object being created.

String myString = "Hello World!";

In this example, `myString` is a string that holds the text "Hello World!".


Concatenation:

Concatenation is the process of appending one string to the end of another string. The `+` operator can be used for string concatenation.

String firstName = "John";
String lastName = "Doe";
String fullName = firstName + " " + lastName; // "John Doe"

The `concat()` method of the 'String' class can also be used for string concatenation.

String fullName = firstName.concat(" ").concat(lastName); // "John Doe"


Accessing Strings:

Individual characters in a 'String' can be accessed using the 'charAt()' method with the position (index) of the character in the string. Indexing in Java is zero-based, meaning the first character is at index 0.

String myString = "Hello, World!";
char firstChar = myString.charAt(0); // 'H'
char sixthChar = myString.charAt(5); // ','


String Length:

The length of a 'String' (the number of characters it contains) can be retrieved using the 'length()' property.

String myString = "Hello, World!";
int length = myString.length(); // 13


These are just some of the many ways to work with strings in Java. The `java.lang.String` class provides many more methods for string manipulation and querying, such as `substring`, `replace`, `split`, `trim`, `toLowerCase`, `toUpperCase`, and more.

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !