Mastering Java: The Ultimate Quiz for 'Thinking in Java'

Disable ads (and more) with a membership for a one time $2.99 payment

Mastering Java: The Ultimate Quiz for 'Thinking in Java'. Dive deep into Java with multiple-choice questions. Challenge yourself with quiz questions designed to test and improve your understanding of the 'Thinking in Java' book. Get ready for your exam!

Practice this question and more.


What method is used to convert a String to a byte array?

  1. toString

  2. toByteArray

  3. getBytes

  4. asString

The correct answer is: getBytes

A String is an array of characters, and in order to convert it into a byte array, we need to use a method that returns an array of bytes, rather than a String. toString(), asString(), and toByteArray() all return Strings, which makes them incorrect. The correct method is getBytes(), which actually converts the String into an array of bytes.