Tuesday, 21 August 2007

Advanced ternary conditions in Java

Recently i came across Paul's article describing "Advanced ternary operators in javascript .I believe that article was really nice and explored a simple but powerful way of calling multiple functions by use of ternary operations and so avoiding boring endless if/else loops.

As this is my first article ever in my life i try to replicate the same in java and give an example.Though nothing great stuff here but it may help to anyone if at all but gives a moral boost and additional energy to me also.

For starters who may want to know quickly difference between Bitwise OR and logical OR operators click on the highlighted link.

Here is a simple Example:


public class TernaryOperatorsExample {

public static void main(String[] args) {

TernaryOperatorsExample ternaryOperatorsExample=new TernaryOperatorsExample();
ternaryOperatorsExample.m3();
}

public void m3() {
int i=10;
boolean test=false;
int j=i > 0 ? m1() | m2() : 0; }

public int m1() {
System.out.println("Came here m1()");
return 1;
}

public int m2() {
System.out.println("Came here m2()");
return 2;
}

class InnerClass {
int innerM1() {
System.out.println("Inner M1()");
return 10;
}
}
}

As you can see here we are able to call multiple functions at a time in java too.Thanks to paul for providing a cool alternative.

Similarly as known we can call any package class functions etc like

int j=i > 0 ? new InnerClass().innerM1() | m2() : 0;
System.out.println("J: " + j);


Also nested ternary operators go like this way.
int jj= i > 5
? i > 8 ? m1() : 0
: test==false ? m2() : 1;
System.out.println("JJ: " + jj);


Any comments suggestions much appreciated.

Thanks
Prashant

5 comments:

Mike said...

Java Megastar emi cheppina kathi laga cheputhadu... vadiki thiruguledu.... kani ee blog emi rasado naku ardam kaledu....

Unknown said...

Java King vi ra nuvvu... super anna... carry on.. dusukuni vellu.. niku tirugu ledu... ninnu yevvaru apaleru... All the Best ra....

Venu said...

Hi Prasanth,
First of All Wish you Best of luck for your enthu, and keep producing some more good papers.

The point is pretty clear that we can call multiple functions and also package class functions.

However, you may not be able to execute this line in main()
int j=i > 0 ? new InnerClass().innerM1() | m2() : 0; because of static references...

if your plan is to keep that line in m3(), thats fair enough...

Suggestion: Would require more clarity in presentation side, while giving the examples.

becaues, the reader might not always in sync with your knowledge.

All the Best...

JP said...

venu,

Surely will try to follow your suggestion.

Anonymous said...

Hi Prashant,
Great going. Appreciate you sharing your learnings. Curious question, how do you manage to read so many books :-)

cheers,
-Sapien