Comparing equality between 2 strings using '=='

Sorry if this seems a pretty trivial question, but it has me rather puzzled.
when comparing reference types (objects) for equality using '==' , it normally only returns true if the two operands are one and the same object.
Now say I were to test this out with the following code:
public class EqualsTest {
  public static void main(String[] args)  {
     String a = "hello";
     String b = "hello";
     System.out.println(a==a);
     System.out.println(a==b);
     System.out.println(a.equals(a));
     System.out.println(a.equals(b));
}a==b actually returns true. This seems counter to what I expected; aren't Strings a and b separate objects despite being the same value (i.e. the literal value of "hello")?
However if I were to change the two string initializations to:
     String a = new String("hello");
     String b = new String("hello");...then it works as expected.
What's the difference here? I'm puzzled...

Grant, thanks for your answer - I am unclear as to
the concept of this constants pool - maybe I'll do a
search on that...As both a space and time saving, when you put something in "" in your code, it gets put into the 'constant pool' section of your class file, and everywhere in your code you use the exact same string ends up referencing the same entity.
You can accomplish this with runtime Strings by using the String.intern() method - it adds the String to the CP, and lets you use == for compares. Can be useful in code where performance is more important than clarity.
Consider this sample:public class StrCheck {
public static boolean pool() {
  String a = "one";
  String b = "one";
  return (a==b);
public static boolean ctor() {
  String c = new String("two");
  String d = new String("two");
  return c==d;
}which decompiles to:ggainey@dhcp59-157 t]$ javap -c -s -verbose StrCheck
Compiled from "StrCheck.java"
public class StrCheck extends java.lang.Object
  SourceFile: "StrCheck.java"
  minor version: 0
  major version: 49
  Constant pool:
const #1 = Method       #7.#17; //  java/lang/Object."<init>":()V
const #2 = String       #18;    //  one
const #3 = class        #19;    //  java/lang/String
const #4 = String       #20;    //  two
const #5 = Method       #3.#21; //  java/lang/String."<init>":(Ljava/lang/String;)V
const #6 = class        #22;    //  StrCheck
const #7 = class        #23;    //  java/lang/Object
const #8 = Asciz        <init>;
const #9 = Asciz        ()V;
const #10 = Asciz       Code;
const #11 = Asciz       LineNumberTable;
const #12 = Asciz       pool;
const #13 = Asciz       ()Z;
const #14 = Asciz       ctor;
const #15 = Asciz       SourceFile;
const #16 = Asciz       StrCheck.java;
const #17 = NameAndType #8:#9;//  "<init>":()V
const #18 = Asciz       one;
const #19 = Asciz       java/lang/String;
const #20 = Asciz       two;
const #21 = NameAndType #8:#24;//  "<init>":(Ljava/lang/String;)V
const #22 = Asciz       StrCheck;
const #23 = Asciz       java/lang/Object;
const #24 = Asciz       (Ljava/lang/String;)V;
public StrCheck();
  Signature: ()V
  Code:
   Stack=1, Locals=1, Args_size=1
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return
  LineNumberTable:
   line 1: 0
public static boolean pool();
  Signature: ()Z
  Code:
   Stack=2, Locals=2, Args_size=0
   0:   ldc     #2; //String one
   2:   astore_0
   3:   ldc     #2; //String one
   5:   astore_1
   6:   aload_0
   7:   aload_1
   8:   if_acmpne       15
   11:  iconst_1
   12:  goto    16
   15:  iconst_0
   16:  ireturn
  LineNumberTable:
   line 3: 0
   line 4: 3
   line 5: 6
public static boolean ctor();
  Signature: ()Z
  Code:
   Stack=3, Locals=2, Args_size=0
   0:   new     #3; //class java/lang/String
   3:   dup
   4:   ldc     #4; //String two
   6:   invokespecial   #5; //Method java/lang/String."<init>":(Ljava/lang/String;)V
   9:   astore_0
   10:  new     #3; //class java/lang/String
   13:  dup
   14:  ldc     #4; //String two
   16:  invokespecial   #5; //Method java/lang/String."<init>":(Ljava/lang/String;)V
   19:  astore_1
   20:  aload_0
   21:  aload_1
   22:  if_acmpne       29
   25:  iconst_1
   26:  goto    30
   29:  iconst_0
   30:  ireturn
  LineNumberTable:
   line 9: 0
   line 10: 10
   line 11: 20
}You can see the constant pool (and lots of other neat stuff) in the disassembled output. Note that "ldc" is LoaDing a Constant from the pool - in pool(), you can see it loading constant #2 twice, and then comparing the results. ctor() uses #4 twice, but loads the results of invokespecial() and compaes that.
Grant

Similar Messages

