Comparing primitive wrappers

I guess everyone who played around with autoboxing ran into the problem that comparing primitive wrappers does not compare values but object references.
This is annoing since java 1.0 but the issue becomes much worse with autoboxing. You can now freely intermix Integer and int without compile time error, so the chance that you compare Integer references while you mean to compare int values has increased.
Example
int getOneValue() ...
Integer getAnotherValue() ...
// and somewhere else
if (getOneValue() == getAnotherValue()) ...
This will work as expected long as at least one function returns an int (thanks to auto unboxing). If you change both functions to return Integer this will still compile, but it won't work anymore.
I know that this cannot be changed for backward compatibility reasons but it would be VERY helpful if we could get some kind of workaround.
For example an annotation to tell the compiler that we want auto-unboxing before compare:
How about:
@greedyunboxing(true)
Integer getOneValue() ...
Integer getAnotherValue() ...
if (getOneValue() == getAnotherValue()) ... // unbox before compare now because @greedyunboxing is true

I'd just prefer that the compiler issue a warning when it sees reference equality tests between two primitive wrapper objects. If you really intend to do that (which would be extremely rare) you could turn off the warning via some annotation.
God bless,
-Toby Reyelts

Similar Messages

  • Should the primitive wrappers be lazy Flyweights?

    Following on from a discussion earlier today, which observed that autoboxing currently creates new wrappers:
    Integer i = 7;
    //currently expands to
    Integer i = new Integer(7);
    //but we probably want it to become
    Integer i = Integer.valueOf(7);This got me thinking about this discussion I saw recently:
    http://www.cafeaulait.org/oldnews/news2004March16.html
    And that made me think about caching and and the Flyweight design pattern [GangOfFour]
    Here's the JavaDoc for Integer.valueOf(int):
    * Returns a <tt>Integer</tt> instance representing the specified
    * <tt>int</tt> value.
    * If a new <tt>Integer</tt> instance is not required, this method
    * should generally be used in preference to the constructor
    * {@link #Integer(int)}, as this method is likely to to yield
    * significantly better space and time performance by cacheing
    * frequently requested values.
    * @param i a int value.
    * @return a <tt>Integer</tt> instance representing <tt>i</tt>.
    * @since 1.5
    public static Integer valueOf(int i) ;
    Unfortunately, this method currently just does:
    new Integer(i) !
    Is the plan to introduce the use of caching here? And if so will autoboxing use it?
    Consider this code:
    Integer a = 7;
    Integer b = 7;
    a.equals(b); // TRUE
    a == b; // FALSE with the current autoboxing implementationIf you were to do caching for wrappers, and autoboxing were to use valueOf(), then the second comparison would yield "true".
    Thinking that through, one obviously can't change the fact that Integer's constructor is public, so it would always be possible to create new Integers that failed the reference equality test.
    Integer is not Cloneable but it is Serializatable, so you'd have to implement readResolve().
    I don't know if it would be acceptable to have the old Integer.valueOf(String) method return a cached Integer... probably...
    Finally, you'd probably want to support an Integer.intern() method, similar to String.intern() so people can resolve Integers they receive from libraries, should they wish to do so.
    Naturally everything I've said about Integer can be applied to the other wrapper classes too.
    So is any of this stuff planned? The comments on Integer.valueOf(int) seem to suggest that it is, but some insight would be nice.

    We're always being told to use 'new' instead of object
    pooling, because object creation/deletion is so fast
    these days. Supposedly also one day the JVM will be
    able to create stack instead of heap objects (under
    suitable circumstances), so 'new' will be almost
    costless, whereas pooling would be almost impossible
    for the JVM to optimize away.I understand what you mean, and I agree with it for most uses. It somewhat misses the point in this instance.
    If one goes around creating 'new' objects then '==' must necessarily return 'false' when they are compared. This is not useful behaviour in this case, in particular because Integer and the other wrapper classes are immutable. It defies expectations that two Integer's that are both '7' are not ==.
    The real reason I say you missed the point is because the aim of this object pool is not to improve performance, its to get a different behaviour for autoboxed Integers. As such, while saying "it may be faster to create new objects" is an interesting observation, unless you can devise a way to allocate new objects and preserve reference equality, its not really relevant to the question I was trying to ask.
    If you do want to think about performance though, here's some thoughts:
    I'm not sure whether you'd ever need to garbage collect the cached Integer instances. I'd guess that you could, because you could use weak references in the cache and let the Integer instances be collected once no more code needs them. In pratice a small working set of Integers (and Doubles, Longs etc) would probably always exist because they would be being used by the VM. It would probably even be worthwhile to determine what this working set is, and preload it as a part of the new startup image optimization.
    You might simply decide never to cleanup cached Integers. It might work better to just keep them around for the next time someone uses them. My guess would be some large perctentage of the commonly used Integers fall in a range close to zero (+/- 128?), so why not always have these on-hand in the cache? Perhaps high numbers are rarely used, and would be weak references, but low numbers would be strong references and would never be collected?
    One would need to measure and tune to really be sure.
    If it turns out that 99% of the Integer objects ever allocated are already loaded in the cache, then all you ever pay is the lookup cost. You would never allocate them and never have to garbage collect them. And that's likely to be faster than making them with 'new' no matter how fast the allocator & collector get. You can't beat simply doing no work on the collection side of things!

  • Comparing colors in java

    import java.awt.*;
    import java.awt.event.*;
    import java.lang.Object;
    import java.awt.Robot;
    public class Robot04 {
    public static void main(String[] args) throws AWTException{
    Color UnkownColor = new Color(0, 102, 255);
    Color greenn = new Color(0, 204, 51);
    Color bluu = new Color(0, 102, 255);
    If (UnkownColor = bluu) System.out.print(" the color is blue");
    }This doesn't successfully compare the unknown and blue color and neither does ==, How do I compare them?

    if(aColor.equals(otherColor)) { /* ... */ }http://java.sun.com/j2se/1.4.2/docs/api/java/awt/Color.html
    = is the assignment operator;
    == can be used to compare primitives;
    .equals(...) is used to compare Objects for equality.

  • Comparing Strings with "If" statements : help please. :-)

    I have an assignment for class... and having lots of trouble trying to figure out what I did wrong. I cannot find a solution.. if anyone can help me with this, it'd be much appreciated.
    Assignment Write a program to allow the user to calculate the area and perimeter of a square, or the area and circumference of a circle, or the area of a triangle.
    To do this, the user will enter one of the following characters: S, C, or T. The program should then ask the user for the appropriate information in order to make the calculation, and should display the results of the calculation. See the example program execution shown in class.
    The program should use dialog boxes.
    When expecting an S, C, or T, the program should reject other characters with an appropriate message.
    Get extra points for allowing both the uppercase and lowercase versions of a valid character to work. Name the program ShapesCalc.java.My error codes are
    incomparable types: java.lang.String and Char
    cannot find symbol variable output
    incomparable types: java.lang.String and Char
    incomparable types: java.lang.String and CharI've asked a friend and they said something about Strings cannot be compared in "If" statements... if that is the case.. how is this supposed to be arranged? If you can point me in the right direction, I will be very grateful! :-)
    What I have created so far
    import javax.swing.JOptionPane;
    public class ShapesCalc {
        public static void main(String[] args) {
          //Enter S,C, or T
          String input = JOptionPane.showInputDialog("Enter S,C, or T");
          //If Statements
          //Square
          if (input == 'S'){
               String lengthu = JOptionPane.showInputDialog("Enter length of a square");
               double length = Double.parseDouble(lengthu);
               double area = length * length;
               double perimeter = length * 4;
               String ouput = "The area is " + area + " and the perimeter is " + perimeter;
               JOptionPane.showMessageDialog(null, output);}
          //Circle
          else if (input == 'C'){
               String radiusu = JOptionPane.showInputDialog("Enter the radius of a circle");
               double radius = Double.parseDouble(radiusu);
               double area = 3.14159 * radius * radius;
               double circumference = 2 * 3.14159 * radius;
               String output = "The area is " + area + " and the circumference is " + circumference;
               JOptionPane.showMessageDialog(null, output);}
          //Triangle
          else if (input == 'T'){
               String baseu = JOptionPane.showInputDialog("Enter the base of a triangle");
               double base = Double.parseDouble(baseu);
               String heightu = JOptionPane.showInputDialog("Enter the height of a triangle");
               double height = Double.parseDouble(heightu);
               String output = "The area is " + (base * height) / 2;
               JOptionPane.showMessageDialog(null,output);}
          //Error Message
          else {
               String error = "Incorrect variable please enter S,C, or T only.";
               JOptionPane.showMessageDialog(null,error);}
          //Signature
          String signature = "Rodriguez, Markos has compiled a Java program.";
          JOptionPane.showMessageDialog(null,signature);
    }Edited by: ZambonieDrivor on Feb 22, 2009 6:52 PM

    ZambonieDrivor wrote:
    How would I go about on the extration of a single char from a String to make it comparable, I don't quite understand this part.Read the [Java API|http://java.sun.com/javase/6/docs/api/] for the String class and see what methods it has.
    I will convert the == to equals() method.If you want to compare primitives (ints, chars etc) then using == is fine. Only when comparing objects do you use the equals method.

  • C++ primitive versus Coherence Primitive POF encoding

    I was wondering if anyone can shed some light on the differences b/w POF encoding of C++ primitives vs encoding of Coherence Primitive.
    I've noticed using Coherence Primitives retain both type & value allowing readObject() to work as expected, whereas there are nuances where only the value is retained when using primitives.
    * Is there an inherent difference as to how primitive types are POF encoded versus Coherence Primitives ? ie. Do they both use packed optimizations? Are Coherence Primitives encoded as a Type which contains the primitive type, or are they both encoded the same.
    * Is it possible for readObject() to infer the correct types from the stream, or must the type definition always be implicit. ie. The deserializer and serializer must always agree on read/write methods. How is readObject() affected by the optimizations?
    * The return type and name of the function readObject() implies it only deals with objects, but its documentation states it reads a property of ANY type including a user type from the stream. How does it internally handle primitive types? ie. If it encounters a primitive in the stream, does readObject() wrap it in a (correct) Coherence Primitive?
    * Is there any cross-language implications when using Coherence Primitives?

    Hi Mark,
    For those who may be confused by what a "Coherence Primitive" is I'll clarify. The coherence::lang::Primitive<T> template class is a common template base class used for building up wrapper classes for C++ primitive types such as bool, int32_t, int64_t. For instance the coherence::lang::Integer32 class extends Primitive<int32_t>, and works similar to the relationship between int and java.lang.Integer in Java. Primitive<> extends from coherence::lang::Object class which is the root of our manage object class hierarchy. As with Coherence for Java these primitive wrappers are POF serializable. In fact the description I give here applies equally to our Java and C++ extend clients.
    Language primitives and primitive wrappers are bit for bit identical when serialized in POF format. There is however a subtle but important difference. For some values PofWriter may choose to entirely optimize out the value from the byte stream, and this does differ between the primitives and wrappers. The basic rule is that primitives can be optimized out of the POF stream entirely when writing the types default 'zero' value, and this is not true for the wrapper types. For instance:
    hWriter->writeInt32(PROP_ID_BLAH, 0); // this will be a noop
    This will be a noop, and the corresponding readInt32() call will treat the lack of a property in the POF stream as a zero value.
    int32_t nVal = hReader->readInt32(PROP_ID_BLAH); // will return 0
    However if you were to write out the corresponding wrapper object a zero would be written to the stream.
    hWriter->writeObject(PROP_ID_BLAH, Integer32::create(0)); // writes a zero to the stream
    Integer32::View vnVal = cast<Integer32::View>(hReader->readObject(PROP_ID_BLAH)); // will return an Integer32 representing zero
    This optimization works beautifully so long as the reader and writer are symmetric, using either the same type of methods for a given property. If you mix and for instance use writeInt32, and then readObject, you can see some surprising results. For instance zero's come out as NULLs, and all other numeric types (such as Integer64 or Float32/64) will come out as Integer32 for certain small numeric values. This has caused us some issues with the initial release of PofExtractor which always returns Objects, and as such will show behavior similar to the above when the primitive based writer methods were used during serialization. This fix for this specific issue will be made available soon in an upcoming 3.5 service pack.
    So this leaves the question what method should you use for writing primitives. I would say that in the vast majority of cases it would be preferable to use the primitive variants, rather then writing the wrapper object via writeObject(). The biggest advantage of this is that it avoids the unneeded object creation. The primary benefit of using writeObject() for the wrappers is that it gives you one additional value, i.e. NULL. So for instance which writeBoolean() can only communicate one of two values (true, false), writeObject() passing a Boolean, can communicate one of three values (true, false, NULL). Outside of that writeObject() on a primitive wrapper is also beneficial for generic code which doesn't know the type of the object being serialized.
    I suppose the docs for writeObject need some cleanup. This method supports the serialization of any type which extends from coherence::lang::Object, and has a registered POF serializer.
    To answer your final question the two variants produce language neutral POF streams, and can be read from Java and .NET just fine.
    hope that helps,
    Mark
    Oracle Coherence

  • Literal Strings - same value, same object?

    I've read that if two literal Strings contain the same value, they reference the same object to save memory. Is this guaranteed? And is the same thing true of primitive wrappers with literal values like Integer(42)?
    The reason I ask is because I'm thinking of using a Map as a sparse array indexed by Integers... or, if not that, then Strings representing integer values.

    Ok so you put a string into the map using one of the Integer references as a key and took it out using the other one.
    The problem here is how a Map works when you get() something. (Including HashMap).
    "Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
    "More formally, if this map contains a mapping from a key k to a value v such that (key==null ? k==null : key.equals(k)), then this method returns v; otherwise it returns null. (There can be at most one such mapping.)"
    http://java.sun.com/javase/6/docs/api/java/util/Map.html#get(java.lang.Object)
    The important bit is the second paragraph. Do you see where for non-null keys it checks key.equals(k)? In your case the two 666 Integers were checked for equality of value using equals(), not for identity of reference (using ==). They are different objects, but they represent the same integer value so they compare true with equals(). Hence the map finds a match even when you use a different key.
    A more straightforward test is to simply print:
    {code}
    Integer i1 = new Integer(666);
    Integer i2 = new Integer(666);
    if(i1 == i2) {
    System.out.println("Same");
    } else {
    System.out.println("Different");
    {code}
    You'll find the same behaviour - +different+ key objects returning the same value from a Map - even when you use small Integer objects like new Integer(66).

  • Null String and Empty String problem

    Hello everyone,
    since i am totally new in JSP, i am getting problem in handling strings.
    Suppose i have a variable users = ""; then
    I want to ask when to use:
    if (users.equals(""))
    and
    if(users == "")
    in my code, variable users has value "regional" for regional users.
    and i am checking this code as:
    if (users.equals{"regional")) {
    out.print ("I am inside code");
    at that time, the code is throwing error (run time error)
    and when i changed the code as:
    if (users == "regional") {
    out.print ("I am inside code");
    this time, the code is not generating error but the part message "I am inside code " is not displaying. The code do not inserts inside the if condition
    I hope u understand my problem. Can anybody help me out with this.

    This has basically nothing to do with JSP, but with basic Java knowledge.
    When using the '==' operator to compare Objects (yes, String is actually a subclass of Object), then it will look if they are of the same reference. Using the '==' operator to compare primitive datatypes (int, boolean, char, etc) will look if they have the same value.
    That is why the Object class has the equals() method to give the ability compare with another objects. And you can only invoke it when the Object is actually instantiated. So if it is not null.
    if (string != null && string.equals("somevalue")) {
    // or
    if ("somevalue".equals(string)) {
    }should work.
    Edit rym82: this will not throw a NPE, but an ordinary compilation error ;)
    Message was edited by:
    BalusC

  • Differences between == and .equals

    I'm rather new to Java programming and have learned that == can only be used to compare primitive types in Java (for example when comparing to int) and when comparing objects, one should use the .equals-method (that should be overloaded from the one in Object). This is because == compare the object's reference adress (is this correct?) For example:
    Vector v1 = new Vector();
    Vector v2 = new Vector();
    v1.add("hello");
    v2.add("hello");
    System.out.println(v1 == v2);This program should print false, since v1 and v2 are different objects.
    System.out.println(v1 == v1);should print true.
    OK, so far so good. However, an experiment I've made clearly shows that there's an exception to this rule. When comparing objects of type String, you don't need to use .equals, == works perfectly. My question is why?

    When comparing objects of type String, you
    don't need to use .equals, == works perfectly. My
    question is why?It doesn't work perfectly at all.
    String literals
    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 ==

  • Cant get metod to work

    Hi all,
    I am totally lost. This is the problem. I have a JTable and in one of the cells is the value 1.
    When I run the following code:
    System.out.println("Value = "+animationTable.getValueAt(3, 4));
    it outputs: Value = 1
    OK fine. But after that if I say...
    if (animationTable.getValueAt(2,4) == "1")
         System.out.println("Value = 1");
    it doesnt evaluate the if expression as true. Why is this? I would appreciate any help.

    You can only reliably use the == operator when comparing primitives (char, int, long, etc). Since the value in your cell is a String (I assume), you should use the equals operator of that object.
    String sValue = (String) animationTable.getValueAt(3, 4);
    if (sValue.equals("1")) {
      System.out.println("Value = 1");
    }Another thing I noticed is your first println looks at cell (3, 4) and your comparison looks at (2, 4).
    Hope this helps.

  • Object confusion

    I'm getting a little confused over the use of objects in general in code. I always considered an object in my code basically as a pointer, such that using it in a function or adding it into a list would retain the object itself not just a copy. However this doesn't seem to be the case.
    This little code snippet shows where my confusion is.
    When I add a String object to the list then alter the String, shouldn't that change translate to the object in the array? Or, does ArrayList.add automatically allocate a new object to store in itself?
    When I pass an Integer into the function and change the value it is not reflected in the original Integer object I passed in. This is the behavior I would expect from an int primitive. Is there a way to pass an object like this by reference rather than value?
    Lastly, when I pass the ArrayList in to the function, its changes are reflected in the original list. Do ArrayLists actually represent pointers like I assumed all objects did where as Integer objects are treated differently?
    public static void main(String[] args) throws Exception {
         ArrayList<String> t = new ArrayList<String>();
         String s = "a";
         t.add(s);
         s = "b";
         System.out.println(t.get(0));
         System.out.println(s);
         Integer i = 1;
         test(t, i);
         System.out.println(i);
         System.out.println(t.get(0));
    public static void test(ArrayList<String> list, Integer i){
         list.set(0, "c");
         i = 2;
    }

    jamesss wrote:
    jverd wrote:
    Not in this case, because String literals are cached. If you had done s = new String("a") or s = new anything or s = anything else that creates an object, then yes.By String literals being cached you mean the literal "a" is cached right? not whatever object s is currently pointing at?s points at a String object. In that line, that object is the interned ("cached") String object containing "a".
    i.e. if I rewrote it as
    String s;
    for(int i=0; i<5; i++){
    s = Integer.toString(i);
    would this actually create 5 separate objects since it is using a different string value each time?Yes.
    >
    and with
    for(int i=0; i<5; i++){
    String s = "a";
    does this imply new String("a") and thus would also create 5 separate objects?No. The "a" does not create a new String object. That object is placed into the constant pool when your class is loaded, and from then on, whenever "a" appears, in your code, it's just a reference to that already existing object. If you did new String("a"), that would create a new String object, but it would be pointless to do so.
    Lastly, is there any real difference between the value held by a String reference variable and an Integer reference variable, obviously they must point at their own object type but do the reference values among types basically look/act the same?No difference. Any reference variable just holds a reference that points to an object of an appropriate type, or it holds null, meaning it doesn't point to any object. What's special about Strings is how "abc" literals get put into the constant pool so that you can avoid creating new string objects in some cases. The primitive wrappers--Integer, etc.--do something similar for autoboxing with numbers in the range -128..127.

  • Object is not an instance of declaring class

    Hi All,
    I am having an issue with reflection invoking a method. I have looked up the error I am getting but cannot see why my code is throwing it. As I understand it, the error thinks I am invoking a method on the wrong instance of an expected object, but clearly my code shows I am passing the same class.
    The call to field.getName() will return capitalised variables Id and Description, so that when "get" is prepended, getId and getDescription are formed. Neither method takes arguments.
    I have placed a log statement gm= to find out whether the Method object has been captured, and it has. I get getId logged to the console. All fine so far until a call is made to invoke. Clearly my passed lineItemClass is causing a problem but I am not sure why, this class afterall does have getId. Have also tried changing the lineItemClass param to lineItem which is an actual instance found earlier in my code but this throws ClassCastException, even though that too has getId.
    Your help appreciated!
    try {
    Object[] args = {};
    Class[] paramTypes = {};
    Class lineItemClass = lineItem.getClass();
    Method getMethod = lineItemClass.
    getDeclaredMethod("get" + field.getName(), paramTypes);                    
    System.out.println("gm=" + getMethod.getName());
    Object value = getMethod.invoke(lineItemClass, args);
    } catch (Exception e) {
    System.out.println("error on getFieldValue " + field.getName() + " " + e.getMessage());
    }

    You cannot overload a method with a different return type only, in this case invoke can only return an Object.
    What reflection does for you is ensure that if the actual method invoked returns a primitive, that the equivalent Number type or Boolean is returned.
    Number is the superclass of all primitive wrappers except Boolean, which is the wrapper for the boolean primitive type.
    What reflection also does for you is ensure that although parameter values must be objects that the correct type is used in a method invocation so a method that expects an int will be invoked with a parameter of type Integer, Method.invoke ensures that the Integer value is converted to an int before the method actually is called.

  • Offline-searchable javadoc

    Is there an offline-searchable copy of the java docs? Knowing just where to find the documentation on JList is non-trivial for those, like me, who are new to Java.
    Having to go back to the online site to conduct a search instead of intuitively knowing where to navigate through what seems like a random spattering of categories and links is very annoying.
    I don't like .NET but I'll give Microsoft one thing: their MSDN Library is first rate, and if Sun offered something similar, it would make life less painful when developing Java apps.
    Thanks :)
    PS, I've installed netBeans 5.0 and the help that comes with it seems to deal with the IDE itself, and not with the Java language. Also, the help that comes with code-completion is only useful if you know the Java API like the back of your hand to begin with, which I don't.

    And to kablair, if you don't like newcomers to Java,
    and their questions, why do you read this particular
    forum? If you can't handle these sorts of questions,
    then perhaps you should stick to programming or
    reading expert fora. There's no need to take my
    question personally. I don't mind newcomer questions. I do mind people who come here and start blaring about how Javadoc sucks and MSDN rules and Sun is just so lucky they're going to write Java code. See, it really gets on my nerves because then they usually produce a list of problems that are either inaccurate or issues with them rather than the tools and documentation.
    And what's wrong with autoboxing/unboxing? Anything
    that makes for simpler and more readable code is a
    good thing, and given that Java is the most prolix
    language I've ever used, I would have thought that
    such a time saver would be welcome. Maybe you should
    go back to Java 1.0, because 1.5 has other,
    blasphemous, shortcuts -eg, the simplified for-loop.
    How dare Sun try to make their language easier (if
    not the documentation)?The for-each loop is simple, readable, predictable and easily understood.
    Autoboxing/unboxing is often confusing, unpredictable for those who don't know the relevent JLS chapter like the back of their hand, riddled with "gotchas" and can easily lead to bugs that are extremely hard, if not impossible, to debug. The sole benefit from all of this is less typing when converting to and from primitive wrappers. Is it easier to read? No. In fact in some cases it may obfuscate the developers intentions. In all other cases reading 0 is not profoundly more understandable than new Integer(0).

  • For String == return true, then returns false in another app.

    First App:
    import java.awt.*;
    import java.awt.event.*;
    public class again
         TextField t1, t2;
         public again()
              Frame f=  new Frame();
              t1 = new TextField(10);
              t2 = new TextField(10);
              Button b1 = new Button("Compare");
              b1.addActionListener(new ActionListener()
                   public void actionPerformed(ActionEvent e)
                        String one = t1.getText();
                        if(one=="123")
                             System.out.println("true");
                        else
                             System.out.println("false");
              f.add(t1);
              f.add(t2);
              f.add(b1);
              f.setLayout(new FlowLayout(FlowLayout.LEFT));
              f.setSize(500,500);
              f.setVisible(true);
         public static void main(String args[])
              new again();
    }Second App:
    public class comp
         public static void main(String [] arg)
              String str1 ="123";
              String str2 ="123";
              if(str1=="123")
                   System.out.println("true");
              else
                   System.out.println("false");
    }

    DogsAreBarking wrote:
    None of these books talk about compile time pool constants. Read the JLS.
    As far as i know equals is used to compare reference types and == is used to compare primitive types.Read your books again. So why would strA == strB not lead to a compiler error if it's just for primitives? '==' is the operator to check for referential identity or primitive equality.
    May I quote you when you were told not to use '==':
    yes yes yes... i know all that

  • Passing of Collection of Objects

    I am using Collection of Objects to pass data between Java class and stored packages. Sometimes the error 'Handle is not valid' happens. When we recycle the application, the problem goes away temporarily and but come back later. Does anyone encounter this situation?

    The JNI forum would have been a more obvious place to ask this, but...
    The object of type "jobjectarray " which can be used with jni, i think can hold only objects of same type.So make that type Object, and wrap the primitives in their primitive wrappers (Integer, etc.)

  • Simply if-statement I just can't figure out...

    Well, It's late and I'm very tired... so I just can't get the simpliest of things working right now... so, please, if you can get my brain to understand the following:
    Why can't I compare the string object right?! I just can't get it true in some cases where I thought I could... is it because it an object?! What am I comparing really?!?!
    I've forgot how to code... to many sad news...
    Please, see below for the examples... thanks!
    String test="1";
    if((test)==(test)) { // true }
    String test="1";
    if((test+1)==(test+1)) { // NOT true here!!! WHY?}
    char test='1';
    if((test+1)==(test+1)) { // true }
    int test=1;
    if((test+1)==(test+1)) { // true }
    String test="1";
    if(((test.concat("1").toString()))==((test.concat("1").toString()))) {
         // NOT true here!!! WHY?
                        

    [soapbox]
    The == should only be used to compare primitives and actual object instances (ie. "address" of the object).
    The equals() method should be used to compare objects of any other type (if implemented).
    [soapbox]

Maybe you are looking for

  • How Can I Stop My Photoshop Crashing after every 2/3 actions?

    Hi, ive recently got photoshop cs6 and after every 2/3 actions i get a message saying 'photoshop isnt working' or something like that then i get told to 'close program' how can i stop this happening? here is my system info: Adobe Photoshop Version: 1

  • Trading Partner

    Hi, New to BCS hence needs guidance from you experts 1. Can we define Trading Partner for a specific Item in a company or replace the existing partner with new partner 2.  I have uploaded a file thru Flexi upload method, I want to reload that file wi

  • Error retriving session EJB with getEJBObject() from handle

    the Code i use is CREATE: Handle handle = user.getHandle(); session.setAttribute("user",handle); GET: Handle handle = (Handle)session.getAttribute("user"); UserEJB user = (UserEJB)handle.getEJBObject(); // the abowe row gets the error. Error: java.la

  • HOW TO DISPLAY PICTURE IMAGE ON FORM

    I am a new learning database developer/programmer. I am proud to use Oracle Application Express 11.2. I have succeeded creating a table, a form and report on the table. I have used Blob as data-type for the Photo column. The browse link locates the p

  • I have corrupt pdf's in iBooks

    I have deleted and installed fresh copies of the pdf's a few times. The main copy in iTunes is fine, but when I copy it to my new iPad, it gets corrupted. I have other books on my iPad that work just fine. I have even uninstalled and reinstalled iBoo