Reputation: 1
I have the below syntax:
public static String getName() {
return (fullName= firstName + " " + lastName);
}
and it throws an error. However, if I use
public static String getName() {
fullName=firstName + " " + lastName;
return fullName;
}
the problem is resolved.
Question:
Why is the assignment to fullName
not working as per #1 and why do I get an error on the field fullName
as fullName
is not being used if I use the #1 Syntax ??
Upvotes: 0
Views: 708
Reputation: 26
From the perspective of readability, and for your future and your good habits. You should write like this:
public static String getName() {
return firstName + " " + lastName);
}
Upvotes: 0
Reputation: 44
return (fullName = fullName=firstName + " " + lastName);
You should to separate this code. First you assign new value for full name (with only 1 assign operator =), then return full name.
Another way is just say:
return firstName + " " + lastName;
PS: Yes you're right, assign expression will run first, then it return the new value of full name.
Upvotes: 1
Reputation: 497
It is works for me. There is example of usage.
public class Test {
private static String fullName;
private static String firstName = "FirstName";
private static String lastName = "LastName";
public static String getName() {
return (fullName = fullName=firstName + " " + lastName);
}
public static void main(String[] args) {
System.out.println(getName());
}
}
But logically there is two mistakes:
fullName = fullName
Assigning field to itself doesn't makes any sense
Changing value in method called getName()
makes a lot of confusion for developers. See Side effect function for more details
Upvotes: 0