• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How do we decide on when to create primitive variables and when to create objects?

 
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
How do we decide on when to create primitive variables and when to create objects?
Can you explain it with sceanario's
 
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Sowm Herur wrote:How do we decide on when to create primitive variables and when to create objects?
Can you explain it with sceanario's



It's a question of performance. Primitives occupy less space and are faster.

But this doesn't mean you should always prefer primitives. At some point introducing your own type (class, enum or interface) starts making sense.

Say for example you want to work with complex numbers. A complex number consists of two doubles. Now should you handle a complex number as two separate doubles, or should you introduce a class like,



I'd say this is a pivot case when you must start seriously consider introducing a type rather than using primitives. Otherwise you're not utilizing the abstraction powers of OO in Java and your program becomes harder to read and more prone to errors.

There's another reason not to use a primitive, a primitive is very general. It can be used for lots of purposes. Say you want to represent temperature. You can use a double or you can introduce a type,



A double can be anything but a type called Temperature really makes a statement about what it is. And because of this the Java type checking can kick in and help you avoiding errors.

So in summary, primitives are used for speed and because they're small, but at some point the advantages of abstraction tilts the scale in favour of own types.
 
Sowm Herur
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes that makes sense.

Thanks,
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic