December 31 2013 by Kevin Bowersox

   When beginning to learn Java, early in your journey you will most likely encounter a discussion of the primitive data types.  An investigation of the primitive numeric data types will expose you to the primitives byte, short, int and long.  From their definitions, most individuals with no programming background can discern the following about these types:

These primitive data types only represent whole numbers (including negative numbers) aka Integers.

 

Each of these primitives can store a specific range of values with byte having the smallest range and long having the largest range.


   With these simple concepts established most beginners can declare and use these primitives without any further knowledge.  This article explores the fundamentals of how these primitives are stored in memory.  At this point, you may be asking yourself if it is really necessary to understand how Java stores a primitive data type.

   Grasping this low-level concept will provide a better understanding of concepts such as type overflow, memory management and reading/writing files.  This knowledge serves as the foundation for understanding bitwise operators and brings the programmer one step closer to the hardware.  A true appreciation and understanding of the language is gained from understanding how the language works at its lowest level.

 

   From a personal perspective, the more I work with third party frameworks such as Spring and Hibernate the more I yearn to master the 1s and 0s.


   The first clue about storing primitives can be found in the Java Language Specification, Section 2.3. Primitive Types and Values.  Within this section we find the definition of the Integral primitive types.  Let's specifically focus on the definition of byte, which is as follows:

 

byte, whose values are 8-bit signed two's-complement integers, and whose default value is zero

 

   For the seasoned programmer this definition is clear and concise, however a beginner may be intimidated.  What exactly is an 8-bit signed two's complement integer?  Let's discover its meaning by exploring the language and a bit of binary.


   First, let's evaluate the MIN, MAX and RANGE of a byte:

public class ByteExamples {

	public static void main(String[] args) {
		System.out.println("MAX:" + Byte.MAX_VALUE);
		System.out.println("MIN:" + Byte.MIN_VALUE);
		
		int byteCounter = 0;
		for(int x = Byte.MIN_VALUE; x <= Byte.MAX_VALUE; x++){
			byteCounter++;
		}
		
		System.out.println("RANGE:" + byteCounter);
		
		// Outputs:
		// MAX:127
		// MIN:-128
		// RANGE:256
	}
}

    Our simple example allows us to discern two facts about bytes.  First, there are 256 values assignable to a byte and second, those values range from -128 to 127.  Keep these two facts in the back of your mind as we move on to explore some related binary numbers.


   The definition of byte states that each byte is 8-bit.  This means that 8 binary digits, containing a value of either one or zero, make up a byte.  For example, 1111 1111 would represent the maximum value for an 8-bit binary number.  Let's explore this value through Java:

public class ByteExamples {

	public static void main(String[] args) {
		System.out.println("VALUE: " + Integer.parseInt("11111111", 2));
		//  Outputs;
		//  VALUE: 255
	}

}


    In our first example, we discovered the maximum value for a primitive byte is 127, however when calculating the maximum value for an 8-bit number, 1111 1111, we discover that 8-bits can represent a maximum value of 255.  This may cause you to question why the primitive byte's maximum value is lower than the maximum value that can be represented by an 8-bit number.  To answer this question lets explore the binary representation of the minimum byte value -128:

public class ByteExamples {

	public static void main(String[] args) {
		String b = Integer.toBinaryString(-128);
		System.out.println(b.substring(b.length() -8));
	}
	// Outputs:
	// 10000000
}

   Interestingly, we see that the binary equivalent of byte's (decimal) minimum value -128 is equivalent to the binary representation 1000 0000.  At this point, we must ask why a seemingly positive binary number 1000 0000, is equivalent to a negative decimal number.  The answer lies in how Java stores negative numbers in binary, the two's compliment.

    To create a negative number Java uses the two's compliment, which is created by first representing the absolute value of a number in binary.  For example, the absolute value of -128 (128) represented in 8-bit binary would be:  1000 0000.  Next, we perform a bitwise not (~) by flipping every bit: 0111 1111.  Then we add 1, leaving us with the two's complement: 1000 0000.

    At the lowest level, Java stores negative decimal numbers in binary using the two's compliment, while positive numbers are stored in their regular binary representation.  When storing binary numbers the most significant bit of the binary number is considered the sign bit.  In a binary number, the most significant bit will always be the left most bit since it contains the bit with the largest possible value.  In a two's complement number system the sign bit will be 0 for positive numbers and 1 for negative numbers, hence the minimum byte value's (-128) most significant bit in binary is a 1, 1000 0000.

    To convert a two's compliment number to decimal, we must reverse the operations.  Using 1000 0000 (-128 decimal) as our example, we first perform a bitwise not (~) by flipping every bit: 0111 1111.  Next, we add one to the inverted number:  1000 0000 or 128 decimal.  Finally, we negate the number since its most significant bit was a 1, leaving us with -128.

    We can now answer our lingering question, "Why is the primitive byte's maximum value (127) lower than the maximum value that can be represented by an 8-bit number (255)?"  The answer is because the sign bit occupies the most significant digit so that negative numbers can be represented in binary.  When storing values a byte only uses the first seven bits since the most significant bit stores the sign bit.  We can illustrate this via a Java example:

