Reputation: 17
So, I was wondering what the difference was between this:
first = "Hello!"
and:
String first = "Hello!"
Upvotes: 0
Views: 131
Reputation: 4855
first = "Hello!"
will not compile correctly because it doesn't have a type. In Java, when you create a variable (in this instance called 'first'), you must give it a type such as String, int, long, et cetera. Because the type wasn't given, it doesn't know what to do. So, when you create the variable, you must use String first = "Hello!"
You don't need to give the type when the variable is already declared. For example,
String first = "Hello!"
first = "Goodbye!"
first will now be "Goodbye!"
Upvotes: 1
Reputation: 14815
Not really sure what you're asking. In your first example: first = "Hello!"
you aren't declaring first
, so if you run only that line of code, it will not work. Assuming you declared first
as a String, then both examples are the same. And there is no primitive string
type like there is with int
and Integer
. String is always an object.
Upvotes: 1
Reputation: 4704
At first glance there is no other difference than the first variable is declared in another line probably an instance variable?
In memory the strings are being pooled so that should be it.
Upvotes: 0
Reputation: 225281
The former assigns to a declared variable; the latter declares and assigns a variable.
Upvotes: 10
Reputation: 974
I don't think this:
first="Hello!"
will compile as the compiler will throw an error asking for the type of first. Java is a strongly typed language - each variable needs a well-defined type. I'm ignoring generic types like E for the moment...
Upvotes: 1