Using objects: String, Math, and wrappers · Menggunakan objek: String, Math, dan wrapper
Using objects
- An object is a value that knows how to do things. You call its methods with a dot
.. - A
Stringis an object.Math,Integer, andDoublegive you ready-made tools. - In this lesson you learn to make objects and use their methods.
Menggunakan objek
- Sebuah objek adalah nilai yang tahu bagaimana melakukan sesuatu. Anda memanggil method-nya dengan titik
.. - Sebuah
Stringadalah objek.Math,Integer, danDoublemenyediakan alat siap pakai. - Dalam pelajaran ini Anda belajar untuk membuat objek dan menggunakan method-nya.
Making objects with new
- Some objects are made with the keyword
newand a constructor. - A
Stringis special: you can write it directly with quotes, like"hi". - You can also make a separate
Stringobject withnew String("..."), but quotes are the normal way.
Membuat objek dengan new
- Beberapa objek dibuat dengan kata kunci
newdan constructor. - Sebuah
Stringitu spesial: Anda bisa menuliskannya langsung dengan tanda kutip, seperti"hi". - Anda juga bisa membuat objek
Stringterpisah dengannew String("..."), tetapi tanda kutip adalah cara normalnya.
public class Main {
public static void main(String[] args) {
String greeting = "Hello";
String copy = new String("Hello");
System.out.println(greeting);
System.out.println(copy);
}
}
String methods
s.length()— how many characters are ins.s.charAt(i)— the character at positioni(the first position is 0).s.substring(a, b)— the part fromaup to but not includingb.s.indexOf("x")— the first position of"x", or-1if not found.
Method String
s.length()— berapa banyak karakter dalams.s.charAt(i)— karakter pada posisii(posisi pertama adalah 0).s.substring(a, b)— bagian dariahingga tetapi tidak termasukb.s.indexOf("x")— posisi pertama dari"x", atau-1jika tidak ditemukan.
public class Main {
public static void main(String[] args) {
String word = "computer";
System.out.println(word.length()); // 8
System.out.println(word.charAt(0)); // c
System.out.println(word.substring(0, 4)); // comp
System.out.println(word.indexOf("put")); // 3
}
}
Comparing Strings
- Use
s.equals(other)to check if two Strings have the same letters. - Do not use
==to compare Strings — it can give the wrong answer. We learn why in lesson 3. s.compareTo(other)returns0when equal, a negative number ifscomes first in order, and a positive number if it comes later.
Membandingkan String
- Gunakan
s.equals(other)untuk memeriksa apakah dua String memiliki huruf yang sama. - Jangan gunakan
==untuk membandingkan String — dapat memberikan jawaban yang salah. Kita pelajari alasannya di lesson 3. s.compareTo(other)mengembalikan0jika sama, angka negatif jikasmuncul lebih dulu dalam urutan, dan angka positif jika muncul belakangan.
public class Main {
public static void main(String[] args) {
String a = "cat";
String b = "cat";
String c = "dog";
System.out.println(a.equals(b)); // true
System.out.println(a.equals(c)); // false
System.out.println(a.compareTo(c)); // negative: "cat" is before "dog"
}
}
Math methods
Mathholds math tools. You call them onMathitself, likeMath.abs(-5).Math.abs(x)— the size ofxwith no minus sign.Math.pow(b, e)—bto the powere(returns adouble).Math.sqrt(x)— the square root ofx(returns adouble).Math.random()— a randomdoublefrom0.0up to (not including)1.0.
Method Matematika
Mathmenyimpan alat matematika. Anda memanggilnya padaMathitu sendiri, sepertiMath.abs(-5).Math.abs(x)— ukuran darixtanpa tanda minus.Math.pow(b, e)—bdipangkatkane(mengembalikandouble).Math.sqrt(x)— akar kuadrat darix(mengembalikandouble).Math.random()— angka acakdoubledari0.0hingga (tidak termasuk)1.0.
public class Main {
public static void main(String[] args) {
System.out.println(Math.abs(-7)); // 7
System.out.println(Math.pow(2, 3)); // 8.0
System.out.println(Math.sqrt(9)); // 3.0
// Math.random() changes each run, so we do not print it here.
}
}
Wrappers and autoboxing
intanddoubleare simple types. Their object versions areIntegerandDouble.- Java can switch between them for you. This is called autoboxing.
Integer.parseInt("42")turns text into anint.Double.parseDouble("3.5")turns text into adouble.
Wrapper dan Autoboxing
intdandoubleadalah tipe sederhana. Versi objek mereka adalahIntegerdanDouble.- Java dapat beralih di antara keduanya untuk Anda. Ini disebut autoboxing.
Integer.parseInt("42")mengubah teks menjadiint.Double.parseDouble("3.5")mengubah teks menjadidouble.
public class Main {
public static void main(String[] args) {
Integer boxed = 10; // int -> Integer (autoboxing)
int back = boxed; // Integer -> int (unboxing)
int n = Integer.parseInt("42");
double d = Double.parseDouble("3.5");
System.out.println(back + n); // 52
System.out.println(d); // 3.5
}
}
Common mistakes
- Compare Strings (and other objects) with
.equals(), not==. Math.random()returns a value from0up to (but not including)1.
Kesalahan umum
- Bandingkan String (dan objek lainnya) dengan
.equals(), bukan==. Math.random()mengembalikan nilai dari0hingga (tetapi tidak termasuk)1.
Now you try
- Each task pre-fills the class skeleton — write your code inside main, or complete the method shown.
- Press Run to compile and run, then Check answer.
- Your code compiles and runs on the server, so even the first run is fast.
Sekarang Anda coba
- Setiap tugas telah mengisi kerangka class — tulis kode Anda di dalam main, atau lengkapi method yang ditampilkan.
- Tekan Jalankan untuk mengompilasi dan menjalankan, lalu Periksa jawaban.
- Kode Anda dikompilasi dan dijalankan di server, sehingga bahkan jalankan pertama kali pun cepat.
The String word is "programming". Print its length on the first line, then print the first 4 letters (use substring(0, 4)) on the second line. · String word bernilai "programming". Cetak panjangnya di baris pertama, lalu cetak 4 huruf pertama (gunakan substring(0, 4)) di baris kedua.
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Complete hypotenuse(double a, double b) so it returns the length of the longest side of a right triangle: the square root of a*a + b*b. Use Math.sqrt and Math.pow (or a*a). · Lengkapi hypotenuse(double a, double b) agar mengembalikan panjang sisi terpanjang dari segitiga siku-siku: akar kuadrat dari a*a + b*b. Gunakan Math.sqrt dan Math.pow (atau a*a).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.
Complete sameWord(String a, String b) so it returns true when the two Strings have the same letters, and false otherwise. Use .equals (not ==). · Lengkapi sameWord(String a, String b) agar mengembalikan true ketika dua String memiliki huruf yang sama, dan false sebaliknya. Gunakan .equals (bukan ==).
Click Run to see the output here. · Klik Jalankan untuk melihat output di sini.