File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Creating Objects! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Creating Objects!" Watch "Creating Objects!" New topic
Author

Creating Objects!

Amir Ghahraei
Greenhorn

Joined: Jun 20, 2002
Posts: 5
Hello all,
I have a question regarding object creation.
The code is as follows:
class SomeClass {
String newString = new String(); //fine!

//But if I write
String anotherString;
anotherString = new String(); //(1)
//compiler will complain
//but inside a constructor it's fine again
SomeClass() {
String works;
works = new String();
}
}
Why does the compiler complain at line (1)?
Jessica Sant
Sheriff

Joined: Oct 17, 2001
Posts: 4313

Two things:
1st thing:
"Amir_Ghahrai"
Welcome to the JavaRanch! Please adjust your displayed name to match the JavaRanch Naming Policy. Particularly, it should be first name <space> last name.
You can change it here.
2nd thing;
You can declare and initialize a reference on a single line outside of a method.
But to initialize the reference on its own (without the declaration) -- the expression must be within a method (like a constructor).
Hope that helps, and again welcome to the JavaRanch!
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Though if you will put that line within a variable intialiser block then it will compile.
i.e {anotherString = new String()l}
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Creating Objects!