Whats the difference between = and == in java? - java

I know that == means equal to but I cannot figure out what = means.

A single = is assignment. A value is assigned to a variable.
int a = 1; // <-- assign 1 to a.
JLS-15.26.1. Simple Assignment Operator = says (in part)
A compile-time error occurs if the type of the right-hand operand cannot be converted to the type of the variable by assignment conversion (ยง5.2).
The == is the equality operator, JLS-15.21. Equality Operators says (in part),
The operators == (equal to) and != (not equal to) are called the equality operators.

= means assignment operator which assigns the value on its right to the operand on its left whereas == (Equal to) means equality check.
Say, you want to assign 1 into a variable i, so you have to write:
i = 1;
But if you want to check whether the value of i is 1 or not, you have to check:
if (i == 1) {
//do something
} else {
// do something else
}

= is the assignment operator. E.g., a = 5 means assigning the value of 5 to the variable a.

the operator "=" assign the value to a certain instance
but
an operator "==" means a certain instance has a value of something
example
x = 2; //It means x is 2
x == 2; //means x has a value of 2

= is the assignment operator which is used to assign a value to a variable, property or fields. While == is used to check a condition for example in a if condition

int houseAddress = 1;
This means that the variable houseAddress is given the value of 1, so you can think of this as the address of the house is equal to 1;
if(houseAddress == 1){
//do something
}
This code is saying whether houseAddress is equal to 1 this would return TRUE or FALSE in this case we know that houseAddress is 1 so it return TRUE.
Hope this helps its missing a few technical detail which might confuse you so its missed out.

Related

