3 Replies Latest reply: May 4, 2012 3:10 PM by rp0428 RSS

    What is the basic need and use of int and Integer , two different types ?

    bootstrap
      Hello,
      i am wondering if there are value types like int, byte , short ,bool ...etc then why there exists Integer , Short , Boolean etc as classes ?
      At which scenario use of any one say Boolean cannot be overlooked over there primitive counterpart ?
      Can you please help me .
        • 1. Re: What is the basic need and use of int and Integer , two different types ?
          aksarben
          There are many use cases, but the big reason I personally prefer classes over primitives is to detect programming errors. My rule of thumb is to always use classes instead of primitives for class variables. For example, let's say you have a class with a int variable called "length." While you're debugging, you notice that the value of "length" is zero. The problem here is: You can't tell if the length really IS zero, or your code just forgot to initialize it. If length were an Integer instead of an int, there would be no doubt about whether it was initialized. If it's null, it wasn't initialized.

          An even worse scenario is that you DON'T notice that the "length" zero, and your program runs without crashing. However, because the int length was not initialized, the program is silently producing incorrect output, wrong behavior, etc.. However, you don't KNOW it's wrong because it SEEMS to run smoothly. If the length variable had been declared as an Integer instead of an int, your program would probably have crashed the first the variable was used, because it null (would most likely throw a null pointer exception).

          There is no significant performance hit for using a class instead of a primitive, in probably well over 95% of all apps you'll ever see. In a corporate environment, for example, the logjams are usually databases & network latency, not CPU time.

          So back to my rule of thumb: Prefer classes over primitives whenever possible.
          • 2. Re: What is the basic need and use of int and Integer , two different types ?
            bootstrap
            Thanks aksarben .
            Are there only 8 primitive types in current version of java language ?
            • 3. Re: What is the basic need and use of int and Integer , two different types ?
              rp0428
              The answer to that is in the Java Language Specification
              See section 4.2. Primitive Types and Values
              http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2