+ 1
Why is it printing out 0 instead of 1?
So, I am pretty new to Java. When I was doing some code for fun in the code playground, I decided to make a program that checks if the user input is the same as a word in an array string. However, it didn't work as expected. Here's my code, please take a look. https://code.sololearn.com/c9k5wnrOzfuo/?ref=app In the input part, no matter I type "Hello" or "Amogus", it stills prints 0 even though these words are in the array string. Please tell me, how do I fix it? Thanks!!
9 odpowiedzi
+ 5
In Java, == isn’t used to compare strings. Instead, use .equals() function
“Hello”.equals(“Hello”); -> true
+ 2
getin is stored in heap memory(different reference) while the i in the loop is the copy of each reference from array
so when we do
== in string it actually compares reference not the content
https://code.sololearn.com/cgvZ02V1Sb35/?ref=app
Ugulberto Sánchez maybe you can go in a depth of java.lang.String
I would say that strings in java have much more things to know what I gave is just a small piece ask more if you have further question
+ 2
Snehil I also had that experience and that was the solution I found 😅 I’m just starting with java
+ 1
Ugulberto Sánchez Thank you sir. I am a Python Programmer so it's a little hard to get started with Java.
+ 1
Dragon RB I’m also experiencing that 😅. I had the same question than your before
+ 1
Ugulberto Sánchez Learning C++ is even more difficult tbh(my opinion).
There are lots of things that I haven't discovered in Java . So, guess I'll learn more about this language as possible as I can like Python..
Thanks for the tips again.
+ 1
Ugulberto Sánchez yeah I know that's why I mentioned you too so that I can share my knowledge and when you ask further question there must something new for me.
+ 1
We use the .equals() function for comparisons
0
Sifat Hossain noted!