Java If statement trouble...

Associate
Joined
30 Dec 2005
Posts
415
Hey to all!

I may be doing something really stupid here but I can't see what it is at the moment (9 hours of Java has pretty much fried my brain!).

Basically, when I run the program i'm either typing in the command prompt:

java MyProgram

or

java MyProgram text


The problem occurs when the second one is executed. Although it detects that an arguement has been passed, the if statement fails to go to the TRUE block. Can anyone spot the problem?

Code:
public class MyProgram extends JFrame
{
	public static void main(String[] args)
	{
		String version = "gui";
		if (args.length > 0)
		{
			System.out.println(args[0]);
			[B]if(args[0]=="text")[/B]
			{
				version = "text";
				System.out.println("Launching text version...");
			}
			else
				System.out.println("Launching GUI version...");			
		}
		else
			System.out.println("Launching GUI version...");	

etc etc...

Btw, the code "System.out.println(args[0]);" does actually print "text" to the command prompt.


I appreciate any advice!

Cheers,
Rich
 
Had this trouble myself in the past.

I think it's because the == operator compares the string's references rather than the contents of the strings (Strings are objects). So, it returns false if the strings on the rhs and lhs aren't the exact same object.

Hope that helps,
Jim
 
JIMA said:
Had this trouble myself in the past.

I think it's because the == operator compares the string's references rather than the contents of the strings (Strings are objects). So, it returns false if the strings on the rhs and lhs aren't the exact same object.

Hope that helps,
Jim

Yep thats it - but you mean if the rhs and lhs references are not refering to the same object just to make it precise.
 
pfft silly old java, would annoy me that everything is a reference type. C# *** in that area i guess ;p

== meaning value equals rather than reference equals seems a lot more logical imo.
 
Ah cheers for that guys! I've had several scenarios where that would have been the cause of it, but never caught on that it was based on references.
 
It confused me a lot to start with, Strings are treated like primiative types but they are in fact objects which can be confusing when you wonder why == doesn't work.
 
RobH said:
It confused me a lot to start with, Strings are treated like primiative types but they are in fact objects which can be confusing when you wonder why == doesn't work.

Yes strings are treated slightly different in Java than other objects for example + operator is defined for string concatenation but java allows no operator overloading so you can't do that with your own defined types. There is a lot of weirdness with strings in java and I don't really want to go into too much detail.

If your interested: http://groups.google.com/group/comp...-8&group=comp.lang.java.help#a6b694b8c8fbe85e
 
Back
Top Bottom