Take the 2-minute tour ×
 public String withoutEnding(String str){
     return (boolean)(str.length() <= 2) && "" || str.substring(1,str.length() - 1);

rather than

 public String withoutEnding(String str){
     if (str.length <= 2)
       return "";
    else return str.substring(1,str.length() - 1)

It would error, the first one. I started Java in my AP Computer Science Class, though I have some knowledge on coding, but this is annoying me and I don't exactly know how to word my question to search on Google, so sorry if this may be found on another article.

But just wondering why the first one would not work.

share|improve this question
What is your method's return type and what are you returning? –  Sotirios Delimanolis Oct 17 '13 at 23:19
you should learn ternary operator –  mohsin azeem Oct 17 '13 at 23:22
What kind of compiler messages did you get when you tried it? –  Joshua Taylor Oct 17 '13 at 23:26

1 Answer 1

up vote 5 down vote accepted

The && and || logical operators only work on boolean values. "" and str.substring(1,str.length() - 1) aren't boolean, so it's a compiler error.

A valid, compact way of writing what you want would be to use the ?: ternary operator (scroll down about half way in that linked page):

return (str.length() <= 2) ? "" : str.substring(1, str.length() - 1);

The form is basically, condition ? trueValue : falseValue

share|improve this answer
What if I were to have multiple conditions? condition ? (second_condition ? : true : false) : (third condition ? : true : false) –  wateraura Oct 17 '13 at 23:34
The condition can be any boolean expression, even if it's complex. So something like ((condition1 && condition 2) || condition3) ? valueIfTrue : valueIfFalse would work. –  rgettman Oct 17 '13 at 23:36

Your Answer


