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.
Joined: Jul 07, 2008
Yes that makes sense.
subject: How do we decide on when to create primitive variables and when to create objects?