You are here: irt.org | BBS | Re: New Help with 2 Lines of Code! [This BBS is closed]
Posted by Stephen Saunders on August 07, 1998 at 13:20:39:
In Reply to: New Help with 2 Lines of Code! posted by Metin on August 06, 1998 at 14:38:28:
: What is wrong when I try to change the value of a global variable
: "k". The compiler tells me that I cannot reference member "k"
: without an object.
: Am I not creating a new object when I say "new String ()"?
: Thank You for any suggestions.
Let me oversimplify: Java, being as strictly object-oriented as it is, will not allow you to do any sort of memory allocation unless it is done within a method defintion. Which means you should never see the keyword "new" outside of a method.
Cheers,
Stephen
New code:
class test
{
String k = null; // no memory allocation here, just variable declaration
public static void main (String args[])
{
k = "Hello World";
System.out.println (k);
}
}
---
PS - Note that the two lines...
k = "Hello World";
k = new String ("Hello World");
... are the same thing. Seeing as how Strings are so often used and manipulated, the Java team built in a whole suite of shortcuts that you can use. The former line above is one of those shortcuts.
---
Old code:
class test
{
String k = new String ();
public static void main (String args[])
{
k = "Hello World";
System.out.println (k);
}
}
Follow-ups:
You are here: irt.org | BBS | Re: New Help with 2 Lines of Code! [This BBS is closed]