10
  1. I would like to know which representation of a String (normal String or byte-array) would require more memory to be stored?

  2. A byte-array representation is available to me in my code. Should I convert this to a String before transferring it over the network (in response to an AJAX call)?

5
  • if it's already in byte format and you don't need it in a String form, then there's no need to convert it to a String. I'm not sure what your goals are, but it seems like you want to optimise prematurely? If you're worried about memory you wouldn't be using Java. Commented Nov 27, 2015 at 13:03
  • 1. can't be answered since it depends on too many things. 2. When you transfer something over the network it must be turned into bytes, therefore the answer is no, just use the byte representation. Commented Nov 27, 2015 at 13:06
  • 6
    @WalterM do you suggest that Java developers do not feel concerned by memory management? Commented Nov 27, 2015 at 13:06
  • String in java holds Unicode by design (=can hold all combinations of scripts). Using chars of 2 bytes, UTF-16. As bytes must be associated with some encoding, conversion to bytes must indicate the target encoding, and a conversion will take place. On that basis you can decide yourself. Commented Nov 27, 2015 at 14:02
  • Strings are basically a standardized array of bytes, so you can use them easily in your code, not worrying about encoding. An array of bytes is binary, and can contain any encoding. Commented Nov 27, 2015 at 14:21

2 Answers 2

3

1 => see: What is the Java's internal represention for String? Modified UTF-8? UTF-16?

2 => multiple options if it's short, simply transfer a string if it's ascii, otherwise, convert it :

String serial= DatatypeConverter.printBase64Binary(bytes)

and you can use GET

decoding is possible with java, php, ...

if it's big, use POST, and binary (or native).

Sign up to request clarification or add additional context in comments.

Comments

0

For 2: If it is a response to an AJAX request most probably you need to send an HTTP response and to send an HTTP response usually, in a Servlet for example, you use an OutputStream object (http://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html) or a PrintWriter and use write method to write the response.

If you use HttpServletResponse you may directly write a String with a PrintWriter

HttpServletResponse httpServletResponse;

...

String responseToClient = "HOLA";
httpServletResponse.getWriter().write(responseToClient);

If you use method getOutpuStream then you will obtain a SevletOutputStream and write method receives a byte array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.