In this tutorial we will learn how to work with strings in Java. Strings, which are so widely used in programming, are a sequence of characters. In the Java programming language, strings are an object. The Java platform provides a class
String
for creating and manipulating strings.
Creating Strings
The simplest way to create a string looks like this:
String greeting = "Hello world!";
In this case, “Hello World!” is a string literal (i.e. a constant) consisting of a sequence of characters enclosed in quotation marks. Whenever the compiler encounters a string literal, it creates an object of type String
with a value, in our case, "Hello World!". Like any other object, a string can be created using the keyword new
. The class String
has three constructors that allow you to create an object using different sources, such as a character array .
char[] helloArray = {'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println(helloString);
The last line of the example will print hello to the screen . The class String
is immutable, so once we create an object, we cannot change it. Some methods that we will look at below can fix this. Because String
immutable, these methods create and return a new string containing the result of the operation.
Java string length
Methods for obtaining information about a string are called access methods. One of these methodslength()
. It returns the number of characters in the string. In the following example len
it will be 17:
String palindrome = "Dont saw I saw Tod";
int len = palindrome.length();
The variable palindrome
contains a palindrome, i.e. a word or sentence that reads the same both ways. Let's write a small program that will reverse a palindrome. We will use the method charAt(i)
, which returns the i -th character of the string, starting with 0
.
public class StringDemo {
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
char[] tempCharArray = new char[len];
char[] charArray = new char[len];
//создадим из строки
// массив символов
for (int i = 0; i < len; i++) {
tempCharArray[i] =
palindrome.charAt(i);
}
// перевернем массив символов
for (int j = 0; j < len; j++) {
charArray[j] =
tempCharArray[len - 1 - j];
}
String reversePalindrome =
new String(charArray);
System.out.println(reversePalindrome);
}
}
The program will print
doT saw I was toD
In order to reverse a string, we first created an array of characters from the string (the first loop), then created a new array into which we wrote the inverted first array, then created a new string. The class String
contains a method getChars()
that returns an array of characters, so the first loop can be replaced with the line:
palindrome.getChars(0, len, tempCharArray, 0);
String concatenation
The classString
implements a method for concatenating two strings:
string1.concat(string2);
This code will return a new string containing string1
and appended to it string2
. You can also use this method with string literals:
"My name is ".concat("Rumplestiltskin");
Most often, strings are joined using the “ +
” operator, example:
"Hello," + " world" + "!"
The result will be the string “ Hello, world!” " The " +
" operator is widely used to display information, for example:
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
The code will output " Dot saw I was Tod ". Such concatenation can be used in conjunction with any other objects. For objects that are not strings, the method will be called toString()
, which converts them to strings. Setting the string output format We have already looked at methods printf()
when format()
we formatted the output of numbers. The class String
has a similar method that returns a string. Using a static method format()
it is possible to create a stock template that can be reused, for example instead:
System.out.printf ("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, "
"and the string is %s",
floatVar, intVar, stringVar);
you can use this code:
String fs;
fs = String.format("The value of the float " +
"variable is %f, while " +
"the value of the " +
"integer variable is %d, " +
" and the string is %s",
froatVar, intVar, stringVar);
System.out.println(fs);
That's all! :) Link to source: Strings in Java
GO TO FULL VERSION