All QuestionsCategory: Java Questionsstring to byte array and vice versa and compare both string
Gopal asked 2 years ago

I convert string to byte array and this byte array to string again,
so i just want to know that the original string and converted string was equal or not?
if it is equal than what is the reason for that???

Below is the code for that:
String str = “My string”;
byte[] theByteArray = str.getBytes();
System.out.println(“string to byteArray: ” + theByteArray);
String str1 = new String(theByteArray);
System.out.println(“byteArray to string: ” + str1);

if (str.equals(str1)) {
System.out.println(“equal”);
} else {
System.out.println(“not equal”);
}

Output of this code is “equal”.
You can take any string what you want and check to it.

I want one scenario that it will not equal.
Thats my AIM for the research

1 Answers
Uday Staff answered 2 years ago

I don’t understand your requirement.
It is expected that when you convert a string to byte array and convert back the byte array to string, both the strings should always be equal. As an analogy you can consider that you have 100 rupees note which you convert into equivalent value in coins and then you convert the coins back to 100 rupees note, now the value of both the notes should be same. isn’t it? Similar is the case for strings.
The only case, where both strings might not be equal is when you use a different encoding for string to byte and byte to string conversion as shown in below program.
String str = “My string”;
byte[] theByteArray = str.getBytes(“UTF-8”);
System.out.println(“string to byteArray: ” + theByteArray);
String str1 = new String(theByteArray, “UTF-16”);
System.out.println(“byteArray to string: ” + str1);
if (str.equals(str1)) {
System.out.println(“equal”);
} else {
System.out.println(“not equal”);
}
The output of above program will be “not equal”.

Your Answer