Vivek Sharma
Vivek Sharma

Reputation: 1

The assignment to a variable name has no effect

I have the below syntax:

1

public static String getName() { 
    return (fullName= firstName + " " + lastName);
}

and it throws an error. However, if I use

2

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

Answers (3)

TraXD
TraXD

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

berong91
berong91

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

Andrii Liubimov
Andrii Liubimov

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:

  1. fullName = fullName Assigning field to itself doesn't makes any sense

  2. Changing value in method called getName() makes a lot of confusion for developers. See Side effect function for more details

Upvotes: 0

Related Questions