hello daniweb.. :)

I am learning JAVA and currently new to it, I am studying "The Complete Reference-JAVA" by Herbert Schildt.
In that book its written that using short or byte will save space, but there is no guarentee that Java won't promote those types into int internal anyway.
Remember TYPE DETERMINES BEHAVIOR NOT SIZE.

I didn't understand is type independent of size ..??? only depends on behavior??
in java int is of 4 byte whether it is machine dependent..??
Please explain me every thing related to this.:icon_eek:

That sentence in the book is indeed confusing. You should assume that Java will always use the type as you declare it. If you say int i = 0, Java will use an integer for that, and when you say short s = 0, Java will use a short for that.

The only time when Java will (maybe) change the type, is when you build your program, and that will only happen if the change optimizes your program a lot. You have no control in this, so you should always try to keep the types you declare as small as possible (use the types you need, and nothing more special).

The point it is making is that there is no guarantee about how Java will store those numbers. All that is guaranteed in the JAva language specification is their behaviour. So chosing byte, short or char to save space may be pointless because Java may chose to allocate a full 4 bytes when storing them. Having said that, this would only matter if you had a big array of such numbers, and it would break a lot of running applications if those suddenly started to take 2 or 4 times as much memory!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.