473,396 Members | 2,102 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

How can "1" != "1"

SammyB
807 Expert 512MB
I'm trying to keep up with you youngsters, so I'm taking a beginning Java course. As part of a homework assignment, we were to prompt the user for a number between 1 & 3. We also used while loops in the chapter, so I decided to put the prompt in a while loop to force the user to enter 1, 2 or 3. I was very surprised when it did not work, so I have written a 5-liner to show you the problem:
Expand|Select|Wrap|Line Numbers
  1. import javax.swing.JOptionPane;
  2. public class Weird {
  3.  public static void main(String[] args) 
  4.  {
  5.   String s = "";
  6.   while (s != "1" && s!= "2" && s!= "3")
  7.   {
  8.    s = JOptionPane.showInputDialog(null, "Enter 1, 2 or 3");
  9.    if (s == null) break;
  10.   }
  11.   if (s!= null) JOptionPane.showMessageDialog(null, s);
  12.  }
  13. }
  14.  
I fixed the problem by parsing the string and testing for integers 1, 2, or 3, but the above code should work! The same code in VB works great:
Expand|Select|Wrap|Line Numbers
  1. Sub NotWeird()
  2.     Dim s As String
  3.     Do While (s <> "1" And s <> "2" And s <> "3")
  4.         s = InputBox("Enter 1, 2 or 3")
  5.     Loop
  6.     MsgBox s
  7. End Sub
  8.  
Looking at the Java code in the debugger, after the user enters 1, the debugger says s = "1" So far, great, but if I inspect s != "1", it says "s != "1"" = true

What is this crazyness?!?
Oct 7 '07 #1
12 1960
Ganon11
3,652 Expert 2GB
Here's a secret:

When you say

Expand|Select|Wrap|Line Numbers
  1. String myStr;
myStr isn't actually a String. Java tries to trick you into thinking it is (and trust me, that is good for a beginner!), but it's not. myStr is secretly a pointer. Basically, myStr holds an address somewhere in memory. That address is where your actual String is. So when you try and compare myStr to something else with == or !=, you're trying to compare the memory address with a String. So "1" != "1", because the String you use as the left hand side is in a different memory location than the "1" on the right side.

The people at Sun realized this, so they gave you a friendly little method in String called .equals(). So replace

Expand|Select|Wrap|Line Numbers
  1. myStr == "otherStr"
with

Expand|Select|Wrap|Line Numbers
  1. myStr.equals("otherStr")
Oct 7 '07 #2
SammyB
807 Expert 512MB
That's insane! But, very vital to know. It's interesting that
Expand|Select|Wrap|Line Numbers
  1. String s = "1";
  2. if (s == "1")
  3.     MessageBox.Show("C# is not weird!");
  4. else
  5.     MessageBox.Show("C# is as weird as Java!");
  6.  
string comparisons work in C# but not in Java. Thanks for your help, now I'll have to rewrite my homework like I wanted to in the first place!
Oct 7 '07 #3
JosAH
11,448 Expert 8TB
That's insane! But, very vital to know. It's interesting that
Expand|Select|Wrap|Line Numbers
  1. String s = "1";
  2. if (s == "1")
  3.     MessageBox.Show("C# is not weird!");
  4. else
  5.     MessageBox.Show("C# is as weird as Java!");
  6.  
string comparisons work in C# but not in Java. Thanks for your help, now I'll have to rewrite my homework like I wanted to in the first place!
As a matter of fact the above might work. Literal Strings are stored in an 'intern'
pool and both "1" strings are stored only once in that pool; that makes your if-
clause succeed while you actually did it all wrong ;-)

kind regards,

Jos

ps. it's not 'insane'; it just doesn't work your prejudiced mind thought it should work.
Oct 7 '07 #4
SammyB
807 Expert 512MB
... it's not 'insane'; it just doesn't work your prejudiced mind thought it should work.
not prejudiced :D I just expect the compiler to say :You don't want to do this, Sam!" At a minimum, it could have said "Illegal Indirection, like C++. ROFL --Sam
Oct 7 '07 #5
JosAH
11,448 Expert 8TB
not prejudiced :D I just expect the compiler to say :You don't want to do this, Sam!" At a minimum, it could have said "Illegal Indirection, like C++. ROFL --Sam
The compiler can't say that because it's perfectly legal to compare two pointers,
or 'references' as Java calls them; it two pointers compare equal both pointers
point to the same object.

For strings you don't want to compare pointers, you want to compare the *value*
of two (or one?) String object and the String class implements an 'equals' method
for that:

Expand|Select|Wrap|Line Numbers
  1. String s1= new String("foo");
  2. String s2= new String("foo");
  3. if (s1 == s2)
  4.    System.out.println("s1 and s2  point to same object");
  5. else if (s1.equals(s2))
  6.    System.out.println("s1 and s2 have equal value");
  7. else
  8.    System.out.println("s1 and s2 are different");
  9.  
In C++ the overloaded '==' operator in the string class takes care of the 'equals'
functionality. Java doesn't have user defined overloaded operators.

