2

Say I have an ArrayList of type String that stores numbers only. Am I wasting my resources? Is String bigger than int or short? I can't find the size of a String anywhere and came up with this dumb question that intrigues me.

Is short the most efficient data type for storing 5 digit numbers?

  • https://stackoverflow.com/questions/4385623/bytes-of-a-string-in-java – Héctor Jan 30 '18 at 14:59
  • 1
    String uses as much memory as it takes to store each character. the more characters, the more memory it uses – XtremeBaumer Jan 30 '18 at 14:59
  • A string is just an immutable `char[]`. A `char` is 16 bits, how many `char`s are used depends on the encoding, but for the max int value of 2147483647 you need 10 characters while this fits into one 32 bit int. More importantly, _why is this an issue_? This seems like code smell. – Salem Jan 30 '18 at 15:01
  • `short` is not at all the best type to store a 5 digit number. `Short.MAX_VALUE` (2^15-1) is 32767, which doesn't cover the full range of 0-99999. – Salem Jan 30 '18 at 15:02

3 Answers3

3

The size of a String object is very flexible. Each character in the String takes one or two bytes, so storing a 5 digit number is at least 5 bytes. Plus there is some overhead for the String object. On the other hand, an int is 32-bits which is only 4 bytes.

A more important issue is that it is difficult to perform arithmetic with numbers stored as strings. You will have to implement methods to add, subtract, multiply, and divide. With int you have built in operators.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
2

In Java 8 a String is intern just a char[] which contains all characters that are used in the String. In this case, the int with 32 bits is bigger than 1 char with 16 bit.

In Java 9 there is a byte[] instead of a char[] for a String

Now it's on you to figure out which is the more efficient type for you to use.

CodeMatrix
  • 2,124
  • 1
  • 18
  • 30
2

String and Integer are objects and int is primitive type. so Objects use alot more memory whereas primitive types don't. for example if you have a primitive type as:

int i = 5; 

for example in memory address 10 the value 5 will be saved and i knows address 10

but for objects as:

Integer i = new Integer(5):

the value of 5 will be saved in for example address 2 and address 10 (which is i variable) will reference to address 2 which takes more memory. When a new object is created, a composite memory block consisting of a series of consecutive blocks, one for each instance variable, is created which takes alot more memory.

String is an object, an special object but still an object . it's special because for example it doesn't need new

parsa
  • 987
  • 2
  • 10
  • 23