public class ByteExamples {

	public static void main(String[] args) {
		String b = String.format("%32s",Integer.toBinaryString(Byte.MAX_VALUE)).replace(' ', '0');
		System.out.println(b.substring(b.length() - 8));
	}
	// Outputs:
	// 01111111
}

    In this example we see that the sign bit is 0 and precedes seven bits 1111111 equivalent to 127 decimal.  It also should be noted that the sign bit sits in the most significant digit of the 8-bit binary number, which represents the 128 position or the absolute value of byte's minimum value.
   

   This article demonstrated how Java stores the primitive integral type byte.  While our exploration only covered the byte primitive the same concepts are applicable to larger primitive integral types such as short, int and long, however these types require more bits to represent larger numbers.  A main takeaway from this article is how primitive integrals use a two's complement to store negative numbers in binary, which includes the important sign bit.

    Admittedly, the primitive byte or binary numbers are most likely not a fixture in your daily work.  However, the concepts illustrated in this article are applicable to all integral types, which may appear more often during your daily endeavors.  There is also merit in understanding the basic concepts upon which the language is built, since they often arise in other languages and technologies we encounter.  The Java environment is lush with third party libraries and we often develop using libraries dependent upon other libraries.  While these libraries are extremely useful, they often leave us out of touch with some of the most basic concepts of the language.  To maximize our potential as developers, we must master the basics, which will serve as the building blocks for leveraging more complicated technology stacks.

