aspose file tools*
The moose likes Java in General and the fly likes How do we decide on when to create primitive variables and when to create objects? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "How do we decide on when to create primitive variables and when to create objects?" Watch "How do we decide on when to create primitive variables and when to create objects?" New topic
Author

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

Sowm Herur
Ranch Hand

Joined: Jul 07, 2008
Posts: 32
How do we decide on when to create primitive variables and when to create objects?
Can you explain it with sceanario's
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
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

Joined: Jul 07, 2008
Posts: 32
Yes that makes sense.

Thanks,
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How do we decide on when to create primitive variables and when to create objects?