The String class¶
The class called String
is a built into Java. It is used to represent character strings. The text in the form of String
can be declared in two ways:
- Using a letter, e.g., "`String'':
String myText = "This is a simple text."
- Using the keyword
new
:
String myText = new String("This is a simple text.")
The difference between the two approaches is that when creating a string using a letter, we allow Java to manage the created object, and when using the constructor we have control over the created instance ourselves. In practice, we should use the letter approach most often.
Immutability of String objects¶
The immutability
of String objects is that once created, an instance of the String
object will no longer change its value. The String
class does not have any method (e.g., setter) that can modify its value, so this construction is possible:
String text = "This is. "
text += "my text";
In the above example, we have created a new object with the value This is my text
and set the reference variable text
to it.
What gives us the immutability of String
objects?
- security - it is easier to protect against code modifications from outside, and the
String
class is secure in multi-threaded applications. - performance - the
String
class is often used as a key in data structures such as 'HashMap'. This means that once the value ofhashCode
is calculated it will not be recalculated, which significantly affects performance in an application. - String pool - multiple references can point to the same object thanks to the pool - a Java optimization mechanism that stores only one unique String value. This optimization allows for a significant reduction of the amount of text that needs to be stored.
The use of a String from the pool can be done by calling the intern
method on an instance of the String
type object, e.g:
String text1 = "This is a test";
String text2 = "This is a test";
String val1 = text1.intern(); // the value 'This is a test' is taken
String val2 = text2.intern(); // the value 'This is a test' is taken
System.out.print(val1.equals(val2)) // the true value will be returned
In the example above, the variables text1
and text2
will point to the same value in the String pool. The equals
method will return the value of true
because the values of both variables are the same - this method will be discussed later.
Text Concatenation¶
`The concatenation of
Strings is nothing more than the process of connecting them together. This can be easily done using the +
operator, as in the following example:
String text1 = "My name is ";
String text2 = "John Doe";
String finalText = text1 + text2;
The linking operation is done from left to right, so the value of the finalText
variable will be: My name is John Doe
. The concatenation can also be done by calling the concat
method on an instance of a String type object, e.g., the finalText
:
``java String text1 = "My name is "; String text2 = "John Doe"; String finalText = text1.concat(text2);
## Comparing two or more texts
To check if the two texts are identical, use the `equals` method. Example:
```java
String text1 = "Text to campare";
String text2 = "Text to campare";
System.out.print(text1.equals(text2)); // the value true will be displayed because both strings are identical
Let's not compare chains using the operator ==
. This is illustrated by the example below:
``java String text1 = "Text to campare"; String text2 = new String("Text to campare"); System.out.print(text1 == text2); // false !
The operator `===` can only check if both strings are stored in the same memory location, and in the above example they are not (strings are not shared).
## String class methods
The `String` class has several useful methods. Below are the most commonly used ones:
### length()
Returns the chain length, e.g:
```java
System.out.print("This is test value".length()); // a value of 18 is displayed
As you can see, white characters (in this case spaces) are also counted as chain characters.
toUpperCase() and toLowerCase()¶
Both of these methods change the string into a character string consisting of capital letters themselves and, in the second case, lower case letters. Example:
String testValue = "This is test value";
System.out.print(testValue.toUpperCase()); // the text 'THIS IS TEST VALUE' will be displayed
System.out.print(testValue.toLowerCase()); // the text 'this is test value' is displayed
indexOf()¶
The indexOf()
method returns the position of the first occurrence of the specified text in a string of characters (the counting is performed together with white characters, e.g. a space) - the position is counted from the value 0 (the first item). An example follows:
String testValue = "This is test value";
System.out.print(testValue.indexOf("is")); // value 2 will be displayed
replaceAll()¶
The replaceAll()
method allows to replace all occurrences of a given substring with another, e.g:
String text = "Hahahah! Funny joke!"
System.out.print(text.replaceAll("a", "o")); // the string 'Hohohohoh! Funny joke!'
substring()¶
The substring()
method allows to retrieve a substring, based on the initial (or final) index, e.g:
String text = "Example test";
text.substring(3); // will be returned String "mple test"
text.substring(2, 6); // will be returned String ampl
contains()¶
The contains()
method returns information whether a given String contains a specific string, e.g:
String text = "Example test";
System.out.println(text.contains("xam")); // true
System.out.println(text.contains("Test")); // false
trim(), isBlank() and isEmpty()¶
The trim()
method returns a String, which is the result of removing all white characters (such as spaces or tabs) from the beginning and end of a character string. The isEmpty()
method tells us if the String is empty. A similar information is obtained by calling the isBlank()
method, but unlike the isEmpty()
method, all white-space characters at the beginning and end of the string will be removed before this information is obtained, e.g., the isEmpty()
method.
System.out.println("\tsda"); // \t is a tab character, it will display " sda"
System.out.println("\tsda".trim()); // "sda"
System.out.println(" ".isEmpty()); // false
System.out.println(" \"T". isBlank(); // true
Standard input/output¶
Scanner - basic entrance¶
The Scanner
class is ideal for retrieving user input as well as the basic reading of the file. To read the data, an instance of an object of the type Scanner
must be created and the input stream System.in
must be specified as parameter. In the following example, we try to read the text line entered by the user:
Scanner scan = new Scanner(System.in);
String textLine = scan.nextLine(); // we loaded the line of text entered by the user here
// and we saved it in the textLine variable
The class Scanner
is included in the java.util
package, so it should be openly imported in our application. As an argument to the constructor, we have given the System.in
, i.e., the standard input stream (console) - another stream type can also be given here. The nextLine()
method stops the program from running until the user enters something in the console and confirms it with the enter key. It also returns the entire line typed by the user as a string of String
type characters.
In addition to the nextLine()
method, the Scanner
class offers a number of additional methods that allow you to read data of other types, such as
nextInt()
- reads another integernextDouble()
- reads another floating-point numbernextBoolean()
- reads another logical value
Standard output¶
Java has several basic methods for displaying data. The class System
is used for this. We have a few basic variants:
print()
- prints on the screen a given string or a numeric variable that it converts previously to theString
type, e.g.,System
:
int myNumber = 125;
System.out.print("This is a simple text."); // the following will be displayed: 'This is a simple text.
System.out.print(myNumber); // The number 125 will be displayed.
-
println()
- works the same way asprint()
by adding a new line character at the end -
printf()
- a method that can format the data in addition to writing it. Special conversion operators are used for this purpose. Here is a list of basic ones:- d - decimal integer
- e - floating point number in exponential notation
- f - floating-point number
- x - integer in hexadecimal system
- o - integer in the octal (octal) number system
- s - character string
- c - the sign
- b - logical value
Examples of how the printf()
method works:
System.out.printf("100.0 / 3.0 = %5.2f", 100.0 / 3.0); // the result will be a floating point number consisting of 5 characters and 2 digits after the decimal point
System.out.println();
System.out.printf("100 / 3 = %4d", 100 / 3); // the result will be an integer occupying 4 characters - the division will be rounded