So far I understand that both are different, but I'm a bit confused about when to use them or how to use them well. Thanks in advance.
So far I understand that both are different, but I'm a bit confused about when to use them or how to use them well. Thanks in advance.
casting consists of the conversion of similar (compatible) data types to each other, usually through inheritance. For example:
interface Mascota {
// contenido...
}
class Gato implements Mascota {
// contenido...
}
class Perro implements Mascota {
// contenido...
}
void prueba() {
Gato gato = new Gato();
Perro perro = new Perro();
// Ambos son mascotas, por tanto, se puede hacer casting a Mascota.
Mascota mascota1 = (Mascota) gato;
Mascota mascota2 = (Mascota) perro;
}
On the other hand, parsing consists of analyzing the format of a text statement, and obtaining information if the format is correct. For example:
String str1 = "123";
String str2 = "12t";
// No se producen excepciones debido a que el formato de 'str1' es correcto (es un número entero).
int n1 = Integer.parseInt(str1);
// Se producirá una excepción ya que 'str2' no tiene el formato esperado (número entero).
int n2 = Integer.parseInt(str2);
Another good example of parsing are the programming languages: the compiler or interpreter performs a grammar analysis (parsing) to check that the syntax is correct.