THE STRING CLASS

java-logoThe String class after primitive types is one of the most widely used classes ever. It is located in the java.lang package, one of the default packages that does not need to be imported. It also admits the creation of instances with the literal format, consisting on a pair of double quotes. Since String is an object a string can also be created with the new operator. The figure highlights all the ways in which an instance of such a class can be created.

Creare istanze

The second special feature of strings is that they are immutable objects. To understand this concept, let us return to reference types. Let’s look at an example.

CC

Even though the attributes are the same the objects in the figure are still distinct. When we use strings, the Java Runtime manages a particular area of memory called the String Pool within which the various strings are contained.

String Pool

If two string objects have the same content, the two references are made to point to the same memory area. When we create a string Java checks in the String Pool that the string value is not already present. If present for a matter of efficiency the same reference is used. If we modify a string the verification is done again and if the object does not exist memory is allocated to hold the new string.

istanze

For this reason, the strings are immutable, that is, their values cannot be altered; when a new character set is assigned, a new instance of String is created in a different memory area.

METHODS OF THE STRING CLASS

Let us review some methods of the String class (see figure).

Metodi 1

Other methods of the String class (see figure).

Metodi 2

USE COMMAND LINE ARGUMENTS

We will complete the knowledge of the main now that we know about Arrays and the String class.

Metodo main

When the main method is present in a class, it becomes executable, that is, it produces bytecode that the JVM can directly execute from the terminal. Program execution starts exactly inside the main method. It has to be public, this is because it has to be visible outside the class since the JVM has to process it. It is a class method (static) this is because the JVM should not need to instantiate the class that contains it. Nothing returns void, when they end the instructions in the main the program terminates. The main method takes an Array of strings as an input parameter, and this Array is called args. It contains the values passed from the terminal to the main method.

For Each
Parametri dalla command line

LINKS TO PREVIOUS POSTS

THE JAVA LANGUAGE

LINK TO CODE ON GITHUB

GITHUB

EXECUTION OF THE EXAMPLE CODE

  • Download the code from GITHUB, launch the JAR file with the following command in Visual Studio Code, locating in the directory containing the JAR.

        java -jar –enable-preview CorsoJava.jar

  • Or run the main found in the file CorsoJava.java.