• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Creating Objects!

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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)?
 
Sheriff
Posts: 4313
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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!
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Though if you will put that line within a variable intialiser block then it will compile.
i.e {anotherString = new String()l}
 
reply
    Bookmark Topic Watch Topic
  • New Topic