kind regards,

Jos
Oct 8 '07 #6
Dököll
2,364 Expert 2GB
I'm trying to keep up with you youngsters, so I'm taking a beginning Java course. As part of a homework assignment, we were to prompt the user for a number between 1 & 3. We also used while loops in the chapter, so I decided to put the prompt in a while loop to force the user to enter 1, 2 or 3. I was very surprised when it did not work, so I have written a 5-liner to show you the problem:
Expand|Select|Wrap|Line Numbers
  1. import javax.swing.JOptionPane;
  2. public class Weird {
  3.  public static void main(String[] args) 
  4.  {
  5.   String s = "";
  6.   while (s != "1" && s!= "2" && s!= "3")
  7.   {
  8.    s = JOptionPane.showInputDialog(null, "Enter 1, 2 or 3");
  9.    if (s == null) break;
  10.   }
  11.   if (s!= null) JOptionPane.showMessageDialog(null, s);
  12.  }
  13. }
  14.  
I fixed the problem by parsing the string and testing for integers 1, 2, or 3, but the above code should work! The same code in VB works great:
Expand|Select|Wrap|Line Numbers
  1. Sub NotWeird()
  2.     Dim s As String
  3.     Do While (s <> "1" And s <> "2" And s <> "3")
  4.         s = InputBox("Enter 1, 2 or 3")
  5.     Loop
  6.     MsgBox s
  7. End Sub
  8.  
Looking at the Java code in the debugger, after the user enters 1, the debugger says s = "1" So far, great, but if I inspect s != "1", it says "s != "1"" = true

What is this crazyness?!?
Oh! It's crazy alright! Its' quite the headache...

I also find Java sometimes gives you an error on a line, highlights the line, as result of modifications to completely different lines in the code. And of course the moment I put things back where they belong, Java's happy again...
Oct 13 '07 #7
JosAH
11,448 Expert 8TB
Oh! It's crazy alright! Its' quite the headache...

I also find Java sometimes gives you an error on a line, highlights the line, as result of modifications to completely different lines in the code. And of course the moment I put things back where they belong, Java's happy again...
Read my reply #6 for an explanation of this 'crazyness'.
About those errors on 'unrelated' lines: your modifications have ruined the structure
of your program then and the compiler can only detect it when the rest of the
structure of your program can't make sense anymore which may be (many) lines
from where you made your mistake.

kind regards,

Jos
Oct 13 '07 #8
Dököll
2,364 Expert 2GB
The compiler can't say that because it's perfectly legal to compare two pointers,
or 'references' as Java calls them; it two pointers compare equal both pointers
point to the same object.

For strings you don't want to compare pointers, you want to compare the *value*
of two (or one?) String object and the String class implements an 'equals' method
for that:

Expand|Select|Wrap|Line Numbers
  1. String s1= new String("foo");
  2. String s2= new String("foo");
  3. if (s1 == s2)
  4.    System.out.println("s1 and s2  point to same object");
  5. else if (s1.equals(s2))
  6.    System.out.println("s1 and s2 have equal value");
  7. else
  8.    System.out.println("s1 and s2 are different");
  9.  
In C++ the overloaded '==' operator in the string class takes care of the 'equals'
functionality. Java doesn't have user defined overloaded operators.

kind regards,

Jos
Good heavens JosAH!

Java IS like JavaScript a lot of repect then. I cannot recall how I wrote this but in a previous reply specific to Sammy's scenario, I wondered whether:

Expand|Select|Wrap|Line Numbers
  1.  
  2. Var s1 ="Something"
  3. Var s2 ="Something"
  4.  
  5. If (s1 == s2) Then
  6.   This is good stuff
  7. Else
  8.   MsgBox ("Blaze blaze")
  9. End If
  10. ...
  11.  
  12.  
Mind you, I am missing brackets there, but does above signify the similarities in both languages, and if this is a fact, can I look to JavaScrip to get a better understanding of Java, of course to some degree?
Oct 15 '07 #9
SammyB
807 Expert 512MB
Good heavens JosAH!

Java IS like JavaScript a lot of repect then. I cannot recall how I wrote this but in a previous reply specific to Sammy's scenario, I wondered whether:

Expand|Select|Wrap|Line Numbers
  1.  
  2. Var s1 ="Something"
  3. Var s2 ="Something"
  4.  
  5. If (s1 == s2) Then
  6. This is good stuff
  7. Else
  8. MsgBox ("Blaze blaze")
  9. End If
  10. ...
  11.  
  12.  
Mind you, I am missing brackets there, but does above signify the similarities in both languages, and if this is a fact, can I look to JavaScrip to get a better understanding of Java, of course to some degree?
But, as Jos pointed out above, this will print good stuff in Java also because s1 and s2 are both pointing to the same string.

