This site requires JavaScript, please enable it in your browser!
Greenfoot back
xchange
xchange wrote ...

2017/3/31

Necessity for NEW

xchange xchange

2017/3/31

#
Dear All, Being a novice in GF, I find NEW confusing. AFAIK, it is meant to create a new object but isn't the object created at declaration? Take the following snippet for example: String s1; s1="Write Once"; String s2 = new String(); s2="Run Anywhere."; System.out.println(s1 + " " + s2); Both strings are created and work just fine - so what is NEW used for? What does it do? Thank you for your time, --- XC
Super_Hippo Super_Hippo

2017/3/31

#
xchange wrote...
AFAIK, it is meant to create a new object but isn't the object created at declaration?
This is true for strings, yes. But when are you trying to create an instance of an Actor subclass for example, you will need the 'new' keyword.
danpost danpost

2017/3/31

#
Actually, the String class is a special case -- an exception to the rule, you might say. The Java tutorials say the following about strings:
In addition to the eight primitive data types, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such.
For any class that is not String or one of the primitive types corresponding classes (Byte, Integer, Float, Double, etc), creating an object of the class will requires the 'new' keyword, suffice it to say, for now.
You need to login to post a reply.