StringBuffer and .equals()

this is my test codes:
public class Testing
     public static void main(String arg[])
          StringBuffer sb1 = new StringBuffer("test");
          StringBuffer sb2 = new StringBuffer("test");
          if (sb1.equals(sb2))
               System.out.println("1");
                System.out.println("End");
}At runtime, the program only prints out End, without the number 1.
My question is shouldn't the if-statement is equal to true?
Doesnt .equals() method compare the content of one object to another object?
thanks for any explanation
daffy

String is deliberately immutable (a value object). This means you can pass it around and share it as a data member in many classes without the danger that one class might change its value and therefore surprise all the other classes sharing it. IOW, you can treat it much like a basic type. StringBuffer is class for the efficient manipulation of String contents. It is mutable, and not really intended to be 'passed around' (i.e. made part of a interface, declared as an argument or return type in a non-private method) or shared by classes. In general, a String is passed to a method, manipulated via StringBuffer, then returned as a new String.

Similar Messages

  • How do you determine StringBuffer and List capacity?

    hi all,
    I'm curious and would like to post this query that how to determine the StringBuffer and List capacity after read some of the Java Platform performance book. Some of this performance books simply tells number of capacity brieftly without telling what and how does the capacity stand for.
    First, the book mentioned StringBuffer(50). Note, my question is that what is this 50 stand for? 50 Characters? or any. Can someone help me to rectify this?
    Second, List. ArrayList(0.75). And what is this 0.75(by default) stand for? A heap space? Then how many of them? How many objects that can be stored for not to "exceed 0.75"?
    Please help. :)
    regards,
    Elvis
    scjp

    I think the capacity is the CURRENT size of a container. But it is not equal to the number of elements that container currently hold. Just like, a house can have 10 people within, but problably only 3 people at some time. Also, the capacity is not equal to the maximum size, because container can grows automatically.
    For example, a container whose capacity is 50, currently has 30 elements in it. If you add 10 elements more. That is only an addition operation. But if you add 30 elements to it. Then the container first enlarge its capacity according to some arithmetic(a enlarging rate), secondly carry out the addition operation.
    Now that the capacity is the size, it should be a number standing for HOW MANY elements.... In the case of StringBuffer, it should be how many chars; in the case of ArrayList, it should be how many Objects. I do not think 0.75 can stand for a capacity. Prabaly, it was used to describe the enlarging rate when containers need to contain more elements than its current capacity. ( From JDK API, you can see the type of capacity is int ).
    For containers and alike, the questions "how many I can hold" and "how many I am holding", "Do I can enlarge"? are helpful for understanding how it works.

  • I just bought a new dell quad core 5i and HAVE DOWNLOADED THE TRIAL VERSION OF PHOTO SHOP - its Slow to open up a small file and equally as slow to print why?

    HELP I just bought a new dell quad core 5i and HAVE DOWNLOADED THE TRIAL VERSION OF PHOTO SHOP - its Slow to open up a small file and equally as slow to print why?

    Use Photoshop menu Help>system Info... use its copy button and paste that info in an append here.
    Supply pertinent information for quicker answers
    The more information you supply about your situation, the better equipped other community members will be to answer. Consider including the following in your question:
    Adobe product and version number
    Operating system and version number
    The full text of any error message(s)
    What you were doing when the problem occurred
    Screenshots of the problem
    Computer hardware, such as CPU; GPU; amount of RAM; etc.

  • Method Overriding-toString(),hashCode() and equals()?

    Hi,
    In some Java Classes, I saw that
    toString()
    hashCode()
    equals()
    these 3 methods of Object Class is overloaded.
    I don't understand why and in what situation we have to override these 3 methods of Object Class.
    Thanks in advance for ur Knowledge Sharing.
    Regards,
    S.Prabu

    toString() is typically overridden in subclasses so as to output something useful about a class like instance variable values instead of just a hashvalue representing the object reference as per Object.
    hashCode() and equals() are overridden typically for use within the collections framework though you need to fully understand the hashing contract before starting to override these as they can cause strange results if not overridden correctly.
    Take a look at collections and specifically the hashing functionality of HashMap and HashSet for more info on these.

  • Help need to know hashcode() and Equals method

    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........

    jverd wrote:
    euph wrote:
    jverd wrote:
    euph wrote:
    REFTY5_ wrote:
    Hi ,
    Now i'm working under hashtable functions. In that all are asking me to overwrite hashCode and equals method. Why?
    Please let me know briefly...........Thery're asking you to override the equals and hashCode methods. Override means replace.So does "overwrite." However, as you point out, "override" is the correct word here.So you think "overwrite" means the same as "replace"?To the same extent that "override" does. But both are in the general sense. Override has a specific meaning in this Java context, and overwrite does not.Don't tell me. That's what I said in my original reply.
    To my ear it doesn't. To me "overwrite" means the original is destroyed, whereas when something is "replaced" the fate of the original is unknown. So I think there's a slight semantic difference between these words.Fair enough.Fair enougth, but the next time I suggest you're better sorted.

  • Do I need to override enum's hashCode() and equals()?

    Hi all:
    I have a enum type let's say it is
    public enum Type
      ONE,
      TWO;
    }If I want to compare the enum value to see if they are same value or not, let's say I have two:
    Type a = Type.ONE;
    Type b = Type.TWO;should I use a.equals(b) or (a == b) If I want to use it as another class's key field, and I want to override this class hashCode() and equals() methods.
    Can enum Type return the correctly hash code?
    For example the class is like:
    public Class A
      Type type;
      pubilc boolean equals(Object other)
        // here skip check class type, null and class cast
        if(other.type.equals(this.type))
           return true;
        else
         return false;
      public int hashCode()
        int result = 31;
        result += 31 * result + type.hashCode() ;
       // can we get correct hash code from enum here?
        return result;
    }

    Answered by the test code by myself.
    We can use either equals or (==) to see if they are the same value.
    The enum's hashCode() use System.identityHashCode() to generate the hashCode and they are always correct

  • Scenario in which implement or Write our own hascode and equals method

    Dear All,
    Please let me know in which circumstances we write our own Hashcode method and equals method not the default one provided by java.Kindly give me complete code and scenario.
    Thanks
    Sumit

    Thanks for your reply
    I have one more question.
    When equal method of Object class give the same result as equals we override then why should we override equals.For example see the below code
    public class EqualsTest{
    public EqualsTest() {
         super();
    public static void main(String[] args) {
    Moof one =new Moof(8);
    Moof two =new Moof(8);
    if(one.equals(two))
    System.out.println("one is equals to two");
    class Moof {
    private int moofvalue;
    Moof(int val){
    System.out.println("val inside moof constructor"+val);
    moofvalue=val;
    System.out.println("moofvalue inside moof constructor" +moofvalue);
    public int getMoofValue()
    System.out.println("moofvalue inside getmoffvalue method "+moofvalue);
    return moofvalue;
    public boolean equals(Object o)
    System.out.println("Object o in equals"+o);
    if( (o instanceof Moof) &&(( (Moof)o).getMoofValue()==this.moofvalue))
    System.out.println("true");
    return true;
    else
    System.out.println("false");
    return false;
    Here the output we get is :
    val inside moof constructor8
    moofvalue inside moof constructor8
    val inside moof constructor8
    moofvalue inside moof constructor8
    Object o in equalsMoof@119c082
    moofvalue inside getmoffvalue method 8
    true
    one is equals to two
    The last output "one is equals to two" gives the same result as overridng equals by us.So why should we override equals here.
    Thanks
    Sumit

  • Get item Greater than and equal to today's date...

    Hi,
    We are having issue in getting item greater than today's from SharePoint List. We have a column in list with Date and Time Data type.
    I am using below code to get data greater than and equal to today's date.
    SPQuery query = new SPQuery();query.Query = "<Where><Geq><FieldRef Name='Expires' /><Value Type='DateTime'>"+ DateTime.Today.ToShortDateString() + "</Value></Geq></Where>";
    SPListItemCollection listItemCollection = list.GetItems(query);
    Please suggest what is wrong in above query.
    Regards,
    Amit Chhatbar

    Hi Amit,
    I guess the date is expected to be in UTC and ISO 8601 format. Use the below code and check if it works.
    DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")or DateTime.Today.ToString("yyyy-MM-ddTHH:mm:ssZ")
    Ram Prasad Meenavalli | MCITP | MCTS SharePoint | MCPD SharePoint | http://www.spdeveloper.co.in

  • Difference between == and .equals

    How do they differ in functionality?
    Thanks in advance

    hi javanovice33,
    simply put:
    == tests if two object references point to the same and only one object
    and
    .equals() tests if two object references contain identical contents
    Illustration A:
    String hello1 = "Hello";
    String hello2 = "Hello";
    is hello1==hello2?
    answer: TRUE
    reason: both object references point to the same and only one
    object "Hello". Note that literal String "Hello" is immutable and
    can no longer be changed. JVM memory heap will try to look
    first for the existence of the same value if another object reference
    is initialized to the same literal String "Hello". Therefore, in this case,
    the declaration and initialization above can be rewritten as hello2=hello1.
    is hello1.equals(hello2)?
    answer: TRUE
    reason: both object references contain identical contents "Hello"
    Illustration B:
    String hellow1 = new String("Hello");
    String hellow2 = new String("Hello");
    is hellow1==hellow2?
    answer: FALSE
    reason: each object reference points to distinct object in memory
    thus, they are not equal
    Is hellow1.equals(hellow2)?
    answer: TRUE
    reason: both object references contain identical contents "Hello"
    Regards,

  • When we override Hashcode and Equal Methods

    Hi....I have doubt regading Hashcode and equal methods
    why we override this two methods....
    why we override hashcode method when we are overriding equal method,
    i would very thankful to give answser
    Thank you
    Ramesh

    hash code is computed to check the equality of two
    objects ,
    that is why if u change the default equal method
    implementation , u need to change the hashcode method
    as well.That's an incomplete answer at best.
    The hashcode method is used by hashing algorithms and data strcutures such as HashMap. This value is used to determine what 'bucket' the reference will go into. It cannot, by itself determine equality.
    If you are still unsure, I suggest looking up 'hash table' on google. I'm sure there's a decent explanation on wikipedia.

  • The different between Contain and equals

    I not sure about the different between contain and equals if I want to know if the string have some character or not ?
    thankyou

    HJava wrote:
    Thank you for all the reply,
    I have if (myTYpe.substring(0).contains(""u") ) work
    if if (myTYpe.substring(0).equals(""u") ) not work
    so I post this question, may be I made other mistake
    Thank youIf you wanted to see if the first character of the string was u then it is either
    myTYpe.charAt(0) == 'u'or startWith("u") or matches("^u.*$") etc, etc, etc.
    substring(0) will return the entire String, of course, which you would know if had actually looked at the API docs to find out what it did or even simply printed out the result to see what it did. Seemingly, however, you simply assumed you knew what it did and went on with that false assumption without bothering to even attempt to verify even though it was, already, not producing the results you expected. Instead, you focused on "the difference between contains and equals" which is self-evident in their names and obviously not the problem to begin with.

  • ToString array and equals method

    I have an array and i need to get the toString to output the information. How do I get that to happen. This is what i ahve so far.
       public String toString(){
              //should indicate all cities
              System.out.print("Cities :");
              for (int i = 0; i < cities.length -1; i++)
                   return cities;
    Here is another piece of code I am finishing. Please tell me if the loop and equals method is correct but what is the value to return?
       public City getCity(String cityName){
              //returns the City with name cityName (must search for city in the array)
              //if the city does not exist, it returns null
              for(int i = 0; i < cities.length; i++)
                   if(cityName.equals ("cityName"))
                        return ;
                    else return null;
                Message was edited by:
    ehj3000

    great my world class is fixed now im getting missing return statements on the two methods
           public City getCity (String cityName){
          //returns the City with name cityName (must search for city in the array)
          //if the city does not exist, it returns null
             for(int i = 0; i < cities.length; i++)
                if(cities.getName().equals(cityName))
    return cities[i];
    else
    return null;
    public String toString(){
    //should indicate all cities
    System.out.println("Cities: ");
    for (int i = 0; i < cities.length -1; i++)
    return cities[i].getName();

  • 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

  • What is difference between == and equals ??? i wanna know in detain example

    Hi
    1) String s1 = new String("abs");
              String s2 = s1;
              System.out.println(s1==s2);
              System.out.println(s1.equals(s2));
    Output:
    true
    true
    2)
    String s1 = new String("abs");
              String s2 = s1;
              s2 = "abs";
              System.out.println(s1==s2);
              System.out.println(s1.equals(s2));
    output:
    false
    true
    i m not getting that here s1 is object and its assigned to s2 object so both are point to same memory location...but while assinging s2 = "abs" which is same as s1 then its behave like different object y?

    but while assinging s2 = "abs" which is same as s1 then its behave like different object"abs" is "the same as" s1 in the sense that it represents the same characters in the same order. But it is also different from s1 in that it refers to a different object. It's the same distinction as you get comparing two $20 notes: they are equal but, since there are two of them they cannot be identical.
    With Java reference variables this equal/indentical distinction is represented by equals()/==.
    In general each class defines its own equals(). (Much as there will be a legal definition what what counts as being equal to $20.) This realationship is generally what you mean and hence the rule "when comparing objects use equals()".

  • Difference between .equals("") and .equals(null)

    Can any one please tell me the difference between the following?
    String someString;
    someString = someMethod(someParameter);
    After the method call, if I am going for a check like this..
    what will each check do?
    1. if (someThing.equals(null))
    2. if (someThing.equals(""))
    3. if (something == null )
    4. if (something == "" )
    Thanks in advance,
    Regards
    Rakesh

    First, understand that the empty string ("") and null are two very different things. The empty string ("") is a string object that just doesn't contain any characters. It's still an object though--you can call it's methods.
    Null, on the other hand, is essentailly nothing. It's a special value that means "Nothing. No object here." (Ignoring for now the distinction among the null type, a null reference, etc.) You can't call methods or refer to fields on null. If you try, you'll get a NullPointerException.
    1. if (someThing.equals(null))Calls the equals method on someThing to compare someThing to null. If someThing is not null, this returns false. If someThing is null it... what? returns true? Nope. Throws NullPointerException. You can't call the equals method on a null someThing.
    Therefore there's no point in ever using equals(null).
    2. if (someThing.equals(""))Calls the equals method on someThing to compare someThing to the empty string (""). If someThing is not null, but is empty, it returns true. If someThing is non-null and is not empty (e.g., "abc"), it returns false. If someThing is null, it throws NPE.
    One generally uses the equals method, not the == operator to compare objects--that is, to see if their contents or states are equal. The == operator is used to see if two referecnes refer to the same object, or if a reference is null.
    3. if (something == null ) Evaluates to true if something is null and to false if something is non-null. Never throws NPE (since we're not calling a method or accessing a field).
    4. if (something == "" ) You never really want to use == to compare a String variable to a String literal like this. This checks to see if the reference something is referring to the same object as the "" is. The "" will be referring to an object in the constant pool. Even if something is the empty string, it may not refer to the same entry in the constant pool.
    That is (something == "") could evaluate to false, but something.equals("") could return true.

Maybe you are looking for

  • Lightroom 4 suddenly stopped importing most images

    Hi All, I am using an up-to-date version of Lightroom 4.2 on Mac OSX v10.7.5 with 16 GB DDR3 RAM, a 2.93 GHz processor, and about 250 GB free space on my hard drive. I shoot RAW files with a Canon, and always set my import to convert to DNG. I have b

  • The 2014 ASUG Data Quality Survey is Live

    This is the third ASUG survey from the Data Governance Special Interest Group (SIG)/ Metric Working Group. Like the other two surveys from 2009 and 2011, this survey is polling how companies are managing quality control for their master data, in part

  • Audio drop-out ATV3/netflix

    my new ATV is great, but i'm having some issues with the audio (from netflix). on occasion the sound drops out completely, normally after 5/10 mins in to watching something. is this a known issue, apple or netflix? thanks, jb.

  • Default trace?

    Hi Friends, usr/sap/<sid>/DVEBMGS<nn>/j2ee/cluster/server0/log/archive In the above folder the default trace files of XI are getting archived, which is  zip format and in hidden mode.These files have occupied huge amount of space. What is the importa

  • Wanted conversion of character from uppercase to lowercase.

    Hi all, I am useing one function to conver amount numbers to character conversion. but they r comming in upper case. but i want in lower case. and also i want to remove "rupees " word at the end of the wording. for example. Rs.123 /- output is: ONE H