Subscribe to Dogstopper's Code Mania        RSS Feed

Know Your Datatypes

Icon 6 Comments
Because data is the foundation of computing, it is very important to understand how they work. Some of the most notorious hacks through hacker history have occurred because the programmer made an invalid assumption of the data. Take C's scanf() function. What happens when a user inputs a set of characters that is too large for the buffer? Well, the application will crash because there is pointer that could point to an invalid place in memory (that the application doesn't own).

The other day, I walked in and sat down at my computer to see that mostyfriedman has left me a unique challenge that I did get correct, but it certainly demonstrates my point VERY well. In the following application, will the program ever print "Less than 0"?
public void print(int x, int y) {

    if (x < 0 || y < 0)
	int sum = x + y;
	if (sum < 0) {
	    System.out.println("Less than 0");
	else {
	    System.out.println("Greater than 0");

The answer is yes. It could. Due to the maximum size of ints, this application could print less than. The maximum size for ints is 2,147,483,647. Thus, if I made x = 2,147,483,646 and y = 2, then suddenly, the int wraps around to the lowest possible value -2,147,483,648, which is much less than 0.
See all the fundamental Java types here:

Now, I am indicating that this is Java. However, languages like Python, Haskell, Clojure, and other dynamic languages take care of this issue by extending that range to the limits of the computer memory, but in lower-level languages, you must be far more careful.

So, the moral of this story? Know your data and know your datatypes.

Happy Programming!

6 Comments On This Entry

Page 1 of 1

gregwhitworth Icon

15 April 2011 - 08:11 PM
How come I can't give this guy a +1 in reputation?

mostyfriedman Icon

15 April 2011 - 08:41 PM
hey, that's mine :P

Dogstopper Icon

15 April 2011 - 08:51 PM
It really gave me a good example for the blog entry! Thanks Mosty!

mostyfriedman Icon

15 April 2011 - 08:57 PM
no problem :)

gregwhitworth Icon

16 April 2011 - 11:25 AM
Wait a second. So I can give respect for a comment but not a blog post. That doesn't make much sense.

Dogstopper Icon

16 April 2011 - 11:47 AM
It doesn't actually count - even on a comment. Thanks for trying, but I blog to share useful information, not for a number. I'm glad you thought it was useful! :)
Page 1 of 1

May 2018

20 212223242526

Recent Entries

Search My Blog

Recent Comments

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)