Shaydoth Shaydoth - 4 months ago 10
Java Question

"type mismatch" Error Java

I am writing a program that gets an input from the user, and uses to output something on a JTextArea. As I was writing a section, a loop that prints the names of files from a list created eariar:

if(input = "ls") {
int mailSize = mail.size();
for(int i = 0; i < mailSize; i++) {
String value = mail.get(i);
textWindow.append(value + "\n");
}
}


However after I finished writing this section, a section that I have previously written multiple times, It called a
type mismatch
error on the
(input = "ls")
section. I have been looking at it for a while and still can't figure it out. Anyone have the answer?

Answer

It should be input.equals("ls").

input = "ls" is not a comparison but an assignment that puts "ls" inside input, and evaluates to "ls"; in other words, it is an expression of type String, which is invalid inside a conditional and not what you meant.

input == "ls" (note the double =) is a comparison, but it will a test for reference-equality - whether the two strings are the same object, which is also not what you want. For example,

new String("ls") == "ls"

will evaluate to false, although the two objects hold the same value.


(By the way, if you'll write "ls".equals(input) it will evaluate to false even when input is null, instead of throwing an exception. Whether or not it's what you need, or whether you consider it readable, is up to you.)