Java String

 

String is use to store text such as a word, a sentence, a story, a file, or anything that is not of integer.

String is a collection or sequence of characters. In java we use double quotes instead of single quotes to create string.

There are two ways to create a String:
1. String literal
2. new keyword

String literal

String name = "Folau";
// don't do this, '' or single quotes are for chars
String firstName = 'Folau';

String in immutable which means once you have created a string you could no longer change its value. However, a variable as a String reference can be changed to point to some other string value. Remember that everytime you change or edit a string you are creating a new string value.

String name = "Folau";
name = "Lisa";
// In memory we did not overide "Folau" to "Lisa". We created 
// a new String "Lisa" and point name to it. Now we have two strings
// in memory "Folau" and "Lisa"
String name = "Folau";
String firstName = "Folau";
// if we want to use a differenct object in memory then we must use the new keyword to create our string.

Creating String with the new keyword
String name = new String(“Folau”);

String Methods

String length()
To find out the length of a String, use the length() method.

String name = "Folau";
int nameLength = name.length();
System.out.println("The length your name: " + nameLength);// 5

String indexOf()
To find out if a string contains another string, use indexOf(). IndexOf() returns the position of the first occurrence of the searching string.

String name = "Folau";
String searchingString = "lau";
int position = name.indexOf("lau");
System.out.println("position: " + position);// 2

String concat()
To add or put two Strings together, there are two ways to do it. First you can use the + operator

String firstName = "Folau";
String lastName = "Kaveinga";
String name = firstName + " " + lastName;
System.out.println("name: " + name);// Folau Kaveinga

and second we use the concat() method

String firstName = "Folau ";
String lastName = "Kaveinga";
String name = firstName.concat(lastName);
System.out.println("name: " + name);// Folau Kaveinga

Using of + operator with String
adding two strings together will concatenate.

String a = "Folau ";
String b = "Kaveinga";
String c = a + b;
System.out.println("c: " + c);// Folau Kaveinga

Using of + operator with integer
adding two numbers together will add or sum.

int a = 5;
int b = 10;
int c = a + b;
System.out.println("c: " + c);// 15

String replace()
replace(char oldChar, char newChar) – it replaces the oldChar with the newChar.

String sentence = "My name is Folau";
String newSentence = sentence.replace("a","o");
System.out.println("newSentence: " + newSentence);// My nome is Folou

String toLowerCase()
toLowerCase converts all characters within a string to lowercase.

String name = "FOLAU";
String lowercaseName = name.toLowerCase();
System.out.println("lowercaseName: " + lowercaseName);// folau

String toUpperCase()
toUpperCase coverts all characters within a string to uppercase.

String name = "folau";
String uppercaseName = name.toUpperCase();
System.out.println("uppercaseName: " + uppercaseName);// FOLAU

String join(String delimeter, String … elements)
join() joins strings of elements together with delimeter

String sentence = String.join("^","I","have","to","do","this");
System.out.println("sentence: " + sentence);// I^have^to^do^this

String charAt()

To extract a single character from a String, you can refer directly to an individual character via the charAt( ) method.

char charAt(int where)

where is the index of the character that you want to obtain. The value of where must be nonnegative and specify a location within the string.

charAt( ) returns the character at the specified location.

String toCharArray()

If you want to convert all the characters in a String object into a character array, the easiest way is to call toCharArray( ). It returns an array of characters for the entire string.

char[ ] toCharArray( )

String equals vs ==

It is important to understand that the equals( ) method and the == operator perform two different operations. The equals( ) method compares the characters inside a String object. The == operator compares two object references to see whether they refer to the same instance. 

String compareTo()

Often, it is not enough to simply know whether two strings are identical. For sorting applications, you need to know which is less than, equal to, or greater than the next. A string is less than another if it comes before the other in dictionary order. A string is greater than another if it comes after the other in dictionary order. The method compareTo( ) serves this purpose. It is specified by the Comparable<T> interface, which String implements.

int compareTo(String str)

The result of the comparison is returned and is interpreted as shown here.

If you want to ignore case differences when comparing two strings, use compareToIgnoreCase( )

String indexOf( )

Searches for the first occurrence of a character or substring.

String lastIndexOf( )

Searches for the last occurrence of a character or substring.

Text Block

Introduced as a preview feature in Java 13 and then standardized in Java 15, Text Blocks aim to simplify the task of writing and managing multi-line string literals in Java. They are particularly useful when working with JSON, SQL, XML, or any other multi-line textual data.

Basics of Text Blocks:

A text block is denoted by three double-quote marks (""") and allows for multi-line strings without the need for most escape sequences.

All white spaces and new lines within a text block are preserved. If you want to remove the newline at the end of a line, you can use the line continuation character (\)

Within a text block, you can use the standard escape sequences like \n, \t, and \". However, you no longer need to escape every double-quote in the string, only the sequence of three double-quotes (""") if they appear in the content:

String bio = """

        Paul and Silas then travel by night to Berea. In Berea, they find that the
        Jews are more noble-minded than those in Thessalonica, as they receive the message with
        great eagerness and examine the Scriptures daily to see if what Paul says is true.
        Many Bereans believe, including several influential Greek women and men.

        However, when the Jews in Thessalonica learn that Paul is preaching in Berea,
        they come there to agitate the crowds. As a result, the believers send Paul to the coast for his safety,
        while Silas and Timothy remain in Berea.
                        """;

System.out.println("bio: " + bio);
Benefits of Text Blocks:
  1. Readability: Text Blocks improve the readability of your code when dealing with large multi-line strings.
  2. Less Error-Prone: Reduces the chances of errors, especially when embedding strings like JSON, XML, or SQL in your Java code.
  3. Cleaner Code: Reduces the need for most escape sequences, making the code look cleaner.



Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *