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

6 Answers 6

3

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);
1
  • 1
    Perfectly explained! Thank you :)
    – Kimmm
    Apr 6, 2013 at 6:58
2

In your if statement, you are assigning the value 0 to length. Because of this your compiler is complaining, because it expects a boolean expression, and not an int in the if statement (assignment returns the value it is assigning, which is why it mentions the int).

You mean to be evaluating a boolean expression by using == instead.

The second issue is because charAt(int) returns a char primitive, which doesn't have any methods.

In this case you probably want to utilize Character.toUpperCase(char) on the first character of your String and appending the rest.

2

you're missing the == in the if statement

charAt(0) returns a char, one way to make this a string is Character.toString(c)

0

Change it to this:

if (length == 0) {
    return s;
}

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

Note: if the length of the string is exactly 1, you'll still get an error, because of s.substring(1). You might want to add an additional condition for when the length of the string is exactly 1.

0

This line:

if (length = 0) {

means "I want to set the length to zero". But what you want is

if (length == 0) {

which means "Is the length equal to zero?"

The first statement eventually results into an exception as you're passing an integer into a place where boolean is expected.

0

Maybe you can try this:

String s = "testing";
String upper = s.toUpperCase();
System.out.print(upper);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.