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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With