GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes doubt about strings creation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "doubt about strings creation" Watch "doubt about strings creation" New topic
Author

doubt about strings creation

Samarth Barthwal
Greenhorn

Joined: Feb 16, 2006
Posts: 23
In his article on String Literals Corey McGlone says that Strings created using new like:

are created during runtime.why cannot these be created during compilation time?
Are all other object references (for any user defined classes)created during runtime?

Is string created using:



created during compilation time or runtime?and why?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

All objects are created a runtime. The compiler emits code. The code must be loaded into a JVM and executed before any objects are created. No objects are created at compile time -- although the compiler might put code into a class file which results in an object being created more or less automatically.

A String literal "like this" is actually a String object. You don't have to create it explicitly with "new" -- it is created internally by the JVM when the code that first mentions it is executed, based on data in the class file, put there by the compiler. But it is still created while the program is running, as all objects must be.

If you explicitly create a String like this:

new String("literal")

then the "new String" part results in a copy being made of the existing object. If you see this in code, the virtually 100% of the time it is for one of two reasons:

1) The programmer is new to Java and doesn't know what they're doing

2) It's an SCJP test question.


[Jess in Action][AskingGoodQuestions]
Samarth Barthwal
Greenhorn

Joined: Feb 16, 2006
Posts: 23
I want to know that if for the primitive types like string,char,int if the objects are created simply without using "new" then why is it that java has defined the following methods:

Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Those classes are called wrapper classes. They are objects, not primitives. They are used to contain a primitive when an object is needed, like in a Collection.
 
GeeCON Prague 2014
 
subject: doubt about strings creation