Skip to content

Using objects

Java for AP CS A Lesson 2 2:21 English narration · English + 中文 subtitles burned in

space play · ←/→ 5s · j/l 10s · f fullscreen · ,/. speed

Chapters

Transcript
Here is the picture the whole lesson depends on. 这是整节课都要靠的那张图。
When you write String greeting equals Hello, the variable does not contain the letters. 当你写 String greeting = "Hello" 时, 这个变量里装的并不是那几个字母。
It holds a reference — an arrow pointing at an object that contains them. 它装的是一个"引用"——一个指向某个对象的箭头,字母在那个对象里。
Now write new String of Hello, and Java makes a second object. 现在再写 new String("Hello"),Java 就会造出"第二个"对象。
Same letters, different object, and a second arrow pointing at it. 同样的字母,不同的对象, 还有第二个箭头指向它。
And now the exam's favourite question answers itself. 于是考试最爱考的那个问题自己就有了答案。
Double equals asks: are these the same object? 双等号问的是:这两个是"同一个对象"吗?
Two different objects, so false. 是两个不同的对象,所以是 false。
Dot equals asks something else: do they hold the same letters? .equals 问的是另一件事:它们装的字母一样吗?
They do, so true. 一样,所以是 true。
Always use dot equals to compare Strings. 比较字符串永远用 .equals。
And compareTo answers a third question, giving a negative, zero or positive number for their order. 而 compareTo 回答的是第三个问题, 它给出一个负数、零或正数,表示它们的先后顺序。
The String method that loses the most marks is substring, because of its two indexes. 最容易丢分的字符串方法是 substring,问题出在它那两个索引上。
substring of zero and four gives comp — index zero is included, and index four is not included. substring(0, 4) 得到 "comp"—— 索引 0 是"包含"的,而索引 4 是"不包含"的。
Look at the cells and it is obvious. 看那几个格子,一目了然。
Three more you need: length gives eight, how many characters there are; charAt of zero gives c, one character at an index; and indexOf of put gives three, where it starts. 还有三个你要会: length() 得到 8,也就是有多少个字符; charAt(0) 得到 c,是某个索引上的一个字符; 而 indexOf("put") 得到 3,是它开始的位置。
Math is a class full of ready-made methods you call without making an object. Math 是一个装满现成方法的类,你不用造对象就能调用它。
Math dot abs of minus seven gives seven. Math.abs(-7) 得到 7。
Math dot pow of two and three gives eight — but look at the output, it prints eight point zero, because pow always gives a double. Math.pow(2, 3) 得到 8—— 但看输出,它打印的是 8.0, 因为 pow 永远给出 double。
Math dot sqrt is the same. Math.sqrt 也一样。
And Integer and Double are the object versions of int and double, which you will need the moment you meet ArrayList. 而 Integer 和 Double 是 int 和 double 的"对象版本", 你一碰到 ArrayList 就会需要它们。
Four things to take with you. 带走四点。
One: an object variable holds a reference to the object. 第一:对象变量里装的是指向对象的引用。
Two: double equals asks whether it is the same object. 第二:双等号问的是"是不是同一个对象"。
Three: dot equals asks whether the contents match. 第三:.equals 问的是"内容是不是一样"。
Four: substring includes the start index, not the end. 第四:substring 包含起始索引,不包含结束索引。
Now try the String methods in the tasks below. 现在去下面的题里试试这些字符串方法。

Log in or create account

IGCSE, A-Level & AP