• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

string class

 
Omar Nasir
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Omar Nasir
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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. ^_^
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic