0

In my simple java program I convert an UTF-8 string to byte array with getBytes() function, and I run System.out.println() command. When I convert this UTF-8 string in PowerShell to byte array, and I run Write-Host command, the strings aren't equal.

This is my Powershell code:

System.BitConverter]::ToString([System.Text.Encoding]::UTF8.GetBytes("1234AbCd"))

This returned with this string: 31-32-33-34-41-62-43-64c

In Java:

String message;
message = "1234AbCd";
System.out.println(message.getBytes(StandardCharsets.UTF_8));

This returned with this string: [B@2401f4c3

What's the problem?

Abra
  • 19,142
  • 7
  • 29
  • 41
machobymb
  • 9
  • 2
  • 3
    Unless you're using Java 19, `getBytes()` probably doesn't return UTF-8 and you shouldn't use it. It returns whatever the "platform default" is which for you is probably Windows 1252. If you care about which encoding you get, use `getBytes(StandardCharsets.UTF_8)`. (If you don't care which encoding, java.util.Random is an efficient source of random bytes.) – David Conrad Jun 06 '22 at 19:57
  • @DavidConrad Actually [UTF-8 is the default as of Java 18.](https://www.oracle.com/java/technologies/javase/18-relnote-issues.html#JDK-8187041) – VGR Jun 07 '22 at 00:42
  • 3
    *I convert an UTF-8 string to byte array* - this is meaningless. if you have a Java String, it's not "UTF-8", because Strings are made of chars, and the encoding is always UTF-16. UTF-8 is a sequence of bytes, so if you've got some UTF-8, it's already bytes. 'String.getBytes(UTF_8) is how you convert **from** a String (UTF-16) **to** a byte-oriented encoding such as UTF-8. – dangling else Jun 07 '22 at 02:54
  • @VGR Whoops, got the version mixed up. Thank you! – David Conrad Jun 07 '22 at 17:37
  • 2
    `[B@2401f4c3` is the `toString()` of a byte array (`[B`) with identity hash code (`2401f4c3`), this has absolutely no relation to the value of the array. If you want to print the array, use `Arrays.toString(message.getBytes(StandardCharsets.UTF_8))`. See also [What's the simplest way to print a Java array?](https://stackoverflow.com/questions/409784/whats-the-simplest-way-to-print-a-java-array). However, I don't see why you wouldn't just print message directly. – Mark Rotteveel Jun 08 '22 at 10:42

0 Answers0