Counting The Number of Valleys [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
I'm doing a problem on hackerRank and the problem is:
Problem Statement
Here we have to count the number of valleys does XYZ person visits.
A valley is a sequence of consecutive steps below sea level, starting with a step down from sea level and ending with a step up to sea level.
For One step up it U, and one step down it is D. We will be given the number of steps does XYZ person traveled plus the ups and down in the form of string, i.e,
UUDDUDUDDUU
Sample Input
8
UDDDUDUU
Sample Output
1
Explanation
If we represent _ as sea level, a step up as /, and a step down as \, Gary's hike can be drawn as:
_/\ _
\ /
\/\/
He enters and leaves one valley.
The code I wrote doesn't work
static int countingValleys(int n, String s) {
int count = 0;
int level = 0;
String[] arr = s.split("");
for(int i = 0; i<n;i++){
if(arr[i] == "U"){
level++;
} else{
level--;
}
if(level==0 && arr[i]=="U"){
count++;
}
}
return count;
}
But another solution I found does, however no matter how I look at it the logic is the same as mine:
static int countingValleys(int n, String s) {
int v = 0; // # of valleys
int lvl = 0; // current level
for(char c : s.toCharArray()){
if(c == 'U') ++lvl;
if(c == 'D') --lvl;
// if we just came UP to sea level
if(lvl == 0 && c == 'U')
++v;
}
return v;
}
So what's the difference I'm missing here that causes mine to not work?
Thanks.
In java, you need to do this to compare String values:
if("U".equals (arr[i])) {
And not this:
if(arr[i] == "U") {
The former compares the value "U" to the contents of arr[i].
The latter checks whether the strings reference the same content or more precisely the same instance of an object. You could think of this as do they refer to the same block of memory? The answer, in this case, is they do not.
To address the other aspect of your question.
Why this works:
for(char c : s.toCharArray()){
if(c == 'U') ++lvl;
if(c == 'D') --lvl;
when this does not:
String[] arr = s.split("");
for(int i = 0; i<n;i++){
if(arr[i] == "U"){
You state that the logic is the same. Hmmmm, maybe, but the data types are not.
In the first version, the string s is split into an array of character values. These are primitive values (i.e. an array of values of a primitive data type) - just like numbers are (ignoring autoboxing for a moment). Since character values are primitive types, the value in arr[i] is compared by the == operator. Thus arr[i] == 'U' (or "is the primitive character value in arr[i] equal to the literal value 'U') results in true if arr[i] happens to contain the letter 'U'.
In the second version, the string s is split into an array of strings. This is an array of instances (or more precisely, an array of references to instances) of String objects. In this case the == operator compares the reference values (you might think of this as a pointer to the two strings). In this case, the value of arr[i] (i.e. the reference to the string) is compared to the reference to the string literal "U" (or "D"). Thus arr[i] == "U" (or "is the reference value in arr[i] equal to the reference value of where the String instance containing a "U" string" is located) is false because these two strings are in different locations in memory.
As mentioned above, since they are different instances of String objects the == test is false (the fact that they just happen to contain the same value is irrelevant in Java because the == operator doesn't look at the content). Hence the need for the various equals, equalsIgnoreCase and some other methods associated with the String class that define exactly how you wish to "compare" the two string values. At risk of confusing you further, you could consider a "reference" or "pointer" to be a primitive data type, and thus, the behaviour of == is entirely consistent.
If this doesn't make sense, then think about it in terms of other object types. For example, consider a Person class which maybe has name, date of birth and zip/postcode attributes. If two instances of Person happen to have the same name, DOB and zip/postcode, does that mean that they are the same Person? Maybe, but it could also mean that they are two different people that just happen to have the same name, same date of birth and just happen to live in the same suburb. While unlikely, it definitely does happen.
FWIW, the behaviour of == in Java is the same behaviour as == in 'C'. For better or worse, right or wrong, this is the behaviour that the Java designers chose for == in Java.
It is worthy to note that other languages, e.g. Scala, define the == operator for Strings (again rightly or wrongly, for better or worse) to perform a comparison of the values of the strings via the == operator. So, in theory, if you addressed other syntactic issues, your arr[i] == "U" test would work in Scala. It all boils down to understanding the rules that the various operators and methods implement.
Going back to the Person example, assume Person was defined as a case class in Scala. If we created two instances of Person with the same name, DOB and zip/postcode (e.g. p1 and p2), then p1 == p2 would be true (in Scala). To perform a reference comparison (i.e. are p1 and p2 instances of the same object), we would need to use p1.eq(p2) (which would result in false).
Hopefully the Scala reference, does not create additional confusion. If it does, then simply think of it as the function of an operator (or method) is defined by the designers of the language / library that you are using and you need to understand what their rules are.
At the time Java was designed, C was prevalent, so it can be argued that it makes sense the C like behaviour of == replicated in Java was a good choice at that time. As time has moved on, more people think that == should be a value comparison and thus some languages have implemented it that way.

Is it possible to include a = sign in the "if ()"?

I wrote a line to add a total up the total value
int totalValue = value1 + value2 + value3;
Now I want to use an if statement to write if (totalValue = 200); but it gives me an error saying "Cannot convert from an int to a boolean type".
What should I do because I want to have four possible outcomes using else if();
System.out.println();
if (totalValue == 200)
= is for assigning values, == is for comparing values.
The = operator in Java only does assignment; you want to compare totalValue to 200, so you should use the == comparator operator.
if(totalValue = 200){
...
}
Do note that you shouldn't have a semicolon after an if statement, since then Java will basically ignore the if.
The = sign is the assignment operator.
Doing if(totalValue = 200) will actually assign 200 to totalValue.
What you need is the == operator
if(totalValue == 200)
{
System.out.println("200");
}
else if (totalValue == 100)
{
System.out.println("100");
} //...
Putting the line terminator at the end of if(totalValue == 200);
will terminate the conditional statement. This means that the statements below it will not only execute if the condition evaluates to true.
Also, I find it good practice to always put {} after the if() even with just one statement to prevent issues with scoping. Here's a link to show how this can happen (and prevented) https://stackoverflow.com/questions/21999473/apples-goto-fail-security-bug
if you write if(totalValue = 19), it will evaluate if you can successfully assign 19 to totalValue.
Being successful or not, in Java is a Boolean, so it expects to evaluate a boolean.
The expression:
if((totalValue = 19) == True){ ... }
would be correct but also useless, in this case, because it will almost for sure assign successfully the value
if you wanna only check the value you must use ==
Yes, but equality is == and assignment is =. Also, don't end your if statement with a semicolon or you terminate the body of the if.
// if (totalValue = 200);
if (totalValue == 200) {
// Do stuff for when the value is 200
} else {
// Do stuff when the value is not 200
}
Like the others said, the '=' operator in Java is used to assign values. However (maybe a little off-topic), the assignment itself evaluates to the assigned value, which can be reused in a boolean expression.
This can be used like in this loop, where the result of readLine is stored and compared to null in a single expression:
int value;
while ((value = reader.read()) != -1) {
doSomething(value);
}

Why does java require a double equals sign?

Why does java require a double equals sign (==) when comparing Integers in a if statement?
For example
if(x = 3.141)
System.out.println("x is equal to pi.");
is incorrect, it should be
if(x == 3.141)
System.out.println("x is equal to pi.");
I know that "==" is used to compare integers and "=" is used to set an integer value, but why in a if statement does this remain true?
Is it even allowed to assign a variable a value in an if statement (or initiate a new variable)?
Is there any reason anyone would ever want to assign a variable a new value inside an if statement (if so please provide an example)?
This seems like a question that should already have an answer, but I was unable to find one on here or using google, if this is a duplicate question please tell me and I will remove it immediately.
Wouldn't it be confusing if = sometimes did assignment, and sometimes comparison, depending in which context you used it?
That sounds like a bad idea, and would introduce errors.
Plus, the current syntax is compatible with C and C++, so a lot of people are familiar with it.
Is there any reason anyone would ever want to assine a variable a new value inside of an if statement (if so please provide an example)?
It's quite common in while loops:
int b;
while ((b=in.read()) != -1){
=
is used for assignment.
==
is used for comparison.
Is it even allowed to assign a variable a value in an if statement (or initiate a new variable)?
yes it is allowed.
Note what error message you get for if (x = 3.141); it is a type error (cannot convert from double to boolean).
The assignment's type is the type of its both sides; if the type of the assignment is boolean (if (x = true), or even if (x = a.equals(b))), then it is legal to write.
So since it is legal to assign a value to a boolean in the condition, you'd have to use == for comparison.
Is it even allowed to assine a variable a value in an if statement (or initiate a new variable)?
Yes. A common idiom for doing this is:
String line = null;
while ( (line = in.readLine()) != null ) {
// do work
}
In the loop, line is assigned a value and then compared to null. I can't think of an example with ints; it certainly wouldn't be clear there.
History of programming languages 101:
Fortran uses = for both.
Algol introduced := for assignment and used = for comparison. This was required to resolve a grammar ambiguity.
Pascal followed suit.
PL/1 did not.
I can't speak for B or BCPL but by the time we got C it was = for assignment and == for comparison, again to resolve a grammar ambiguity
C++ followed C
Java followed C++ in many respects including this one.
The grammar ambiguity arises because of allowing assignments in expressions. Contrary to your assertion, if (x = true) is legal in Java if x is of type boolean.
== is the identity comparator, which works for both objects and primitives. It answers the question "are the two things the same thing".
= is the assignment operator. It sets the value of the left side to the right side.
Things can turn buggy when using your example with booleans:
boolean b;
if (b = true) // This compiles, but is a bug, because it sets b, not tests it
While other types won't compile with this syntax, boolean and Boolean do, so that's why the following pattern is advised:
if (b)
you can absolutely assign a variable in an if statement. also, that's just the way it works: = always is assignment, and == is always comparison.
So..
= is assignment, and == is comparison, and it is always like this, no matter where they are used.
And assignment is different with "declaration". An assignment statement has its return value, while a declaration doesn't. So you can't write boolean a = false in the () of if statement, but you can write a = false when a has been declared before.
Not all assignments are legal. For example:
int index;
if (index = str.indexOf("something")) {
...
}
It's not legal, because String.indexOf(String) returns an int, while if requires a boolean.
Also, there is a huge difference between "legal" and "making sense".
int index;
if ((index = str.indexOf("something")) != -1) {
...
}
It is legal, as != operation returns a boolean, and it makes sense, as I do want to check if the str contains a substring "something";
However,
int index;
boolean flag;
if ( flag = ((index = str.indexOf("something")) != -1) ) {
...
}
is also legal, as the statement as last returns a boolean; but it DOESN'T make sense, because the != statement already returns a boolean.

What does "?" mean in Java? [duplicate]

This question already has answers here:
What is the Java ?: operator called and what does it do?
(17 answers)
Closed 10 years ago.
I dont know what the question mark (?) stand for in java, I was doing a small program, a Nim-game. were looking in a book, for help and saw this statement:
int pinsToTake = (min >= 2) ? 2 : 1;
I don't understand it, what will ? represent, can it be something to do with if-statement but you put it in a variable? and the : can be something "else"? (this things that I just said can be very misleading)
someval = (min >= 2) ? 2 : 1;
This is called ternary operator, which can be used as if-else. this is equivalent to
if((min >= 2) {
someval =2;
} else {
someval =1
}
Follow this tutorial for more info and usage.
Its ternary operator also referred to as the conditional operator, have a look reference
like Object bar = foo.isSelected() ? getSelected(foo) : getSelected(baz);
eg. operand1 ? operand2 : operand3
if operand1 is true, operand2 is returned, else operand3 is returned
operand1 must be a boolean type
operand1 can be an expression that evaluates to a boolean type
operand1 and operand2 must be promotable numeric types or castable object references, or null
if one of operand2 or operand3 is a byte and the other a short, the type of the returned value will be a short
if one of operand2 or operand3 is a byte, short or char and the other is a constant int value which will fit within the other operands
range, the type of the returned value will be the type of the other
operand
otherwise, normal binary numeric promotion applies
if one of operand2 or operand3 is a null, the type of the return will be the type of the other operand
if both operand2 and operand3 are different types, one of them must be compatible (castable) to the other type
reference
it means:
if(min >= 2)
someval =2;
else
someval =1
Its called a ternary operator
See this java example too
That's a Ternary Operator. Check Oracle's doc for further info. Long story short, it is an if-else statement that can be done in a single line and used inside methods and to define variable values.
Syntax:
boolean_expression ? do_if_true : do_if_false;
Parallelism with if-else statement:
if(boolean_expression)
//do_if_true;
else
//do_if_false;
I didn't use brackets on purpose, since you can only execute one line of code in do_if_true and do_if_false.
Example of use:
boolean hello = true;
String greetings = hello ? "Hello World!" : "No hello for you...";
This will set someString as "Hello World!" since the boolean variable hello evaluates to true. On the other hand, you can nest this expressions:
boolean hello = true;
boolean world = false;
String greetings = hello ? (world ? "Hello World!" : "Hello Stranger!") : "No hello for you...";
In this case, greetings will have as a value "Hello Stranger!";
It's called the Ternary If operator, it's just short-hand for an if...else
"? :" is a ternary operator equivalent to an if else statement.
In your example:
pinsToTake = (min >= 2) ? 2 : 1
if min >= 2 then assign 2 to pinsToTake, else assign 1
max = (a > b) ? a : b;
(a > b) ? a : b; is an expression which returns one of two values, a or b. The condition, (a > b), is tested. If it is true the first value, a, is returned. If it is false, the second value, b, is returned. Whichever value is returned is dependent on the conditional test, a > b. The condition can be any expression which returns a boolean value.
It is called conditional operator.This is how it works.
if min is greater than or equal to 2 ,then first value after ? that is 2 here will be assign to corresponding variable ,otherwise second value that is 1 here will be assign.
This link will tell you all you need.
Summary for archival sakes:
It's called the conditional operator. It's a ternary operator that
takes three terms:
BooleanExpression ? Expr1 : Expr2
The BooleanExpressionis evaluated. If it's true, the value of the
whole expression is Expr1. If it's false, the value of the whole
expression is Expr2.
So it serves the same kind of purpose as an if statement, but it's a
term rather than a whole statement. That means you can embed it in
places where you can't use a whole statement.

"Invalid assignment" error from == operator

I was trying to write a simple method:
boolean validate(MyObject o)
{
// propertyA && propertyB are not primitive types.
return o.getPropertyA() == null && o.getPropertyB() == null;
}
And got a strange error on the == null part:
Syntax error on token ==. Invalid
assignment operator.
Maybe my Java is rusty after a season in PLSQL. So I tried a simpler example:
Integer i = 4;
i == null;
// compile error: Syntax error on token ==. Invalid assignment operator.
Integer i2 = 4;
if (i == null); //No problem
How can this be?
I'm using jdk160_05.
To clarify: I'm not trying to assign anything, just do an && operation between two boolean values. I don't want to do this:
if (o.propertyA() == null && o.propertyB() == null) { return true; }
else { return false; }
== is not an assignment operator, it's a boolean equality operator, see:
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.21.2
If you want to set i to null use the simple assignment operator =:
i = null;
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.1
If you want to check that i is null then you need to use the == operator
if (i == null)
I don't think you are confusing assignment and equality comparison. I think your compiler is just giving you a confusing error message. This program:
Integer i = 4;
i ==null;
should give an error something like this:
Program.java:8: not a statement
i ==null;
Your first program should compile correctly. Perhaps there is some invisible unicode character in the text that is confusing the compiler. Try deleting the entire function and typing it in again.
I think I see your problem. I'm sorry the other answers don't address it.
So, Java has this idea that is shared by some other languages that just because something is a valid expression doesn't mean that that thing, by itself, is a valid statement.
For example, this code will complain similarly:
Integer i = 4;
i+3; // this line gives a compilation error
And yet obviously I can use i+3 (go unboxing!) elsewhere to mean "7":
System.out.println(i+3); // this is fine
It gets a bit confusing because unlike some languages that have this expression/statement distinction, java allows you to use any method call - whether it returns a value or not - as a statement. However, most java operators do not - by themselves - form a valid statement.
Likewise, this fails to compile:
Integer i = 4;
i; // this line gives a compilation error
For the full gory details, see http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#32588
In PL/SQL, assigning a value to a variable is done with the := operator. Comparing two values is done with =.
In Java, assigning a value to a variable is done with the = operator. Comparing two values is done with ==, or a .equals() method in some cases.
You can do things like this:
x = i==null;
This will test if i is null and if so, the value true will be assigned to x (assuming that x is a boolean).

Categories