Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Lecture 1.docx
Скачиваний:
1
Добавлен:
01.07.2025
Размер:
704 Кб
Скачать
☆

6.2. The class String

Of course, strings are objects of the class String. Thus all that was said about objects and references pertains to objects of the class String too. However, operations on strings are very common, so to make programming easier the compiler facilitates handling strings in several ways. Unfortunately, this introduces some confusion too. Objects of the class String may be created similarly to objects of other classes. But the compiler helps us here with the following trick: instead of writing: String s = new String("Abc"); we may write: String s = "Abc"; As a result

  • A new object of the class String representing the string "Abc" is created and

  • a reference to this object is stored into the variable s.

Thus, creating objects of the class String we do not have to use the expression new. Another facility supplied by the compiler is the + operator used for concatenation of strings. For example:

String s1 = "All work and no play";

String s2 = " makes Jack a dull boy";

String s3;

s3 = s1 + s2;

acts as follows:

  • the expression s1 + s2 creates a new object of the class String representing the concatenation of the strings denoted by s1 and s2.

  • a reference to the newly created object is stored to the variable s3.

  • Now s3 represents the string "All work and no play makes Jack a dull boy".

Moreover, the + operator allows appending data of other types to strings (numbers or even objects). For example:

String s1 = "Jack ";

String s2 = "is ";

String s3;

s3 = s1 + s2 + 3 + " years old";

Now the variable s3 represents the string "Jack is 3 years old". Of course, we may use a variable of type int instead of literal 3. int years = 3; ... s3 = s1 + s2 + years + " years old"; The variable years as well as the literal 3 in the concatenation expression are of the type int. Other numeric values (of type float, double and other) may be used as well. If the right operand of concatenation operator (+) is a reference to an object of some class, then this object is converted to a string and appended to the left operand (a string). Again, it is a compiler's trick, but the string representation of an object is defined by the class of the object. We will learn later how to achieve this and how to use such a facility. As an example consider: Date now = new Date(); String s = "Now is: " + now; Here an object of the class Date is created. It stores the current date and time in binary form. After the concatenation the variable s refers to a string describing the current date and time: "Now is: Mon Jul 01 05:55:25 CEST 2002".

The operator + is used as string concatenation operator only if at least one of its arguments is of type String.

Operations on strings involve references, so special care should be taken by comparisons:

Equality operators (== and !=) applied to variables denoting objects compare references not objects themselves.

Thus the following program:

String s1 = "Jo";

String s2 = "hn";

String s3 = s1 + s2;

String s4 = "John";

System.out.println(s3 + " " + s4);

if (s3 == s4) System.out.println("It is John");

else System.out.println("It is not John");

prints (contrary to all expectations): John John It is not John Here is the explanation of this peculiar behavior:

  • The object denoted by s3 represents the string "John".

  • Similarly, the object denoted by s4 represents another string "John".

  • But the result of s3 == s4 is false, because s3 and s4 refer to distinct objects (although they represent the same string).

  • However, it would be true if s3 and s4 referred to the same object.

Strings should not be compared using the equality operators == and !=.

Instead of equality operators the method equals should be used.

The contents of two strings s1 and s2 can be tested for equality by the method invocation:

                s1.equals(s2)

The contents of a string s and a string literal can be compared similarly:                 s.equals(a_string_literal) If both strings contain the same sequence of characters, the result is true and false when they do not.

The next program demonstrates various details of operations on strings.

public class Strings1 {

public static void main(String[] args) {

String aString = "Weight ";

double w = 10.234;

System.out.println(aString + w + " kg");

String txt = aString + w + 10 + " kg";

System.out.println(txt); // why 10.23410?

txt = aString + (w + 10) + " kg";

System.out.println(txt); // why 20.234?

txt = aString + w * 10 + " kg"; // w*10 without braces ?..

System.out.println(txt); // ...ok, why?

String anotherString = "AnotherString";

anotherString = aString;

System.out.println(anotherString); // Why prints "Weight ", not "AnotherString"

txt = aString;

txt = txt + "of John ?";

System.out.println(txt);

System.out.println(aString); // Why does aString refer to "Weight "?

// and not to "Weight of John ?"

System.out.println( aString == anotherString ); // why true?

System.out.println( txt == aString ); // why false?

System.out.println( txt == "Weight of John ?"); // why false?

System.out.println( txt.equals("Weight of John ?") );// why true?

// something strange:

aString = "John";

System.out.println( aString == "John"); // true or false ???

}

}

Weight 10.234 kg Weight 10.23410 kg Weight 20.234 kg Weight 102.34 kg Weight Weight of John ? Weight true false false true true

The output of the program is displayed on the figure. Note that as an argument to the method println() an arbitrary expression can be given. We'll explain this phenomenon later. Analyze carefully the program answering the questions given as comments. The last part of the program demonstrates another Java aberration from simple rules. All string literals representing the same text refer to a single object. The instruction aString = "John"; creates new object representing the string "John". Consecutive calls to the literal "John" will refer to the created object (and not to some other object of the class String containing the string "John"; such an object will not be created again). Thus the result of the last test is true.

This property of the Java language should not be abused. The method equals should always be used for comparing strings.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]