Run the following and see if it helps!
Expand|Select|Wrap|Line Numbers
  1. import javax.swing.JOptionPane;
  2. public class Weird 
  3. {
  4.  public static void main(String[] args) 
  5.  {
  6.   String s1 ="Something";
  7.   String s2 ="Something";
  8.   if (s1 == s2)
  9.    JOptionPane.showMessageDialog(null, "You just think this is good stuff");
  10.   else
  11.    JOptionPane.showMessageDialog(null, "Blaze blaze");
  12.   s2 ="Something else";
  13.   s2 = s2.substring(0, 9);
  14.   if (s1 == s2)
  15.    JOptionPane.showMessageDialog(null, "This is not expected");
  16.   else
  17.    JOptionPane.showMessageDialog(null, "Blaze blaze");
  18.   if (s1.equals(s2))
  19.    JOptionPane.showMessageDialog(null, "Jos is always right!");
  20.   else
  21.    JOptionPane.showMessageDialog(null, "Why bother with this message!");
  22.  
  23.  }
  24. }
  25.  
Oct 15 '07 #10
Dököll
2,364 Expert 2GB
But, as Jos pointed out above, this will print good stuff in Java also because s1 and s2 are both pointing to the same string.

Run the following and see if it helps!
Expand|Select|Wrap|Line Numbers
  1. import javax.swing.JOptionPane;
  2. public class Weird 
  3. {
  4.  public static void main(String[] args) 
  5.  {
  6.   String s1 ="Something";
  7.   String s2 ="Something";
  8.   if (s1 == s2)
  9.    JOptionPane.showMessageDialog(null, "You just think this is good stuff");
  10.   else
  11.    JOptionPane.showMessageDialog(null, "Blaze blaze");
  12.   s2 ="Something else";
  13.   s2 = s2.substring(0, 9);
  14.   if (s1 == s2)
  15.    JOptionPane.showMessageDialog(null, "This is not expected");
  16.   else
  17.    JOptionPane.showMessageDialog(null, "Blaze blaze");
  18.   if (s1.equals(s2))
  19.    JOptionPane.showMessageDialog(null, "Jos is always right!");
  20.   else
  21.    JOptionPane.showMessageDialog(null, "Why bother with this message!");
  22.  
  23.  }
  24. }
  25.  
I must have missed a step or two but I was stuck in what seemed to be an endless loop, should I get pop ups to enter stuff, should I have pressed ok for in pop up with "{ }" in the box?
Oct 15 '07 #11
SammyB
807 Expert 512MB
I must have missed a step or two but I was stuck in what seemed to be an endless loop, should I get pop ups to enter stuff, should I have pressed ok for in pop up with "{ }" in the box?
Copy and paste into Weird.java & run it. You get three popups:
You just think this is good stuff
Blaze blaze
Jos is always right!
Oct 15 '07 #12
Hey you can write the code using the String Methods.

Here is the code which i modified.

while (!s.equalsIgnoreCase("1") && !s.equalsIgnoreCase("2") && !s.equalsIgnoreCase("3"))

{

s = JOptionPane.showInputDialog(null, "Enter 1, 2 or 3");

if (s == null) break;

}
Oct 15 '07 #13

Sign in to post your reply or Sign up for a free account.

Similar topics

43
by: steve | last post by:
I am quite frustrated with php’s include, as I have spent a ton of time on it already... anyone can tell me why it was designed like this (or something I don’t get)? The path in include is...
1
by: David Furey | last post by:
Hi I have an XML documnet and a XSLT document as shown below THe XSLT document brings back a filtered docmument that has the VendorName that starts with a particular sub-string This works as...
2
by: Eric Osman | last post by:
Hi, I'm looking for a javascript function that will convert input such as this: <CLUB Code=" into this: &lt;CLUB Code=&quot;
3
by: NecroJoe | last post by:
I am using PHP to generate a little javascript for one of my pages. In short it allows a user to select a value from a list and pop it into a form field on a seperate page. This works well unless...
5
by: Mateusz Loskot | last post by:
Hi, I'd like to ask how XML parsers should handle attributes which consists of &quot; entity as value. I know XML allows to use both: single and double quotes as attribute value terminator. That's...
3
by: Arpi Jakab | last post by:
I have a main project that depends on projects A and B. The main project's additional include directories list is: ...\ProjectA\Dist\Include ...\ProjectB\Dist\Include Each of the include...
5
by: martin | last post by:
Hi, I would be extremly grateful for some help on producing an xml fragemt. The fragment that I wish to produce should look like this <Addresses> <Address>&qout;Somebody's Name&quot;...
8
by: Ulysse | last post by:
Hello, I need to clean the string like this : string = """ bonne mentalit&eacute; mec!:) \n <br>bon pour info moi je suis un serial posteur arceleur dictateur ^^* \n ...
1
by: manchin2 | last post by:
Hi, Can anybody please provide the information about "&quot" and its use, if possible please provide an example. ...
4
by: fran7 | last post by:
Hi, from help in the javascript forum I found the error in some code but need help. This bit of code works perfectly, trouble is I am writing it to a javascript function so the height needs to be in...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.