I denne opplæringen vil vi lære om Java Strings, hvordan du lager dem, og ulike metoder for String ved hjelp av eksempler.
I Java er en streng en sekvens av tegn. For eksempel er "hei" en streng som inneholder en sekvens av tegnene 'h', 'e', 'l', 'l' og 'o'.
Vi bruker doble anførselstegn for å representere en streng i Java. For eksempel,
// create a string String type = "Java programming";
Her har vi opprettet en strengvariabel med navnet type. Variabelen initialiseres med strengen Java Programming
.
Merk : Strings i Java er ikke primitive typer (som int
, char
osv). I stedet er alle strengene gjenstander fra en forhåndsdefinert klasse String
.
Og alle strengvariablene er forekomster av String
klassen.
Eksempel: Opprett en streng i 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 ) )
I eksemplet ovenfor har vi opprettet tre strenger med navnet første, andre og tredje. Her lager vi direkte strenger som primitive typer.
Imidlertid er det en annen måte å lage Java-strenger på (ved å bruke new
nøkkelordet). Vi lærer om det senere i denne opplæringen.
Java-strengoperasjoner
Java String gir forskjellige metoder for å utføre forskjellige operasjoner på strenger. Vi vil se på noen av de vanligste strengoperasjonene.
1. Få lengde på en streng
For å finne lengden på en streng bruker vi length()
metoden til strengen. For eksempel,
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); ) )
Produksjon
String: Hei! Verdens lengde: 12
I eksemplet ovenfor length()
beregner metoden det totale antallet tegn i strengen og returnerer den. Hvis du vil vite mer, kan du gå til Java-strenglengde ().
2. Bli med to strenger
Vi kan bli med i to strenger i Java ved hjelp av concat()
metoden. For eksempel,
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); ) )
Produksjon
Første streng: Java andre streng: programmering sluttet streng: Java programmering
I eksemplet ovenfor har vi opprettet to strenger som heter første og andre. Legg merke til uttalelsen,
String joinedString = first.concat(second);
Her concat()
kobles metoden til første og andre og tildeler den til joinedString-variabelen.
Vi kan også bli med i to strenger ved hjelp av +
operatøren i Java. For å lære mer, besøk Java String concat ().
3. Sammenlign to strenger
I Java kan vi sammenligne mellom to strenger ved hjelp av equals()
metoden. For eksempel,
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); ) )
Produksjon
Strenger første og andre er like: sanne Strenger første og tredje er like: falske
I eksemplet ovenfor har vi opprettet 3 strenger med navnet første, andre og tredje. Her bruker vi equal()
metoden for å sjekke om en streng er lik en annen.
Den equals()
metoden sjekker innholdet av strenger mens sammenligne dem. For å lære mer, besøk Java String er lik ().
Merk : Vi kan også sammenligne to strenger ved hjelp av ==
operatøren i Java. Denne tilnærmingen er imidlertid annerledes enn equals()
metoden. For å lære mer, besøk Java String == vs equals ().
Metoder for Java String
Foruten de som er nevnt ovenfor, er det forskjellige strengmetoder til stede i Java. Her er noen av disse metodene:
Metoder | Beskrivelse |
---|---|
substring () | returnerer strengenes understreng |
erstatte() | replaces the specified old character with the specified new character |
charAt() | returns the character present in the specified location |
getBytes() | converts the string to an array of bytes |
indexOf() | returns the position of the specified character in the string |
compareTo() | compares two strings in the dictionary order |
trim() | removes any leading and trailing whitespaces |
format() | returns a formatted string |
split() | breaks the string into an array of strings |
toLowerCase() | converts the string to lowercase |
toUpperCase() | converts the string to uppercase |
valueOf() | returns the string representation of the specified argument |
toCharArray() | converts the string to a char array |
Escape character in Java Strings
The escape character is used to escape some of the characters present inside a string.
Suppose we need to include double quotes inside a string.
// 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,
- JVM takes the first string "Hello! "
- creates a new string by adding "World" to the first string
- assign the new string "Hello! World" to the example variable
- 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.
- Hvis strengen allerede eksisterer , opprettes ikke den nye strengen. I stedet peker den nye referansen til den eksisterende strengen.
- Hvis strengen ikke eksisterer , opprettes den nye strengen.
Imidlertid, mens du oppretter strenger ved hjelp av det nye nøkkelordet , oppgis ikke verdien av strengen direkte. Derfor opprettes den nye strengen hele tiden.