1. Comparando strings

Está tudo bem e bom. Mas você pode ver que as strings s1e s2são na verdade as mesmas, o que significa que elas contêm o mesmo texto. Ao comparar strings, como você diz ao programa para olhar não para os endereços dos Stringobjetos, mas para o seu conteúdo?

Para nos ajudar com isso, a classe Java Stringpossui o equalsmétodo. Chamando fica assim:

string1.equals(string2)
Comparando duas strings

Este método retorna truese as strings forem iguais e falsese não forem iguais.

Exemplo:

Código Observação
String s1 = "Hello";
String s2 = "HELLO";
String s3 = s1.toUpperCase();

System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s2.equals(s3));
// Hello
// HELLO
// HELLO

false // They are different
false // They are different
true // They are the same, even though the addresses are different

Mais exemplos:

Código Explicação
"Hello".equals("HELLO")
false
String s = "Hello";
"Hello".equals(s);
true
String s = "Hel";
"Hello".equals(s + "lo");
true
String s = "H";
(s + "ello").equals(s + "ello");
true

4
Tarefa
Java Syntax,  nível 4lição 6
Bloqueado
Minimum of two numbers
All search and sort algorithms are based on comparisons. You'll be able to handle these very soon, if you so desire. In the meantime, we suggest starting with something small: write a program to find the minimum of two numbers. Find it and then display it. And if the numbers are the same, display either of them.
4
Tarefa
Java Syntax,  nível 4lição 6
Bloqueado
Maximum of four numbers
Finding the maximum is an n-ary operation (an operation on n numbers) that returns the largest of several numbers. Never mind. We have no need for such definitions at the secret CodeGym center. We're here to learn how to write code. In this task, you need to use the keyboard to enter four numbers. Then determine the largest of them and display it on the screen.

2. Comparação de strings sem distinção entre maiúsculas e minúsculas

No último exemplo, você viu que a comparação produz . De fato, as cordas não são iguais. Mas..."Hello".equals("HELLO")false

Claramente, as strings não são iguais. Dito isso, seu conteúdo tem as mesmas letras e difere apenas no caso das letras. Existe alguma maneira de compará-los e desconsiderar o caso das letras? Ou seja, então isso rende ?"Hello".equals("HELLO")true

E a resposta a esta pergunta é sim. Em Java, o Stringtipo possui outro método especial: equalsIgnoreCase. Chamando fica assim:

string1.equalsIgnoreCase(string2)

O nome do método é traduzido aproximadamente como comparar, mas ignorar maiúsculas e minúsculas . As letras no nome do método incluem duas linhas verticais: a primeira é minúscula Le a segunda é maiúscula i. Não deixe que isso o confunda.

Exemplo:

Código Observação
String s1 = "Hello";
String s2 = "HELLO";
String s3 = s1.toUpperCase();

System.out.println(s1.equalsIgnoreCase(s2));
System.out.println(s1.equalsIgnoreCase(s3));
System.out.println(s2.equalsIgnoreCase(s3));
// Hello
// HELLO
// HELLO

true
true
true

8
Tarefa
Java Syntax,  nível 4lição 6
Bloqueado
Sorting three numbers
Planet Linear Chaos is populated by isomorphs. They are believed to have invented sorting algorithms. Everything in their heads is extremely well-ordered. They only issue planetary visas to people who know at least 7 sorting algorithms. Let's take our first step toward Linear Chaos: Read three numbers from the keyboard, put them in descending order, and then display them on the screen.

3. Exemplo de comparação de strings

Vamos dar apenas um exemplo simples: suponha que você precise inserir duas linhas do teclado e determinar se elas são iguais. É assim que o código ficará:

Scanner console = new Scanner(System.in);
String a = console.nextLine();
String b = console.nextLine();
String result = a.equals(b) ? "Same" : "Different";
System.out.println(result);

4. Uma nuance interessante de comparação de strings

Há uma nuance importante da qual você precisa estar ciente.

Se o compilador Java encontrar várias strings idênticas em seu código (especificamente em seu código), ele criará apenas um único objeto para elas para economizar memória.

String text = "This is a very important message";
String message = "This is a very important message";

E aqui está o que a memória conterá como resultado:

comparação de strings

E se você comparar text == messageaqui, obterá true. Portanto, não se surpreenda com isso.

Se, por algum motivo, você realmente precisar que as referências sejam diferentes, poderá escrever o seguinte:

String text = "This is a very important message";
String message = new String ("This is a very important message");

Ou isto:

String text = "This is a very important message";
String message = new String (text);

Em ambos os casos, as variáveis text​​e messageapontam para objetos diferentes que contêm o mesmo texto.


4
Tarefa
Java Syntax,  nível 4lição 6
Bloqueado
Jen or Jen?
Jen, Company X's admin, learned how to pilot a space ship and flew away to another planet. People in Company X are good and sincere. It's just that they're scatterbrained and they mix up names. So they decided that the new administrator would also be called Jen. Let's help Company X find their Jen: write a program that checks the identity of two entered names.