• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 238
  • Last Modified:

How to get the size of string in Java

Hi,
In my Java code I have string. And I get this string as the following:

java.lang.String rcm = g.getRcm();

Open in new window


Now, I would like to get the size of the string rcm in terms of KB?

Thanks,
0
Tolgar
Asked:
Tolgar
2 Solutions
 
CEHJCommented:
That would be something like
double kb = rcm.length() * 2 / 1024.0;

Open in new window

0
 
jimyXCommented:
Each char is one byte so you can read the length of your string and the result will be the number of bytes.
0
 
ALaRivaCommented:
From my understanding, the encoding and other factors will determine the calculation, it is not just 1 to 1 as JimyX stated.

CEHJ has good knowledge, so I'm assuming he's been down this road before, and maybe that's the closest representation to it's size or the default encoding of java.

Here's a decent thread discussing it - http://stackoverflow.com/questions/409765/does-a-strings-length-equal-the-byte-size

hth

- Anthony
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
CEHJCommented:
>>Each char is one byte

Each char in a java string is *two* bytes - it effectively uses UTF16 encoding
0
 
ksivananthCommented:
how abt converting to byte array and use its length to calculate actual size?
0
 
CEHJCommented:
>>how abt converting to byte array

Why do that?
0
 
ksivananthCommented:
>>Why do that?

not to worry abt enconding?
0
 
CEHJCommented:
>>not to worry abt enconding?

Well,

a. there are no encoding issues: a String is always UTF-16 (essentially)
b. turning it from a String into byte[] would bring up encoding issues, meaning the in-memory representation would vary depending on the encoding used
0
 
ksivananthCommented:
>>a String is always UTF-16

isn't just by default and not always?

>>meaning the in-memory representation would vary depending on the encoding use

isn't( in memory ) the KB represent?
0
 
ksivananthCommented:
looks like there is a tool... http://www.javamex.com/classmexer/
0
 
objectsCommented:
its not as simple as that :)
0

Featured Post

Never miss a deadline with monday.com

The revolutionary project management tool is here!   Plan visually with a single glance and make sure your projects get done.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now