Рядок Java (з прикладами)

У цьому підручнику ми дізнаємося про Java Strings, як їх створювати та різні методи String за допомогою прикладів.

У Java рядок - це послідовність символів. Наприклад, "привіт" - це рядок, що містить послідовність символів "h", "e", "l", "l" та "o".

Ми використовуємо подвійні лапки для представлення рядка в Java. Наприклад,

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

Тут ми створили рядкову змінну з іменем type. Змінна ініціалізується рядком Java Programming.

Примітка : Рядки в Java не є примітивними типами (як int, charі т.д.). Натомість усі рядки є об'єктами попередньо визначеного класу з іменем String.

І всі рядкові змінні є екземплярами Stringкласу.

Приклад: Створення рядка на 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 ) )

У наведеному вище прикладі ми створили три рядки з іменами first, second і third. Тут ми безпосередньо створюємо рядки на зразок примітивних типів.

Однак існує інший спосіб створення рядків Java (за допомогою newключового слова). Про це ми дізнаємось пізніше у цьому підручнику.

Рядові операції Java

Java String надає різні методи для виконання різних операцій над рядками. Ми розглянемо деякі загальновживані рядкові операції.

1. Отримати довжину рядка

Щоб знайти довжину рядка, ми використовуємо length()метод String. Наприклад,

 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); ) )

Вихідні дані

Рядок: Привіт! Довжина світу: 12

У наведеному вище прикладі length()метод обчислює загальну кількість символів у рядку і повертає його. Щоб дізнатися більше, відвідайте Java String length ().

2. Об’єднайте дві струни

Ми можемо об’єднати два рядки в Java, використовуючи concat()метод. Наприклад,

 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); ) )

Вихідні дані

 Перший рядок: Java Другий рядок: Програмування Приєднаний рядок: Програмування Java

У наведеному вище прикладі ми створили два рядки з іменами first і second. Зверніть увагу на заяву,

 String joinedString = first.concat(second);

Тут ми concat()приєднуємо метод перший і другий і призначаємо його змінній joinString.

Ми також можемо об’єднати два рядки, використовуючи +оператор на Java. Щоб дізнатись більше, відвідайте Java String concat ().

3. Порівняйте дві струни

У Java ми можемо проводити порівняння двох рядків за допомогою equals()методу. Наприклад,

 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); ) )

Вихідні дані

 Рядки перший і другий рівні: true Рядки перший і третій рівні: false

У наведеному вище прикладі ми створили 3 рядки з іменами first, second і third. Тут ми використовуємо equal()метод, щоб перевірити, чи однаковий рядок дорівнює іншому.

У equals()методі перевіряє вміст рядків, порівнюючи їх. Щоб дізнатись більше, відвідайте Java String equals ().

Примітка : Ми також можемо порівняти два рядки, використовуючи ==оператор у Java. Однак цей підхід відрізняється від equals()методу. Щоб дізнатись більше, відвідайте Java String == vs equals ().

Методи Java String

Окрім згаданих вище, у Java існують різні рядкові методи. Ось деякі з цих методів:

Методи Опис
підрядок () повертає підрядок рядка
replace () замінює вказаний старий символ вказаним новим символом
charAt () повертає символ, присутній у вказаному місці
getBytes () перетворює рядок у масив байтів
indexOf () повертає позицію вказаного символу в рядку
compareTo () порівнює два рядки в порядку словника
обрізати () видаляє будь-які пробіли, що ведуть і закінчуються
формат () повертає відформатований рядок
розділити () розбиває рядок на масив рядків
toLowerCase () перетворює рядок у малу літеру
toUpperCase () перетворює рядок у верхній регістр
valueOf () повертає рядкове представлення зазначеного аргументу
toCharArray () перетворює рядок у charмасив

Втеча символу в Java Strings

Символ втечі використовується для виходу з деяких символів, що знаходяться всередині рядка.

Припустимо, нам потрібно включити подвійні лапки всередину рядка.

 // 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.

  • Якщо рядок уже існує , новий рядок не створюється. Натомість нове посилання вказує на існуючий рядок.
  • Якщо рядок не існує , створюється новий рядок.

Однак під час створення рядків з використанням нового ключового слова значення рядка прямо не надається. Отже, новий рядок створюється весь час.

Цікаві статті...