4

So I just started my second programming class in Java, and this is the example given to us by the professor to demonstrate loops and arrays.

public class ArraysLoopsModulus {                       
public static void main(String [ ] commandlineArguments){                   
  //Declare  & Instatiate an Array of 10 integers
  Integer[ ] arrayOf10Integers = new Integer[10];

  //initialize the array to the powers of 2
  Integer powersOf2 = new Integer(1);   
  for(int i=0;i<arrayOf10Integers.length;i++){
    arrayOf10Integers[i] = powersOf2;
    //multiply again by 2
    powersOf2 = powersOf2 * 2;
  }

  //display the powers of 2     
  System.out.println("The first 10 powers of 2 are: ");
  for(int i=0;i<arrayOf10Integers.length;i++){
    System.out.print(arrayOf10Integers[i] + ", ");
  }  
}
}

Having looked through all of the upcoming examples, it seems that my professor never uses primitive data types, he always uses the equivalent object class (in this case Integer instead of int and Integer[] instead of int[]). Also I understand that some situations require the use of objects. My questions are:

What possible reason is there for always using the object? Especially in this simple case when the use of the primitive seems to fit better

Is it a bad habbit to always do this? Should I always use the objects just to make him happy, but know in real life to use the primitive data types when possible

Would this example I gave be considered bad programming?

Thanks

EDIT: Thanks for all of the great answers, I (a beginner) just needed confirmation that what I was looking at here was not the best way to code.

4
  • 3
    It seems that your professor doesn't know about autoboxing. Because this Integer powersOf2 = new Integer(1); is redundant.
    – Andremoniy
    Jan 11, 2013 at 18:19
  • 2
    I like and agree with the answer here: stackoverflow.com/a/2509478/1201423
    – cklab
    Jan 11, 2013 at 18:22
  • 3
    I think your professor does not use autoboxing until he teached about the autoboxing idea.
    – MrSmith42
    Jan 11, 2013 at 18:22
  • 1
    we covered autoboxing in the first class with a different professor. im not so sure about this second professor, questionable code
    – Kailua Bum
    Jan 11, 2013 at 18:35

9 Answers 9

12

What possible reason is there for always using the object?

There is no reason, this code is ugly. Primitives as objects have advantage when using collections, but they are not used in your example.

Especially in this simple case when the use of the primitive seems to fit better

Absolutley correct, Objects in this case are worse, they need more memory and have no advantage in your example.

Is it a bad habbit to always do this?

Yes, you should only use Objects (boxed primitives) if they are needed. Beside use in collections, such object can also be null, this is an advantage which can be used as "value not (yet) existing", etc.

Should I always use the objects just to make him happy, but know in real life to use the primitive data types when possible

No, tell him that this makes no sense. But keep in mind, that your professor never wanted to give progarmming lessons. He was probably "forced" to do so.

Would this example I gave be considered bad programming?

Yes. maximum bad!

2
  • 2
    The ability to tell null/"no data" apart from 0 is sometimes of some value :)
    – Affe
    Jan 11, 2013 at 18:34
  • @Affe Updated considering your comment.
    – AlexWien
    Jan 11, 2013 at 18:46
9

From Effective Java by Joshua Bloch,

Item 49: Prefer primitive types to boxed primitives. There are three main differences between primitive types and boxed primitives:

  • Primitives have only their values, whereas boxed primitives have identities distinct form their values.

  • Primitive types cannot be null, but boxed primitives can.

  • Primitive types are more space and time efficient than boxed-primitives.

Care must be taken with using the == operator with boxed primitives as, with any other reference type, it compares identity and you almost certainly want to be comparing value. If a boxed primitive is compared to a primitive with the == operator, the primitive type is boxed and the identities compared, so care must also be taken here.

The process of boxing and unboxing, especially in a loop can serious impede performance.

Basically, boxes primitives should be avoided unless primitive types cannot be used, such as in collections or as parameterised types.

I hope this helps you understand the difference.

4

Most people agree you should use primitives when you can. To play the devil's advocate, I thought of one advantage: They fail faster.

This code will throw a null pointer exception because you forgot to initialize myInteger:

private Integer myInteger;

public void run () {
    int myNewInt = myInteger + 5;
}

If you used an int, it'd proceed and it'd be harder to notice the mistake you made.


Here's another similar advantage I just ran into: It lets you represent the absence of data. I have a method that returns a configuration option. It has a signature that returns a boolean. Turns out the configuration option didn't exist in the system. But instead of telling me that, it just defaults to false (it has to pick something). As a result, I thought this value was set to false but turned out it was missing. The bug would have been more obvious if the method returned a Boolean.

1
  • @danilo Like I said, I was playing the devil's advocate. But I'd still prefer my code to explode if I forgot to do something instead of run in a state I never intended. Aug 20, 2019 at 20:51
1

E.g. primitives cannot be stored in Collectins.

Ok autoboxing helps, but hat is only wrapping them by the compiler instead of your own.

1

No, you shouldn't use Object wrappers of primitive types anywhere:

1) object equivalents use more memory then primitive types.

2) it could be cause of invalid comparing of two Integer objects - you should compare them, using equals method - it is not conveniently.

The only sensible reason for using Object wrappers is generics where you have to use some Class. For example such collections as List<Integer> or Map<Integer, Double>.

Another reason is if you have to store null value of variable instead of any numeric.

Provided block of code has a lot of redundant pieces.

1

Primitives are more space efficient, as the object wrappers create a new Object just to hold the same primitive you'd normally work with. Java has a lot of optimizations these days that make your professor's code not totally slow/broken, but it's certainly a bad practice.

In general, you should use primitives wherever you need them, unless you discover that you need object support, notably like @MrSmith42 suggests, if you want to store primitives in a Java Collection, like an ArrayList.

There's rarely any good reason to create an array of wrapper objects. Primitive arrays are very space efficient, arrays of objects lose all of that efficiency.

1

Contrary to popular opinion here, I am with your professor on this one. I prefer using the primitive wrapper objects much of the time. I think it comes down to programming style.

Example: I have a method that calls up the database to get an int. The method returns an Integer object. If the int doesn't exist it can return a null object. If it returns a non-null object then I know that the item exists in the database and is a valid number.

With a primitive you have to return a number, or throw an exception, but sometimes neither of these is appropriate.

So I do think there are plenty of valid reasons for using the wrapper-type objects. Most people's reasons for not using them is that they don't perform as well. This is often premature optimisation and in a real-life code base writing simple, robust code is usually far more important (depending on the application).

0
powersOf2 = powersOf2 * 2;

How about shifting bytes?!

//convert to primitive than someting like :

powersOf2  = powersOf2 << 2; 
0

According to Java documentation on The Number Classes tutorial it specifies only three reasons that you MIGHT want to use a Number object rather than a primitive. I would assume that any other reasons that not listed below will then be considered bad programming.

  1. As an argument of a method that expects an object (often used when manipulating collections of numbers).
  2. To use constants defined by the class, such as MIN_VALUE and MAX_VALUE, that provide the upper and lower bounds of the data type.
  3. To use class methods for converting values to and from other primitive types, for converting to and from strings, and for converting between number systems (decimal, octal, hexadecimal, binary).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.