Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason to always use Objects instead of primitives?

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.

like image 325
Kailua Bum Avatar asked Nov 27 '22 11:11

Kailua Bum


1 Answers

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!

like image 117
AlexWien Avatar answered Dec 15 '22 02:12

AlexWien