• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

doubt about strings creation

 
Samarth Barthwal
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Samarth Barthwal
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic