Search code examples
javastringcapitalize

How to take a string and return the capitalized format of a word


int length = s.length();

if (length = 0){
    return s;
}

else {
    return s.charAt(0).toUpperCase()+ s.substring(1);
}

I get two errors saying:

if (length = 0){
^^^^^^^^^^
Type mismatch: cannot convert from int to boolean


return s.charAt(0).toUpperCase()+ s.substring(1);
       ^^^^^^^^^^^^^^^^^^^^^^^^^
Cannot invoke toUpperCase() on the primitive type char

Plus, if it's an empty sting it should just return it. That's why I'm using an If-Else statement.


Solution

  • if (length = 0) should be if (length == 0)

    You're assigning the value 0 to length and not comparing it to 0.

    I recommend you to take a look at this:

    At run time, the result of the assignment expression is the value of the variable after the assignment has occurred. The result of an assignment expression is not itself a variable.

    This way, your if is never satisfied since the value inside it evaluated to the value of the assigned (0 in this case), so your program goes to the else, and there you should:

    return Character.toUpperCase(s.charAt(0)) + s.substring(1);