• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ternary operators

 
Alpha Mak
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
> can we call methods in TERNARY OPERATORS ;
> e.g, x==y ? method1() :method2();
> ps explain with a example or two.
Such a powerful method such a little explaination.
> thanking you in advance
> Alpha.
 
Paul Stevens
Ranch Hand
Posts: 2823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The short answer is yes. You didn't ask for a good example
public class Temp {
public static void main(String[] args) {
Temp t = new Temp();
String s = 1 > 2 ? t.method1() : t.method2();
System.out.println(s);
}
public String method1() {
return "method1";
}
public String method2() {
return "method2";
}
}
 
Alpha Mak
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Paul for you reply
but ques is what if my method returns any other data type than string???
Originally posted by Paul Stevens:
The short answer is yes. You didn't ask for a good example
public class Temp {
public static void main(String[] args) {
Temp t = new Temp();
String s = 1 > 2 ? t.method1() : t.method2();
System.out.println(s);
}
public String method1() {
return "method1";
}
public String method2() {
return "method2";
}
}

 
Jennifer Warren
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
let me add to the question that if we can call any methods which do not return any thing.
thanks.
Jennifer
 
Jose Botella
Ranch Hand
Posts: 2120
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
to Jennifer
You can not add these kind of methods because in ? A : B ; A an B must evalute to something
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Jose is right...
Try compiling this piece of code. I have modified Alpha Mak's version.

Cheers!
Shyam

[This message has been edited by Shyamsundar Gururaj (edited September 06, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic