1

I am wondering if it's recommended always to use primitive types such as int when defining class attributes or should I wrapper classes instead of.

class Test{
    private final int id;

    /**
     * Class constructor
     * @param id
     */
    Test(int id) {
      this.id = id;
    }
  }
noname
  • 565
  • 6
  • 23
Leandro Maro
  • 325
  • 1
  • 12
  • 1
    How else would `id` be defined? – ruohola Oct 04 '19 at 14:50
  • 3
    So wouldn't your "wrapper class" have the primitive type in that case, breaking your proposed best practice? – Tom Faltesek Oct 04 '19 at 14:50
  • 1
    Using of boxed variables makes sense if they can be `null` – Alex Salauyou Oct 04 '19 at 14:53
  • By "wrapper class", do you mean `Integer` instead of `int`? If so, it kind of depends. In any situation where you don't want a default value, or when you want to allow null values, using the class wrapper instead of the associated primitive is preferred. – Jordan Oct 04 '19 at 14:54
  • You mean `int` vs `Integer` ? In most cases it is easier and faster to just use primitives (IMHO) though the wrapper classes do have their advantages. For example `Boolean` can be `null` which basically gives the boolean "true-false" construct a third state. I guess it depends only on your use case. An `id` for example might be so simple that `int` is sufficient. – GameDroids Oct 04 '19 at 14:55
  • also: The Wrapper classes provide a nice set of methods you can use on the values! – GameDroids Oct 04 '19 at 14:57
  • I am asking if to defining class attributes should I use int or Integer in cases like these. – Leandro Maro Oct 04 '19 at 15:02
  • 1
    @LeandroMaro And the answer is that it depends on what you want to do. There is no one general answer. – ruohola Oct 04 '19 at 15:03
  • 1
    maybe [this post](https://stackoverflow.com/q/8419860/896249) can be of interest to you - it discusses the usage of memory of the wrapper classes – GameDroids Oct 04 '19 at 15:03
  • @GameDroids it's the answer I was looking for. – Leandro Maro Oct 06 '19 at 19:32

1 Answers1

-1

It depends on what you need to do... If it's important to you to hold null values so you should use wrappers... Else you could as well use primitive... If you don't know if you need null or not then it's better to use primitives to avoid getting NPE.

Thiago E S
  • 75
  • 3