0

So, I was wondering what the difference was between this:

first = "Hello!" 

and:

String first = "Hello!"
3
  • What do you mean, specifically? Commented May 26, 2012 at 1:18
  • 2
    If you are trying to learn to program in Java (or just to read Java code) then you need to get / read a text book, or do the Oracle Java tutorials. If not, the correct answer won't make much sense to you. Commented May 26, 2012 at 1:46
  • Context can make a world of difference. Commented May 26, 2012 at 2:02

5 Answers 5

10

The former assigns to a declared variable; the latter declares and assigns a variable.

Sign up to request clarification or add additional context in comments.

1 Comment

given the wording of the question, this would seem to be the most correct answer
1

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...

1 Comment

Unless its preceded by String first;
1

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.

Comments

1
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!"

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.