Java不是说两个字符串相等吗?

Java不是说两个字符串相等吗?,java,string,equality,Java,String,Equality,可能重复: 这是我的剧本: public class euler4 { /** * a palindromatic number reads the same both ways. the largest palindrome * made from the product of 2-digit numbers is 9009 = 91 * 99. * * find the largest palindrome made from the p

可能重复:

这是我的剧本:

public class euler4 {

    /**
     * a palindromatic number reads the same both ways. the largest palindrome
     * made from the product of 2-digit numbers is 9009 = 91 * 99.
     * 
     * find the largest palindrome made from the product of two 3-digit numbers.
     */
    public static void main(String[] args) {
        /*for(int t = 100; t < 200; t++) {
            for(int l = 100; l < 100; l++) {
                String milah = "" + t * l;
                String result = palin(milah);
                if(result != "no_pali") {
                    System.out.println(milah);
                }
            }
        } */
        String result = palin("abba");
        System.out.println(result);
    }

    public static String palin(String the_num) {
        int orech = the_num.length();
        String back_word = "";
        /**
         * the for loop has the counter starting at the orech of the number, then
         * decrementing till 0 (or the 0'th index)
         */
        for(int i = orech - 1; i >= 0; i--) {
            back_word = back_word + the_num.charAt(i);
        }
        System.out.println(the_num);
        System.out.println(back_word);
        System.out.println(back_word == "abba");
        if(back_word == the_num) {
            return back_word;
        } else {
            return "no_pali";
        }

    }
}
那印的是假的

它打印了单词的精确副本,但当我比较它们时,它给出的是假的


因为它们不相等(当它们真的相等时),所以返回错误的东西

您需要使用String.equals()而不是比较指针

back_word.equals("abba");
(另请参见
String.equalsIgnoreCase()
如果适用)

使用
back_word.equals(“abba”)取而代之

=
在Java测试中,如果它们是相同的对象,那么
back\u word==back\u word
将返回
true

但是String类的
.equals
方法会检查

如果给定对象表示与此字符串等效的字符串,则为false


取自:

因为
=
比较它们是内存中的同一对象,而它们不是。它们表示相同的数据,但它们不是相同的对象


您需要
返回\u word.equals(“abba”)

在java中,==运算符比较对象的地址

要比较两个字符串是否相等,需要使用
.equals()
函数

back_word.equals("abba");

Java中的==运算符执行对象相等而不是值相等。back_单词和“abba”是两个不同的对象,但它们可能具有相同的值

您正在寻找的是equals方法:

System.out.println(back_word.equals("abba"));

在字符串类型的上下文中,使用==通过引用进行比较(内存位置)

除非将字符串与其自身进行比较,否则它将返回false


尝试使用equals()方法,因为它通过值进行比较,您应该可以得到所需的信息。

您的意思是什么?这一行代码替换的是什么?这里的其他答案涵盖了这一点,Java中的变量是指向存储该对象的内存地址的指针,除了像
int
byte
boolean
这样的简单类型之外。因此,当您对对象使用
=
运算符时,您是在比较两个地址,而不是对象本身。如果您想测试两个对象(在本例中为两个字符串)之间的相等性,请使用
.equals()
方法。一旦我知道答案,这将是重复的。在我知道答案之前,我不知道我在寻找什么。请不要把东西放进像pastebin这样的网站,然后链接到它。SO代码渲染引擎完全可以胜任这项任务。即使互联网上的所有其他网站都消失了,关于SO的问题和答案也应该是有用的!用于澄清或扩展的链接是可以的,但Q&a应该尽可能独立。当您为SO上的问题键入标题后,会弹出一个带有类似标题问题的框。快速查找真正重复的东西是值得的。如果它总是检查对象的地址,整数i=6;整数j=6;System.out.println(i==j);
System.out.println(back_word.equals("abba"));