Doubt about denial operator

Asked

Viewed 300 times

1

Why is it not possible in Java to use the negation operator on an object like Javascript? Is this because Java is strongly typed or is there some other peculiarity? For in Javascript the negation operator can be applied in any type.

Example:

Java

String nome = "Renan";

if(!nome){ // erro

} ...

Javascript

let nome = "Renan";

if(!nome) 
   alert("Sem erro");
else
   alert(nome);

4 answers

2

The guy String in Java is a objeto, then he tries to deny an object generating error, but javascript is not strongly typed and it is possible to interpret a string, if the string is empty for example the return will be false and if she has any value the return will be true, that is to deny the string it will take its value booleano and this amount will be denied.

2

This is because Java is heavily typed?

It’s not just because Java is heavily typed but because Javascript is weakly typed,

    let nome = "Renan";

if(!nome) 
   alert("Sem erro");
else
   alert(nome);

This returns a boolean expression, i.e., The value Undefined behaves as false when used in a Boolean context. For example, the code you gave of example runs Alert(name) because the variable is not Undefined.

Already this that you are trying to do in Java in my view it doesn’t even make sense:

String nome = "Renan";

if(!nome){ // da erro

} ...

Because what you are trying to do inside the if does not return a Boolean, so it gives the error.

  • I know it doesn’t make sense, this example is to explain the difference

0

In JS a Boolean comparison is made with the internal value, if empty, it means 0 (zero) or false, when it has something it understands as 1 (one) or true.

Java treats the string as a string and not as an object, so the comparison has to be done as its type (string), for this we use the method equals(), this method returns true or false as you wish to compare.

Ex.:

String nome = "Renan";

if(!nome.equals("")){ // nome NÃO é vazio

} ...

See the java documentation.

See spinning here.

  • String is rather an object in Java as it is a built type.

  • @renanzin, yes String is a Java class, not a generic object, so you cannot compare it boolean, but rather its value.

0

In java, if only checks a boleana condition.

boolean condicao = true;

if(condicao) {

}...

//agora é possível negar a condição
if(!condicao) {

}...

//para verificar se uma String está vazia pode utiliza o método isEmpty(), que retorna um boolean
String nome = "Renan";
if(nome.isEmpty()) {

}...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.