9
  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)?

Sabaat Ahmad
  • 522
  • 1
  • 5
  • 10
  • 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. – WalterM Nov 27 '15 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. – wero Nov 27 '15 at 13:06
  • 5
    @WalterM do you suggest that Java developers do not feel concerned by memory management? – dotvav Nov 27 '15 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. – Joop Eggen Nov 27 '15 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. – Guillaume F. Nov 27 '15 at 14:21

2 Answers2

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).

Community
  • 1
  • 1
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.

rodolk
  • 5,606
  • 3
  • 28
  • 34