Java String (con esempi)

In questo tutorial, impareremo a conoscere le Java String, come crearle e vari metodi di String con l'aiuto di esempi.

In Java, una stringa è una sequenza di caratteri. Ad esempio, "ciao" è una stringa contenente una sequenza di caratteri "h", "e", "l", "l" e "o".

Usiamo le virgolette doppie per rappresentare una stringa in Java. Per esempio,

 // create a string String type = "Java programming";

Qui abbiamo creato una variabile stringa denominata type. La variabile viene inizializzata con la stringa Java Programming.

Nota : le stringhe in Java non sono tipi primitivi (come int, char, ecc). Invece, tutte le stringhe sono oggetti di una classe predefinita denominata String.

E tutte le variabili stringa sono istanze della Stringclasse.

Esempio: creare una stringa in Java

 class Main ( public static void main(String() args) ( // create strings String first = "Java"; String second = "Python"; String third = "JavaScript"; // print strings System.out.println(first); // print Java System.out.println(second); // print Python System.out.println(third); // print JavaScript ) )

Nell'esempio precedente, abbiamo creato tre stringhe denominate prima, seconda e terza. Qui stiamo creando direttamente stringhe come i tipi primitivi.

Tuttavia, esiste un altro modo per creare stringhe Java (utilizzando la newparola chiave). Lo impareremo più avanti in questo tutorial.

Operazioni su stringhe Java

Java String fornisce vari metodi per eseguire diverse operazioni sulle stringhe. Esamineremo alcune delle operazioni sulle stringhe comunemente usate.

1. Ottieni la lunghezza di una stringa

Per trovare la lunghezza di una stringa, utilizziamo il length()metodo String. Per esempio,

 class Main ( public static void main(String() args) ( // create a string String greet = "Hello! World"; System.out.println("String: " + greet); // get the length of greet int length = greet.length(); System.out.println("Length: " + length); ) )

Produzione

Stringa: ciao! Lunghezza mondiale: 12

Nell'esempio precedente, il length()metodo calcola il numero totale di caratteri nella stringa e lo restituisce. Per saperne di più, visita Java String length ().

2. Unisci due stringhe

Possiamo unire due stringhe in Java usando il concat()metodo. Per esempio,

 class Main ( public static void main(String() args) ( // create first string String first = "Java "; System.out.println("First String: " + first); // create second String second = "Programming"; System.out.println("Second String: " + second); // join two strings String joinedString = first.concat(second); System.out.println("Joined String: " + joinedString); ) )

Produzione

 Prima stringa: Java Seconda stringa: Programmazione Stringa unita: Programmazione Java

Nell'esempio sopra, abbiamo creato due stringhe denominate prima e seconda. Notare la dichiarazione,

 String joinedString = first.concat(second);

Qui, il concat()metodo unisce il primo e il secondo e lo assegna alla variabile joinString.

Possiamo anche unire due stringhe usando l' +operatore in Java. Per saperne di più, visita Java String concat ().

3. Confronta due stringhe

In Java, possiamo fare confronti tra due stringhe utilizzando il equals()metodo. Per esempio,

 class Main ( public static void main(String() args) ( // create 3 strings String first = "java programming"; String second = "java programming"; String third = "python programming"; // compare first and second strings boolean result1 = first.equals(second); System.out.println("Strings first and second are equal: " + result1); // compare first and third strings boolean result2 = first.equals(third); System.out.println("Strings first and third are equal: " + result2); ) )

Produzione

 La prima e la seconda stringa sono uguali: true La prima e la terza stringa sono uguali: false

Nell'esempio precedente, abbiamo creato 3 stringhe denominate prima, seconda e terza. Qui stiamo usando il equal()metodo per verificare se una stringa è uguale a un'altra.

Il equals()metodo controlla il contenuto delle stringhe mentre le confronta. Per saperne di più, visita Java String equals ().

Nota : possiamo anche confrontare due stringhe utilizzando l' ==operatore in Java. Tuttavia, questo approccio è diverso dal equals()metodo. Per saperne di più, visita Java String == vs equals ().

Metodi di Java String

Oltre a quelli menzionati sopra, in Java sono presenti vari metodi di stringa. Ecco alcuni di questi metodi:

Metodi Descrizione
sottostringa () restituisce la sottostringa della stringa
sostituire() sostituisce il vecchio carattere specificato con il nuovo carattere specificato
charAt () restituisce il carattere presente nella posizione specificata
getBytes () converte la stringa in una matrice di byte
indice di() restituisce la posizione del carattere specificato nella stringa
Paragonare a() confronta due stringhe nell'ordine del dizionario
trim () rimuove tutti gli spazi bianchi iniziali e finali
formato() restituisce una stringa formattata
Diviso() spezza la stringa in un array di stringhe
toLowerCase () converte la stringa in minuscolo
toUpperCase () converte la stringa in maiuscolo
valore di() restituisce la rappresentazione di stringa dell'argomento specificato
toCharArray () converte la stringa in un chararray

Carattere di fuga in Java Strings

Il carattere di escape viene utilizzato per eseguire l'escape di alcuni dei caratteri presenti all'interno di una stringa.

Supponiamo di dover includere virgolette doppie all'interno di una stringa.

 // include double quote String example = "This is the "String" class";

Since strings are represented by double quotes, the compiler will treat "This is the " as the string. Hence, the above code will cause an error.

To solve this issue, we use the escape character in Java. For example,

 // use the escape character String example = "This is the "String " class.";

Now escape characters tell the compiler to escape double quotes and read the whole text.

Java Strings are Immutable

In Java, strings are immutable. This means, once we create a string, we cannot change that string.

To understand it more deeply, consider an example:

 // create a string String example = "Hello! ";

Here, we have created a string variable named example. The variable holds the string "Hello! ".

Now suppose we want to change the string.

 // add another string "World" // to the previous tring example example = example.concat(" World");

Here, we are using the concat() method to add another string World to the previous string.

It looks like we are able to change the value of the previous string. However, this is not true.

Let's see what has happened here,

  1. JVM takes the first string "Hello! "
  2. creates a new string by adding "World" to the first string
  3. assign the new string "Hello! World" to the example variable
  4. the first string "Hello! " remains unchanged

Creating strings using the new keyword

So far we have created strings like primitive types in Java.

Since strings in Java are objects, we can create strings using the new keyword as well. For example,

 // create a string using the new keyword String name = new String("Java String");

In the above example, we have created a string name using the new keyword.

Here, when we create a string object, the String() constructor is invoked. To learn more about constructor, visit Java Constructor.

Note: The String class provides various other constructors to create strings. To learn more, visit Java String (official Java documentation).

Example: Create Java Strings using the new keyword

 class Main ( public static void main(String() args) ( // create a string using new String name = new String("Java String"); System.out.println(name); // print Java String ) )

Create String using literals vs new keyword

Now that we know how strings are created using string literals and the new keyword, let's see what is the major difference between them.

In Java, the JVM maintains a string pool to store all of its strings inside the memory. The string pool helps in reusing the strings.

While creating strings using string literals, the value of the string is directly provided. Hence, the compiler first checks the string pool to see if the string already exists.

  • Se la stringa esiste già , la nuova stringa non viene creata. Invece, il nuovo riferimento punta alla stringa esistente.
  • Se la stringa non esiste , viene creata la nuova stringa.

Tuttavia, durante la creazione di stringhe utilizzando la nuova parola chiave , il valore della stringa non viene fornito direttamente. Quindi la nuova stringa viene creata continuamente.

Articoli interessanti...