Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java object creation syntax efficiency?

Tags:

java

syntax

This may sound really basic. But I'm brand new to Java. With the few initial hours of learning I've put in so far, I'm continuously perplexed by the redundancy in the syntax of a new object declaration:

TypeName a = new TypeName();

In particular,

String s = new String("abc");
Character c = new Character("A");

Why in the world would someone want to type the keyword TypeName (eg. String, Character, etc...) twice? I understand there are short-hands of:

String s = "abc";
char c = "A";

But these are exceptions rather than rules. So can any one enlighten me please? Thx.

like image 886
Zhang18 Avatar asked Aug 31 '10 18:08

Zhang18


People also ask

Is object creation expensive in Java?

Object creation in Java is one of the most expensive operation in terms of memory utilization and performance impact. It is thus advisable to create or initialize an object only when it is required in the code.

What is the syntax for creation of object in Java?

Using new Keyword The syntax for creating an object is: ClassName object = new ClassName();

Is object creation expensive?

Object creation is considered as costly because it consumes your memory.As a result of this, program will suffer from lack of resources(memory) and it become slow.

Which methods are used to reduce object creation?

In java we can avoid object creation in 2 ways : Making the class as abstract, so we can avoid unnecessary object creation with in the same class and another class. Making the constructor as private ( Singleton design pattern ), so we can avoid object creation in another class but we can create object in parent class.


1 Answers

Because sometimes you want to do something like:

// Explicitly force my object to be null
String s = null;

or

// Cast a child class to its parent
MyParentClass mpc = new IneritedClassFromParent();

or

// Store and access a concrete implementation using its interface
ISomeInterface isi = new ConcreteInterfaceImplementation();

In other words, just because you declare a type to store doesn't always mean you want it initialized with a new instance of that class.

You may want to use a new instance of a child class when using inheritance or an Interface Implementation when using Interfaces.

Or sometimes you may want to explicitly force something to be null initially and fill it later.

like image 145
Justin Niessner Avatar answered Oct 16 '22 01:10

Justin Niessner