Meaningless Drivel is fun!*
The moose likes Applets and the fly likes string class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Applets
Bookmark "string class" Watch "string class" New topic
Author

string class

Omar Nasir
Greenhorn

Joined: Jul 11, 2005
Posts: 5
hello there, i am trying to make an applet out of fun. i came across a problem and need u guys to help me out.

my prob is,: take for example im making a calculator. i need to user to input 2 numbers, and a method for calculation ( add, subtract). the user then types "subtract" as method of calculation.

i wrote this:

if(mtdcal == "subtract")
{
sum = num1 - num2;
}

mtdcal is what ever that is typed into the textfield by the user.

mtdcal = txt3.getText();

but it wont work after i compile and execute it. pls tell me what to change.


javaNoob me = new javaNoob();<br />String i = "i";<br />i += "love java!";
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Hi,

Welcome to JavaRanch!

First, a bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name. Joke names and "handles" aren't acceptable here. You can change your display name here. Thanks! We take this rule very seriously.

Now, on to your question: when you have a String variable -- or any other kind of object variable -- it's actually a reference to a String object, rather than the object itself. That means, for example, that multiple String variables can all be referring to the same physical String object in the computer's memory. The "==" operator asks if two variables refer to the same physical object.

But if one of your Strings is compiled into your code, and the other one comes from a user typing, they aren't going to be the same object -- they're going to be two separate objects that just happen to contain the same characters. The equals() method checks for this condition. In other words, replace

if (mtdcal == "subtract")

with

if(mtdcal.equals("subtract"))

and things will magically start working.

For a better and more entertaining explanation of this concept, see this and this.


[Jess in Action][AskingGoodQuestions]
Omar Nasir
Greenhorn

Joined: Jul 11, 2005
Posts: 5
thx lots man. sry bout the name, i changed it. i was in a hury when i signed up, did not read the naming policy. sry again. thx. ^_^
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: string class
 
Similar Threads
Fetching/Passing Data
Re-assigning values to variables
help for a newbie that's out of her depth!
Doubt with notify/ notifyAll method
Formatting date in JSP