Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.getBytes() returns different values for multiple execution?

Tags:

java

string

public static void main(String[] args) {
    try {
        String name = "i love my country";
        byte[] sigToVerify = name.getBytes();
        System.out.println("file data:" + sigToVerify);
        String name1 = "data";
        byte[] sigToVerify1 = name1.getBytes();
        System.out.println("file data1:" + sigToVerify1);

    }
}

I am trying to execute the above program but getBytes() gives me different values for the same String. Is there any way to get the same byte while executing multiple times for a given string?

like image 869
user123 Avatar asked Mar 30 '26 23:03

user123


1 Answers

System.out.println("file data:" + sigToVerify);

Here you are not printing the value of a String. As owlstead pointed out correctly in the comments, the Object.toString() method will be invoked on the byte array sigToVerify. Leading to an output of this format:

getClass().getName() + '@' + Integer.toHexString(hashCode())

If you want to print each element in the array you have to loop through it.

byte[] bytes = "i love my country".getBytes();
for(byte b : bytes) {
    System.out.println("byte = " + b);
}

Or even simpler, use the Arrays.toString() method:

System.out.println(Arrays.toString(bytes));
like image 67
Steve Benett Avatar answered Apr 01 '26 13:04

Steve Benett



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!