user1040876
user1040876

Reputation: 31

java - how to compare string from construction through char[]

I tried the following but could not get any answer to comparing 2 String. How can I compare b and x and get 'true'?

import java.io.*;

class Test {
  public static void main(String[] args) {
    // String a = "abc";
    String b = new String("abc");
    // System.out.printf("a == b -> %b\n", (a == b));
    // System.out.printf("a.equals(b) -> %b\n", a.equals(b));
    char[] x = new char[4];
    x[0] = 'a'; x[1] = 'b'; x[2] = 'c'; x[3] = 0;
    String s = new String(x);
    System.out.printf("x = %s\n", s);
    System.out.printf("b == s -> %b\n", b == s);
    System.out.printf("b.equals(s) -> %b\n", b.equals(s));
    System.out.printf("b.compareTo(s) -> %d\n", b.compareTo(s));
  }
}

x = abc
b == s -> false
b.equals(s) -> false
b.compareTo(s) -> -1

Upvotes: 1

Views: 3232

Answers (4)

Brian Roach
Brian Roach

Reputation: 76908

A char array is not a String. As it is, you're comparing the reference values of the objects (The String and the char[]) which will never be true.

You would either need to convert the char array to a String and use String.equals(otherString) or convert the String to a char array and compare the arrays with the static method from the Arrays class.

char[] x = new char[3];
x[0] = 'a'; x[1] = 'b'; x[2] = 'c';
String b = new String("abc");
String otherString = new String(x);
if (b.equals(otherString))
{
    // they match
}

Or using the static method from Arrays ...

char[] myStringAsArray = b.toCharArray();
if (Arrays.equals(x, myStringAsArray))
{
    // they match
}

As noted in Alex's answer, there's not terminating null in a Java String.

JavaDoc:

http://download.oracle.com/javase/6/docs/api/java/lang/String.html

http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html

Upvotes: 2

KV Prajapati
KV Prajapati

Reputation: 94643

The size of an array must be three.

 char[] x = new char[3];
 x[0] = 'a'; x[1] = 'b'; x[2] = 'c';
 String s = new String(x);

Upvotes: 0

Dave Newton
Dave Newton

Reputation: 160261

Take out the trailing '0' char, use String.equals, and make the char array be three chars long.

Upvotes: 1

Alex Gitelman
Alex Gitelman

Reputation: 24732

You don't need to terminate String with 0 in Java. And don't use == on strings. It will compare the reference not the content.

Upvotes: 1

Related Questions