Comparing a string created with char []

My code compares the equality between two words. It prints the value "TRUE" if the lines are equal. Otherwise, it returns false. Uses Java Equals Function

class k{  

    public static void main(String args[]){  
        String s1="Sach";  
        String s2=word();  
        String s3=new String("Sach");   
        System.out.println(s1.equals(s2));  
        System.out.println(s1.equals(s3));      
    } 

    public static String word() {
        char[] str=new char[100];
        str[0]='S';
        str[1]='a';
        str[2]='c';
        str[3]='h';
        String ss=new String(str);
        System.out.println(ss);
        return ss;
    }
} 

I need to get some selected alphabets into an array and convert them to a string. After this conversion, the function returns a string. But the comparison leads to an incorrect value. Is there any other way to convert an array to a string so that this program gives the correct result.

+4
source share
1 answer

, String , 4 , String.

, 4 96 ('\ u0000'), .

, 4 , , .:

public static String word() {
    char[] str = new char[4];
    str[0] = 'S';
    str[1] = 'a';
    str[2] = 'c';
    str[3] = 'h';
    String ss = new String(str);
    System.out.println(ss);
    return ss;
}

, , , :

public static String word() {
    char[] str = new char[] {'S', 'a', 'c', 'h'};
    return new String(str);
}
+5

Source: https://habr.com/ru/post/1628168/


All Articles