Very basic question !


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Very basic question !

Hybrid View

  1. #1
    Join Date
    Oct 2005
    Posts
    1

    Exclamation Very basic question !

    I'm new to Java...

    Hi why those aren't true:

    Example 1:
    -------------------------------------------
    StringBuffer sb = new StringBuffer("55555");
    char c = 5;

    if(sb.charAt(2) == c){
    System.out.println("True");
    }
    -------------------------------------------

    Example 2:
    -------------------------------------------
    StringBuffer sb = new StringBuffer("55555");
    String s = "5";

    if(sb.substring(1,2) == s){
    System.out.println("True");
    }
    -------------------------------------------

    Any suggestions ? Thank you.

  2. #2
    Join Date
    Aug 2004
    Posts
    46
    Example 1: 5 != '5'
    Example 2: A String reference value and StringBuffer reference value will never be equal; they will never point to the same object in memory. Use the equals() method to compare object contents.

    Change the following to make true...
    Example 1:
    Code:
    char c = '5';
    Example 2:
    Code:
    if (sb.substring(1, 2).equals(s))

  3. #3
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Just for the record

    A String reference value and StringBuffer reference value will never be equal; they will never point to the same object in memory.
    "Equality" in java is about content, not address. So a StringBuffer may
    very well be equal to a String:

    if (aStringBuffer.toString().equals(aString)) {
    ..
    }
    eschew obfuscation

Similar Threads

  1. Replies: 2
    Last Post: 04-12-2005, 04:46 PM
  2. A more basic question
    By crypto85 in forum .NET
    Replies: 4
    Last Post: 02-18-2005, 07:15 PM
  3. SQL and Visual Basic question.
    By Bob in forum VB Classic
    Replies: 2
    Last Post: 11-19-2002, 09:56 PM
  4. SQL Server 2000 and Visual Basic Question
    By Eric Harris in forum VB Classic
    Replies: 2
    Last Post: 04-21-2002, 01:03 PM
  5. Re: Editorial by Russell Jones/Attack on Gosub
    By Dan Barclay in forum .NET
    Replies: 90
    Last Post: 03-09-2001, 07:04 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center