  • Can I use Intermedia to compare documents between each other?

    Hi pplz,
    Can I compare documents between each other using Intermedia?
    The idea is to compare document to itself to receive certain figure to use as 100% and then to compare this document to any other one to receive something like 'relevancy percentage'.
    Thank you in advance.
    Alex.

    interMedia Text does not support that feature.

  • Trying to compare 2 strings using sql...should be an easy one

    I have a String variable named 'code' that = "xyz". I have "xyz" in my DB under the userCodes column. And I have the following in my Java code:
    String query = "SELECT userCodes FROM accounts";
    ResultSet rs = stmt.executeQuery(query);
    while (rs.next()) {
    thisCode = rs.getString("userCodes");
    if (thisCode == code) { System.out.println("ITS THE SAME CODE"); }The problem is that Java is not recognizing thisCode as being equal to code, when they clearly are equal. Could someone please tell me why the two strings are not equal?
    Thanks.

    Since strings are objects you have to use equals metho to test the equality of the strings.
    Or in sql you can do this by adding a where clause
    PreparedStatement ps = connection.prepareStatement("SELECT userCode FROM accounts WHERE userCode=?");
    ps.setString(1,code);
    ResultSet rs = ps.executeQuery();
    ...

  • How do you make an object, whose name is equal to a String?

    Ok, heres my situation, I have a vector full of strings which i've enumerated.. and i need to create a bunch of JCheckBox's whose names are equal to the strings in the Enumeration..
    I tried going:
              Enumeration Type = TypeList.elements();
              while(Type.hasMoreElements()){
                   String T = (String)Type.nextElement();
                   list.add(new JCheckBox(""+T));
    which makes them appear in the GUI, but i dont know how i would then be able to add an actionListener onto that checkbox, or indeed how i would go about accessing any of them when they dont have actual names.
    ANy Help would be appreciated.
    Thanks

    Yeh.. i dont get this.. I've got them to appear in the JPanel with:
              Enumeration Type = TypeList.elements();
         boxMap = new HashMap();
              while (Type.hasMoreElements()) {
                   String T = (String) Type.nextElement();
                   JCheckBox b = new JCheckBox(T);
                   boxMap.put(T,b);
                   list.add(b);
                   b.addActionListener(ch);
    Thats all well and good, but when i try and see which one has been clicked using a similar fashion:
                   if(ae.getSource() instanceof JCheckBox) {          //checkbox
                   Enumeration sourceCheck = TypeList.elements();
                   System.out.println((JCheckBox)ae.getSource().getAccessibleContext());
              Map SourceMap = new HashMap();
                   JCheckBox compare = (JCheckBox) ae.getSource();
              while (sourceCheck.hasMoreElements()) {
                   String T = (String) sourceCheck.nextElement();
                   System.out.println(T);
                   JCheckBox b = new JCheckBox(T);
                   SourceMap.put(T,b);
                   if(compare == b)
                        System.out.println("Oh My : "+T);
                   System.out.println("ZoomJ I have been clicked");
    in my action performed method it doesnt seem to be able to compare them.. its definately registering that its been clicked because it prints out the 'ive been clicked ' message, and it prints out all the correct names from the Vector, but it doesn't seem to compare them..

  • Storing data in Array or StringBuffer and then comparing it to a string

    I want to store some data in a list or an Array (but apparently an Array only holds 10 items?) and then I want to be able to check if myString is equal to any of the posts in the array/list.
    Or if I use a StringBuffer I want to check to see if myString is part of the StringBuffer?
    How do I do this?
    / Elin

    I want to store some data in a list or an Array (but
    apparently an Array only holds 10 items?)Uh, no. Arrays can (theoretically) contain Integer.MAX_VALUE elements.
    and then I want to be able to check if myString is equal to any
    of the posts in the array/list.Don't confuse String's equals() method with the equality operator '=='. The == operator checks that two references refer to the same object. If you want to compare the contents of Strings (whether two strings contain the same character sequence), use equals(), e.g. if (str1.equals(str2))...
    Example:String s1 = "foo";
    String s2 = new String("foo");
    System.out.println("s1 == s2: " + (s1 == s2)); // false
    System.out.println("s1.equals(s2): " + (s1.equals(s2))); // trueFor more information, check out Comparison operators: equals() versus ==
    Or if I use a StringBuffer I want to check to see if
    myString is part of the StringBuffer?See above discussion on .equals().
    How do I do this?
    Here are some other resources to help you get started with Java.
    The Java&#153; Tutorial - A practical guide for programmers
    Essentials, Part 1, Lesson 1: Compiling & Running a Simple Program
    New to Java Center
    How To Think Like A Computer Scientist
    Introduction to Computer Science using Java
    The Java Developers Almanac 1.4
    JavaRanch: a friendly place for Java greenhorns
    jGuru
    Bruce Eckel's Thinking in Java
    Joshua Bloch's Effective Java
    Bert Bates and Kathy Sierra's Head First Java

  • How to search for upper/lower case using string using JAVA!!!?

    -I am trying to write a program that will examine each letter in the string and count how many time the upper-case letter 'E' appears, and how many times the lower-case letter 'e' appears.
    -I also have to use a JOptionPane.showMessageDialog() to tell the user how many upper and lower case e's were in the string.
    -This will be repeated until the user types the word "Stop". 
    please help if you can
    what i have so far:
    [code]
    public class Project0 {
    public static void main(String[] args) {
      String[] uppercase = {'E'};
      String[] lowercase = {'e'};
      String isOrIsNot, inputWord;
      while (true) {
       // This line asks the user for input by popping out a single window
       // with text input
       inputWord = JOptionPane.showInputDialog(null, "Please enter a sentence");
       if ( inputWord.equals("stop") )
        System.exit(0);
       // if the inputWord is contained within uppercase or
       // lowercase return true
       if (wordIsThere(inputWord, lowercase))
        isOrIsNot = "Number of lower case e's: ";
       if (wordIsThere(inputword, uppercase))
         isOrIsNot = "number of upper case e's: ";
       // Output to a JOptionPane window whether the word is on the list or not
       JOptionPane.showMessageDialog(null, "The word " + inputWord + " " + isOrIsNot + " on the list.");
    } //main
    public static boolean wordIsThere(String findMe, String[] theList) {
      for (int i=0; i<theList.length; ++i) {
       if (findMe.equals(theList[i])) return true;
      return false;
    } // wordIsThere
    } // class Lab4Program1
    [/code]

    So what is your question? Do you get any errors? If so, post them. What doesn't work?
    And crossposted: how to search for upper/lower case using string using JAVA!!!?

  • How to compare data between two tables?

    Hi,
    My team is trying to develop a SAP data migration tool (DMT) using ABAP.
    One of the functionalities in the DMT is to validate the data in the staging area against the loaded SAP data.
    The tables in the stagin area are customer tables (i.e. user-defined tables starting with Y, Z).
    How do I compare the data in the staging area against data that are loaded into SAP tables? Are there some built-in SAP functions to do this? Or, are there some better ways of doing this (e.g. instead of comparing against data in the SAP tables, we compare with some INTERNAL tables)?
    Any help would be greatly appreciated, thanks!

    Hi Kian,
    Use <b>SCMP</b> transaction to compare data between two tables and you can not use this for comparing internal tables.
    Thanks,
    Vinay

  • Switching between 2 string values

    This is probably a trivial question, but how do I switch between 2 string values to be sent to one input terminal of a larger concatonated string function. The values need to be changed every 100ms or so.
    Thanks
    mhaque
    Solved!
    Go to Solution.

    Why so complicated???
    You can do this particular string manipulation in a single atomic operation using "Append True/False String"
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    AppendTF.png ‏3 KB

  • How to compare date between 2 file?

    hi there...
    is there any possibility to compare date between 2 file and the file that is latest to open?
    thank you

    i need help urgently..... i type tis code
    <%
    String file = ("C:/");
    File f = new File(file);
    String [] fileNames = f.list();
    File [] fileObjects= f.listFiles();
    %>
    <UL>
    <%
    for (int i = 0; i < fileObjects.length; i++) {
    if(fileObjects.lastModified()){
    %>
    <LI>
    <a href="<%= fileNames[i %">"><%= fileNames[i] %></A>
    <%
    %>
    my purpose is to list out all the file in the folder but not to the user just for the system to check all the files than when i click a link it will open the latest file
    Message was edited by:
    n_dilah</a>

  • Equality between primitive and persistent objects

    Folks,
    I have discovered by chance that the KODO Query implementation allows me
    to test for equality between an Integer and a persistent object. This is
    actually phenomenally useful because it allows me to easily work around
    some really inefficient auto-generated SQL (see below).
    I couldn't find anything about this feature in the JDO specs. Is it
    accidental? Is it supported, or likely to disappear in future versions?
    Dave Syer.
    # 'bean' is an object already loaded from the persistence store
    javax.jdo.JDOHelper.getObjectId(bean)Bean-101
    # it has one mutable property, which is persistence capable
    # and also a read-only property which is the database id
    # (Integer) of the property:
    javax.jdo.JDOHelper.getObjectId(bean.getProperty())Property-371
    bean.getPropertyId()371
    # get an extent for querying (pm is the PersistenceManager)
    ex=pm.getExtent(Bean,0)# First do a query on property...
    qu=pm.newQuery(ex);
    qu.declareParameters("Property id1");
    qu.setFilter("property == id1")# ...generates SQL with additional unnecessary(?) Cartesian join
    # to PROPERTY table:
    res=qu.execute(bean.getProperty())# resulting SQL:
    # SELECT t0.PROPERTY_ID, t0.PROPERTY_ID FROM BEAN t0, PROPERTY t1
    # WHERE (t0.PROPERTY_ID = 371 AND t0.PROPERTY_ID =
    # t1.PROPERTY_ID)
    # Now do a query on propertyId (Integer)...
    qu=pm.newQuery(ex);
    qu.declareParameters("java.lang.Integer id1");
    qu.setFilter("propertyId == id1")# ...but parameter value is allowed to be a Property -- magically
    # turned into an integer when the SQL is generated:
    res=qu.execute(bean.getProperty())# resulting SQL:
    # SELECT t0.PROPERTY_ID, t0.PROPERTY_ID FROM BEAN t0 WHERE
    # t0.PROPERTY_ID = 371

    It is accidental and unsupported.Is there any other way to get round the 'unnecessary join' issue that I
    mentioned briefly in my original posting? In a real world example, I was
    able to improve performance of a single query by a factor of 100 (and my
    DB experts tell me there was no way to optimise indexes or anything at the
    RDBMS level and achieve the same result).
    DAve.

  • Comparing Table between two dbs DBMS_RECTIFIER_DIFF.DIFFERENCES

    We have streams replication between two databases db1 & db2 (table level streams replication).
    We would like to compare tables between these databases.
    we can use DBMS_RECTIFIER_DIFF.DIFFERENCES to find out differences. However what is value to be passed for REFERENCE_SITE & COMPARISON_SITE parameters?
    Is it DBLINK or TNSNAMES entry ?

    Its the DBLINK.

  • Compare settings between plants

    Hi,
    Is there any transaction code to compare settings between 2 plants.For eg Quantity/Value update was done for plant X but not for plant Y.Or else what are the tables used to compare the settings

    >
    nevinphilip wrote:
    > Hi thanks for the reply..Can you tell me which all tables are to be checked.
    Please check this answered link:
    plant table

  • Return the difference between two strings

    Is it possible to return the difference between two strings?
    For example
    String one = "We went for a walk";
    String two = "We went for a run";
    compare "two" to "one" returns "walk"
    compare "one" to "two" returns "run"I need to return the difference of two strings, one prior to editing and one after editing.
    Then I want to return any difference between the two, which will be the effect of the editing.
    Cheers Alex

    Interesting problem. Before you start writing any code, make up a whole bunch of test case pairs. Decide what the difference between the pairs is. When you start seeing patterns, analyse them. After a while you may have enough data to start writing your program. Here's one test case to get started with:"I saw the cat eat a rat"
    "My cat is hungry"

  • How to draw a line(shortest distance)  between two ellipse using SWING

    how to draw a line(should be shortest distance) between two ellipse using SWING
    any help will be appreciated
    regards

    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import javax.swing.*;
    import javax.swing.event.MouseInputAdapter;
    public class ELine extends JPanel {
        Ellipse2D.Double red = new Ellipse2D.Double(150,110,75,165);
        Ellipse2D.Double blue = new Ellipse2D.Double(150,50,100,50);
        Line2D.Double line = new Line2D.Double();
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
                                RenderingHints.VALUE_ANTIALIAS_ON);
            g2.setPaint(Color.green.darker());
            g2.draw(line);
            g2.setPaint(Color.blue);
            g2.draw(blue);
            g2.setPaint(Color.red);
            g2.draw(red);
        private void connect() {
            double flatness = 0.01;
            PathIterator pit = blue.getPathIterator(null, flatness);
            double[] coords = new double[2];
            double x1 = 0, y1 = 0, x2 = 0, y2 = 0;
            double min = Double.MAX_VALUE;
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                    case PathIterator.SEG_LINETO:
                        Point2D.Double p = getClosestPoint(coords[0], coords[1]);
                        double dist = p.distance(coords[0], coords[1]);
                        if(dist < min) {
                            min = dist;
                            x1 = coords[0];
                            y1 = coords[1];
                            x2 = p.x;
                            y2 = p.y;
                        break;
                    case PathIterator.SEG_CLOSE:
                        break;
                    default:
                        System.out.println("blue type: " + type);
                pit.next();
            line.setLine(x1, y1, x2, y2);
        private Point2D.Double getClosestPoint(double x, double y) {
            double flatness = 0.01;
            PathIterator pit = red.getPathIterator(null, flatness);
            double[] coords = new double[2];
            Point2D.Double p = new Point2D.Double();
            double min = Double.MAX_VALUE;
            while(!pit.isDone()) {
                int type = pit.currentSegment(coords);
                switch(type) {
                    case PathIterator.SEG_MOVETO:
                    case PathIterator.SEG_LINETO:
                        double dist = Point2D.distance(x, y, coords[0], coords[1]);
                        if(dist < min) {
                            min = dist;
                            p.setLocation(coords[0], coords[1]);
                        break;
                    case PathIterator.SEG_CLOSE:
                        break;
                    default:
                        System.out.println("red type: " + type);
                pit.next();
            return p;
        public static void main(String[] args) {
            final ELine test = new ELine();
            test.addMouseListener(test.mia);
            test.addMouseMotionListener(test.mia);
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.add(test);
            f.setSize(400,400);
            f.setLocation(200,200);
            f.setVisible(true);
            EventQueue.invokeLater(new Runnable() {
                public void run() {
                    Graphics g = test.getGraphics();
                    g.drawString("drag me", 175, 80);
                    g.dispose();
        private MouseInputAdapter mia = new MouseInputAdapter() {
            Point2D.Double offset = new Point2D.Double();
            boolean dragging = false;
            public void mousePressed(MouseEvent e) {
                Point p = e.getPoint();
                if(blue.contains(p)) {
                    offset.x = p.x - blue.x;
                    offset.y = p.y - blue.y;
                    dragging = true;
            public void mouseReleased(MouseEvent e) {
                dragging = false;
            public void mouseDragged(MouseEvent e) {
                if(dragging) {
                    double x = e.getX() - offset.x;
                    double y = e.getY() - offset.y;
                    blue.setFrame(x, y, blue.width, blue.height);
                    connect();
                    repaint();
    }

  • Compare data between two tables

    Hey Experts
    I am having two tables both are having same structure.
    Both r having 210 columns
    I want to compare data between these two tables.
    I used follwoing query
    select * from t1
    MINUS
    select * from t2but even if thr is diff in 1columns .. i need to search 210 columns which is the exact columns and data
    how can i find the exact columns out of these 210 columns ?

    SShubhangi wrote:
    but even if thr is diff in 1columns .. i need to search 210 columns which is the exact columns and data
    how can i find the exact columns out of these 210 columns ?This is not a trivial problem to solve. Consider a much simpler data set. In table 1 (four columns) we have
    1 A B C
    2 D E F
    3 A B Dand in In table 2 (four columns) we have
    2 X Y Z
    3 A B ENow
    select * from table1 minus select * from table2gives
    1 A B C
    2 D E F
    3 A B Dwhereas
    select * from table2 minus select * from table1gives
    2 X Y Z
    3 A B ENow clearly the first row in Table1 (ID=1) doesn't match any row in Table2 but it's only two columns out from the last row in Table2 (ID=3). However, the row in Table1 with ID=3 only doesn't match on one column.
    So, how do you represent the output?
    Clearly what you want can only be achieved if there are some columns which ought to be the same in both tables i.e. key columns. In which case you can use a full outer join link teh two tables, and case statements to display only the values which don't match:
    select t1.id as t1_id
             , t2.id as t2_id
             , case when t1.col1 != t2.col1 then r1.col1 end as t1_col1
            , case when t1.col1 != t2.col1 then r1.col1 end as t2_col1
            , case when t1.col2 != t2.col2 then r1.col2 end as t1_col2
            , case when t1.col2 != t2.col2 then r1.col2 end as t2_col2
            , case when t1.col3 != t2.col3 then r1.col3 end as t1_col2
            , case when t1.col3 != t2.col4 then r1.col4 end as t2_col2
    from table1 t1
          full outer join table2 t2
         on t1.id = t2.id;Handling nulls is left as an exercise for the reader :)
    I agree that typing all this would be extremely tedious for a table with 210 columns, but that's why Nature gave us the ability to generate SQL statements from teh data dictionary.
    Cheers, APC

Maybe you are looking for

  • Loop within a loop

    is there anything wrong with this code clear wa_bseg. loop at t_final into wa_final.   loop at t_bseg1 into wa_bseg where belnr = wa_final-belnr                                and   gjahr = wa_final-gjahr. *and   zfbdt  = wa_final-zfbdt. if sy-subrc

  • Problem with yahoo! SMTP POP server mail account on new upgraded iphone 4.3.5

    PLEASE HELP! I am a California AT&T wireless customer with a new iphone 4 on the iOS 4.3.5 upgraded system and suddenly I am unable to successfully add my Yahoo! email account and have it configured to send/receive my emails.  I was able to successfu

  • Imcoming Payment DocNum does not match the corresponding JE DocNum.

    Dear Experts, I have a SBO database in which the setting "Use one series for multiple docs" is set to yes. In this database, when I save say Incoming Payment document, the DocNumber generated in Incoming payment and the corresponding JE are same. Now

  • Moving SharePoint from One server to another

    Hi, We are in the process of migrating our current sharepoint farm server to another server. Our scenario WFE Servers  = SERVER01 AND SERVER02 APP Servers   = SERVER03 AND SERVER04 SQL Server   = SERVER05 New WFE Servers = SERVER06 AND SERVER07 New A

  • Adding 7906 to CCM 4.1(3)SR3B

    I am trying to add a 7906 into our environment but the 7906 isn't in the "Add Phone" drop down list, has anyone else this? I have run cmterm-7911_7906-sccp.8-0-4SR1.exe on our callmanagers but it doesn't change the list.