JAVA BASICS
Java String: text strings
String is used to store text. A String variable contains a sequence of characters written inside double quotes in Java code.
Creating a String variable
To store text, create a String variable and assign a value:
String pasisveikinimas = "Labas";
System.out.println(pasisveikinimas);String is not It is an object, so it has methods for examining and transforming text.
Text length
The method length() returns the string's character count. Spaces and punctuation are counted too.
String tekstas = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("Teksto ilgis: " + tekstas.length()); // 26Changing letter case
toUpperCase() converts text to uppercase, while toLowerCase() converts it to lowercase.
String tekstas = "Labas, pasauli";
System.out.println(tekstas.toUpperCase()); // LABAS, PASAULI
System.out.println(tekstas.toLowerCase()); // labas, pasauli These methods return a new string. The original String value stays unchanged because Java strings are
Searching text
The method indexOf() returns the starting index of the first matching character or text. Indices start at 0, and if no match is found it returns -1.
String tekstas = "Surask, kur yra žodis surask";
System.out.println(tekstas.indexOf("kur")); // 8
System.out.println(tekstas.indexOf("Java")); // -1Joining strings
Joining several strings is called concatenation. The simplest approach uses the operator +. Add any required spaces explicitly: Java does not add them automatically.
String vardas = "Jonas";
String pavarde = "Jonaitis";
String visasVardas = vardas + " " + pavarde;
System.out.println("Sveiki, " + visasVardas + "!");Larger programs can also join text with the method concat(), while repeated text changes usually use StringBuilder.
More about String
Text and numbers
Between numbers, + performs addition. If an expression encounters text first, subsequent values are joined as text. Parentheses let you specify that numbers should be added first.
int x = 10;
int y = 20;
System.out.println(x + y); // 30
System.out.println("Rezultatas: " + x + y); // Result: 1020
System.out.println("Rezultatas: " + (x + y)); // Result: 30Special characters
Some characters in text need a preceding backslash, \. These are called escape sequences ( escape sequences).
| Sequence | Result |
|---|---|
\" | Double quote |
\\ | Backslash |
\n | Newline |
\t | Tab |
\r | Carriage return |
String citata = "Ji pasakė: \"Labas!\"";
String kelias = "C:\\Java\\projektas";
String keliosEilutes = "Pirma eilutė\nAntra eilutė";
String suTabuliacija = "Vardas:\tJonas";
System.out.println(citata);
System.out.println(kelias);
System.out.println(keliosEilutes);