Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

The class String

Operations on data (operators and expressions) | Fundamentals of programming II | Write down and run this program on your computer | Write down and run this program on your computer | Introduction to objects | The first program | Types. Primitive types. | Types of variables. Declarations. | More on operators and expressions | Numeric promotions |


Читайте также:
  1. A BRIEF HISTORY OF STRING THEORY
  2. A conversation between a TEFL professor and a student after class
  3. A Feminist Classic from the Early '70s
  4. Act out the interviews in class.
  5. AGRONOMIC CLASSIFICATION OF FIELD CROPS
  6. A” CLASS – CATEGORIES AND RULES
  7. Banks’ typology / classification.


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

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:

 

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:

 

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.


Дата добавления: 2015-11-16; просмотров: 66 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Objects and references| Useful examples

mybiblioteka.su - 2015-2024 год. (0.006 сек.)