Using objects: String, Math, and wrappers · Usando objetos: String, Math y envolventes
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.
Usando objetos
- Un objeto es un valor que sabe cómo realizar acciones. Se llaman sus métodos con un punto
.. - Una
Stringes un objeto.Math,IntegeryDoublete ofrecen herramientas predefinidas. - En esta lección aprenderás a crear objetos y usar sus métodos.
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.
Creación de objetos con new
- Algunos objetos se crean con la palabra clave
newy un constructor. - Una
Stringes especial: puedes escribirla directamente entre comillas, como"hi". - También puedes crear un objeto
Stringseparado connew String("..."), pero usar comillas es la forma habitual.
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étodos de String
s.length()— cuántos caracteres hay ens.s.charAt(i)— el carácter en la posicióni(la primera posición es 0).s.substring(a, b)— la parte desdeahasta (pero sin incluir)b.s.indexOf("x")— la primera posición de"x", o-1si no se encuentra.
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.
Comparación de Strings
- Usa
s.equals(other)para verificar si dos Strings tienen las mismas letras. - No uses
==para comparar Strings — puede dar una respuesta incorrecta. Aprendemos por qué en la lección 3. s.compareTo(other)devuelve0cuando son iguales, un número negativo sisva primero alfabéticamente, y un número positivo si va después.
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étodos Math
Mathcontiene herramientas matemáticas. Se llaman sobre el propioMath, comoMath.abs(-5).Math.abs(x)— el tamaño dexsin signo menos.Math.pow(b, e)—belevado a la potenciae(devuelve undouble).Math.sqrt(x)— la raíz cuadrada dex(devuelve undouble).Math.random()— undoublealeatorio desde0.0hasta (sin incluir)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.
Clases wrapper y autoboxing
intydoubleson tipos simples. Sus versiones como objetos sonIntegeryDouble.- Java puede cambiar automáticamente entre ellos. Esto se llama autoboxing.
Integer.parseInt("42")convierte texto aint.Double.parseDouble("3.5")convierte texto adouble.
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.
Errores comunes
- Compara Strings (y otros objetos) con
.equals(), no con==. Math.random()devuelve un valor desde0hasta (sin incluir)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.
Ahora tú practica
- Cada tarea prellena la estructura de la clase — escribe tu código dentro de main, o completa el método mostrado.
- Presiona Run para compilar y ejecutar, luego Check answer.
- Tu código se compila y ejecuta en el servidor, por lo que incluso la primera vez es rápida.
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 cadena word es "programming". Imprime su longitud en la primera línea, luego imprime las primeras 4 letras (usa substring(0, 4)) en la segunda línea.
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
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 · y Math.pow (or a*a). · Completa hypotenuse(double a, double b) para que devuelva la longitud del lado más largo de un triángulo rectángulo: la raíz cuadrada de a*a + b*b. Usa Math.sqrt y Math.pow (o a*a).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.
Complete sameWord(String a, String b) so it returns true when the two Strings have the same letters, and false otherwise. Use .equals (not ==). · Completa sameWord(String a, String b) para que devuelva true cuando las dos cadenas tengan las mismas letras, y false en caso contrario. Usa .equals (no ==).
Click Run to see the output here. · Haz clic en Ejecutar para ver la salida aquí.