Comments
Post a Comment
viagra pills commented on June 17 2018 12:01 PM
prescription drugs without prior prescription generic viagra canadian pharmacies shipping to usa
Email Site
personal injury lawyer los angeles commented on June 13 2018 22:27 PM
I am regular reader, how are you everybody? This post posted at this web page is genuinely nice.
Email Site
Pharmk87 commented on May 18 2018 10:29 AM
Hello!
Email Site
cialis commented on May 15 2018 11:49 AM
So happens. We can communicate on this theme. Here or in PM.
Email Site
cialis commented on May 15 2018 9:31 AM
I know nothing about it
Email Site
cialis online commented on May 15 2018 7:24 AM
Tell to me, please - where I can read about it?
Email Site
Johna186 commented on May 15 2018 7:11 AM
I really like your writing style, fantastic information, thanks for putting up dfgdfbggcegd
Email
cialis cheap commented on May 14 2018 19:15 PM
Excuse for that I interfere ? here recently. But this theme is very close to me. I can help with the answer. Write in PM.
Email Site
cialis cheap commented on May 12 2018 14:00 PM
Thanks for any other informative site. Where else may I am getting that kind of information written in such a perfect way? I've a undertaking that I am simply now running on, and I've been at the look out for such info.
Email Site
generic cialis commented on May 12 2018 12:13 PM
Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you could do with some pics to drive the message home a bit, but other than that, this is magnificent blog. An excellent read. I'll certainly be back.
Email Site
order cialis online commented on May 12 2018 10:27 AM
Hmm is anyone else encountering problems with the images on this blog loading? I'm trying to figure out if its a problem on my end or if it's the blog. Any responses would be greatly appreciated.
Email Site
cialis commented on May 12 2018 8:33 AM
you are really a good webmaster. The web site loading speed is amazing. It seems that you are doing any unique trick. In addition, The contents are masterpiece. you've done a wonderful job on this topic!
Email Site
generic cialis online commented on May 12 2018 6:45 AM
Good day! I know this is kinda off topic but I was wondering if you knew where I could locate a captcha plugin for my comment form? I'm using the same blog platform as yours and I'm having difficulty finding one? Thanks a lot!
Email Site
order cialis online commented on May 12 2018 4:57 AM
My brother recommended I may like this blog. He was once totally right. This post actually made my day. You can not consider simply how much time I had spent for this info! Thank you!
Email Site
generic cialis online commented on May 12 2018 3:07 AM
Hello There. I found your blog using msn. This is a really well written article. I?ll be sure to bookmark it and return to read more of your useful information. Thanks for the post. I will definitely return.
Email Site
buy cialis commented on May 12 2018 1:17 AM
These days of austerity and also relative stress and anxiety about having debt, many people balk against the idea of employing a credit card in order to make purchase of merchandise or perhaps pay for a holiday, preferring, instead only to rely on this tried in addition to trusted procedure for making payment - cash. However, if you've got the cash on hand to make the purchase in whole, then, paradoxically, that's the best time to be able to use the credit card for several factors.
Email Site
order cialis online commented on May 11 2018 23:25 PM
Great post. I was checking constantly this blog and I am impressed! Very helpful info particularly the last part :) I care for such information a lot. I was seeking this certain info for a long time. Thank you and good luck.
Email Site
buy cialis commented on May 11 2018 21:28 PM
Hi there! Would you mind if I share your blog with my myspace group? There's a lot of folks that I think would really appreciate your content. Please let me know. Thanks
Email Site
natural remedies for erectile dysfunction commented on May 05 2018 22:55 PM
Hello there, You have done a fantastic job. I will definitely digg it and personally suggest to my friends. I'm sure they will be benefited from this website.
Email Site
ed drugs commented on May 05 2018 12:40 PM
Very good blog you have here but I was curious if you knew of any discussion boards that cover the same topics talked about here? I'd really love to be a part of online community where I can get advice from other experienced individuals that share the same interest. If you have any recommendations, please let me know. Kudos!
Email Site
generic cialis commented on May 02 2018 20:53 PM
Quite good topic
Email Site
generic cialis commented on April 30 2018 9:17 AM
Hiya, I'm really glad I have found this information. Nowadays bloggers publish only about gossips and net and this is actually irritating. A good site with interesting content, this is what I need. Thanks for keeping this web-site, I'll be visiting it. Do you do newsletters? Can't find it.
Email Site
buy cialis online commented on April 28 2018 19:09 PM
Simply desire to say your article is as surprising. The clarity in your post is just spectacular and i could assume you're an expert on this subject. Well with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please carry on the enjoyable work.
Email Site
tadalafil commented on April 28 2018 12:07 PM
Aw, this was a very nice post. In thought I wish to put in writing like this moreover ? taking time and precise effort to make a very good article? however what can I say? I procrastinate alot and certainly not appear to get something done.
Email Site
cialis generic commented on April 28 2018 7:19 AM
I wish to convey my admiration for your kindness in support of individuals that require help with this one subject matter. Your real dedication to passing the solution throughout ended up being surprisingly useful and have truly enabled individuals like me to attain their endeavors. Your new insightful guidelines implies so much to me and further more to my mates. Best wishes; from each one of us.
Email Site
tadalafil commented on April 28 2018 3:39 AM
One more thing. I believe that there are quite a few travel insurance sites of reputable companies that allow you enter your journey details and find you the estimates. You can also purchase the international holiday insurance policy on the internet by using your own credit card. All you have to do is to enter all travel particulars and you can begin to see the plans side-by-side. You only need to find the system that suits your allowance and needs after which it use your credit card to buy the item. Travel insurance on the web is a good way to begin looking for a reputable company with regard to international travel cover. Thanks for expressing your ideas.
Email Site
cialis commented on April 28 2018 1:34 AM
Thanks for your posting. What I want to point out is that when you are evaluating a good on the net electronics go shopping, look for a web site with comprehensive information on critical factors such as the level of privacy statement, basic safety details, any payment methods, and other terms plus policies. Generally take time to investigate the help along with FAQ pieces to get a superior idea of the way the shop works, what they are capable of doing for you, and in what way you can use the features.
Email Site
tadalafil commented on April 27 2018 23:41 PM
Nice post. I learn something tougher on totally different blogs everyday. It's going to at all times be stimulating to read content from other writers and practice a bit of one thing from their store. I?d want to make use of some with the content material on my weblog whether you don?t mind. Natually I?ll give you a hyperlink on your net blog. Thanks for sharing.
Email Site
tadalafil generic commented on April 27 2018 22:06 PM
I must express some appreciation to you for rescuing me from this instance. After looking throughout the online world and obtaining ways which were not powerful, I was thinking my entire life was done. Living without the presence of strategies to the problems you've sorted out as a result of this article content is a critical case, as well as the kind which might have negatively damaged my entire career if I had not encountered your web page. Your competence and kindness in controlling a lot of stuff was very useful. I am not sure what I would've done if I hadn't come upon such a step like this. I can at this moment relish my future. Thanks for your time so much for your professional and effective guide. I will not think twice to refer your web page to anyone who will need care about this situation.
Email Site
cialis dosage recommendations commented on April 27 2018 21:29 PM
Hello.This post was extremely motivating, especially since I was browsing for thoughts on this issue last Saturday.
Email Site
5 mg cialis coupon printable commented on April 27 2018 16:00 PM
Very efficiently written article. It will be beneficial to anyone who utilizes it, as well as myself. Keep up the good work - can'r wait to read more posts.
Email Site
Buy Cheap Cialis commented on April 27 2018 10:58 AM
I have noticed that costs for online degree authorities tend to be an incredible value. For instance a full Bachelor's Degree in Communication in the University of Phoenix Online consists of 60 credits at $515/credit or $30,900. Also American Intercontinental University Online provides a Bachelors of Business Administration with a full study course element of 180 units and a cost of $30,560. Online studying has made taking your diploma much simpler because you might earn your own degree from the comfort of your abode and when you finish working. Thanks for all other tips I've learned through your site.
Email Site
erectile dysfunction treatment commented on April 26 2018 8:46 AM
Have you ever thought about adding a little bit more than just your articles? I mean, what you say is important and everything. However just imagine if you added some great pictures or video clips to give your posts more, "pop"! Your content is excellent but with images and clips, this blog could definitely be one of the most beneficial in its field. Fantastic blog!
Email Site
ed treatment commented on April 26 2018 7:20 AM
Heya i?m for the primary time here. I came across this board and I to find It really useful & it helped me out much. I am hoping to give something again and help others like you helped me.
Email Site
Viagra manufacturer coupon commented on April 22 2018 17:27 PM
Thanks! Ample info!
Email Site
order cialis online commented on April 15 2018 22:34 PM
Great work! That is the kind of information that are supposed to be shared around the internet. Disgrace on the seek engines for not positioning this post higher! Come on over and talk over with my website . Thanks =)
Email Site
Cialis online commented on April 06 2018 1:32 AM
Useful stuff. Cheers!
Email Site
Cialis generic commented on April 05 2018 15:55 PM
You expressed it wonderfully!
Email Site
Buy generic cialis commented on April 04 2018 14:04 PM
Many thanks, Numerous information.
Email Site
Generic cialis commented on March 25 2018 17:17 PM
If some one wishes to be updated with hottest technologies after that he must be go to see this web page and be up to date every day.
Email Site
Jodecy commented on January 17 2017 6:30 AM
Ppl like you get all the brisna. I just get to say thanks for he answer.
Email Site
Emmly commented on January 17 2017 6:03 AM
Now I'm like, well duh! Truly thnkufal for your help.
Email Site
Sparky commented on January 17 2017 5:09 AM
A good many vauelblas you've given me.
Email Site
Jady commented on January 17 2017 3:31 AM
This aritcle went ahead and made my day.
Email Site
Dreama commented on January 17 2017 2:43 AM
Hey, that's the grseteat! So with ll this brain power AWHFY?
Email Site
SallyImhoff commented on June 23 2015 6:48 AM
Hi admin, i see your website needs fresh posts. Daily updates will rank your page in google higher, content is king nowadays. If you are to lazy to write unique content everyday you should search in google for: Ightsero's Essential Tool
Email Site
Post a Comment
*Name
Email
Site
*Comment