Java – is there any reason to always use objects instead of primitives?

So I just started to write the second programming class in Java. This is an example that the professor showed us 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] + ",");
  }  
}
}

After looking at all the upcoming examples, my professor never seems to use the original data type. He always uses the equivalent object class (integer instead of int and integer [] instead of int []) in this case In addition, I understand that some situations require the use of objects My question is:

The possible reason is that the object is always used? Especially in this simple case, it seems more appropriate to use primitives

Isn't it bad to always do this? Should I always use these objects to make him happy, but in real life, I should know to use the original data type when possible

Do I see this example as bad programming?

thank you

Editor: thanks for all the great answers, I just need to make sure what I see here is not the best coding method

Solution

For no reason, this code is ugly Primitives as objects have advantages when using collections, but they are not used in the example

Absolutely. In this case, objects are worse. They need more memory. They have no advantage in your example

Yes, you should only use objects (boxed primitives) if necessary In addition to being used in collections, such objects can also be null, which is an advantage and can be used as "value does not exist (not yet exist)", etc

No, it's no use telling him But remember, your professor never wants to give you a preschool course He may have been "forced" to do so

Yes The biggest bad!

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>