java - primitives vs wrapper class initialization -


what difference between declaring int's below. cases suits usage of different types

int     = 20; integer = 20; integer = new integer(20); 

please note : have goggled , found first going create primitive int.second going carry out auto boxing , third going create reference in memory.

i looking scenario explains when should use first, second , third kind of integer initialization.does interchanging usage going have performance hits

thanks reply.

the initialization in 1st case simple assignment of constant value. nothing interesting... except primitive value being assigned, , primitive values don't have "identity"; i.e. "copies" of int value 20 same.

the 2nd , 3rd cases bit more interesting. 2nd form using "boxing", , equivalent this:

integer = integer.valueof(20); 

the valueof method may create new object, or may return reference object existed previously. (in fact, jls guarantees valueof cache integer values numbers in range -128..+127 ...)

by contrast new integer(20) always creates new object.

this issue new object (or not) important if in habit of comparing integer wrapper objects (or similar) using ==. in 1 case == may true if compare 2 instances of "20". in other case, guaranteed false.

the lesson: use .equals(...) compare wrapper types not ==.


on question of use:

  • if i int, use first form.
  • if i integer, second form best ... unless need object != other instances. boxing (or explicitly calling valueof) reduces amount of object allocation small values, , worthwhile optimization.

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -