Using objects: String, Math, and wrappers · Utilisation d'objets : String, Math et wrappers
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.
Utiliser des objets
- Un objet est une valeur qui sait comment faire des choses. Vous appelez ses méthodes avec un point
.. - Un
Stringest un objet.Math,IntegeretDoubleoffrent des outils prêts à l'emploi. - Dans cette leçon, vous apprenez à créer des objets et à utiliser leurs méthodes.
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.
Créer des objets avec new
- Certains objets sont créés avec le mot-clé
newet un constructeur. - Un
Stringest spécial : vous pouvez l'écrire directement avec des guillemets, comme"hi". - Vous pouvez aussi créer un objet
Stringséparé avecnew String("..."), mais les guillemets sont la méthode normale.
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.
Méthodes String
s.length()— combien de caractères y a-t-il danss.s.charAt(i)— le caractère à la positioni(la première position est 0).s.substring(a, b)— la partie deajusqu'à mais sans inclureb.s.indexOf("x")— la première position de"x", ou-1si non trouvé.
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.
Comparer des Strings
- Utilisez
s.equals(other)pour vérifier si deux Strings ont les mêmes lettres. - N'utilisez pas
==pour comparer des Strings — cela peut donner la mauvaise réponse. Nous verrons pourquoi dans la leçon 3. s.compareTo(other)retourne0quand c'est égal, un nombre négatif sisvient en premier dans l'ordre, et un nombre positif s'il vient plus tard.
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.
Méthodes mathématiques
Mathcontient des outils mathématiques. Vous les appelez surMathlui-même, commeMath.abs(-5).Math.abs(x)— la taille dexsans signe moins.Math.pow(b, e)—bà la puissancee(retourne undouble).Math.sqrt(x)— la racine carrée dex(retourne undouble).Math.random()— un nombre aléatoiredoublede0.0jusqu'à (sans inclure)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 et autoboxing
intetdoublesont des types simples. Leurs versions objets sontIntegeretDouble.- Java peut passer de l'un à l'autre automatiquement pour vous. C'est appelé autoboxing.
Integer.parseInt("42")convertit du texte en unint.Double.parseDouble("3.5")convertit du texte en undouble.
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.
Erreurs courantes
- Comparez des Strings (et autres objets) avec
.equals(), pas==. Math.random()renvoie une valeur comprise entre0et (mais non inclus)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.
À vous maintenant
- Chaque tâche préremplit le squelette de classe — écrivez votre code dans main, ou complétez la méthode montrée.
- Appuyez sur Exécuter pour compiler et exécuter, puis sur Vérifier la réponse.
- Votre code compile et s'exécute sur le serveur, donc même la première exécution est rapide.
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. · La String word est "programming". Affichez sa longueur sur la première ligne, puis affichez les 4 premières lettres (utilisez substring(0, 4)) sur la deuxième ligne.
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
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 · et Math.pow (or a*a). · Complétez hypotenuse(double a, double b) pour qu'elle retourne la longueur du plus grand côté d'un triangle rectangle : la racine carrée de a*a + b*b. Utilisez Math.sqrt et Math.pow (ou a*a).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.
Complete sameWord(String a, String b) so it returns true when the two Strings have the same letters, and false otherwise. Use .equals (not ==). · Complétez sameWord(String a, String b) pour qu'elle retourne true lorsque les deux Strings ont les mêmes lettres, et false sinon. Utilisez .equals (pas ==).
Click Run to see the output here. · Cliquez sur Exécuter pour voir le résultat ici.