Results 1 to 3 of 3
  1. #1
    subith86 is offline Senior Member
    Join Date
    Jan 2011
    Location
    Bangalore, India
    Posts
    102
    Rep Power
    0

    Default doubt regarding ternary operator (?)

    In C++
    I'm able to do something like this

    Java Code:
    (some_condition)? function1():function2();
    When i tried the same thing in Java it's not possible. It wants some variable to hold the result even though the return type of function1 and function2 are void.

    Is there any other way to do it?

  2. #2
    pbrockway2 is online now Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,574
    Rep Power
    12

    Default

    It wants some variable to hold the result even though the return type of function1 and function2 are void.

    It's not so much that you must assign the result to some variable, rather, "There are two kinds of types in the Java programming language: primitive types (4.2) and reference types (4.3). There are, correspondingly, two kinds of data values that can be stored in variables, passed as arguments, returned by methods, and operated on: primitive values (4.2) and reference values (4.3)." (JLS 4.1 The Kinds of Types and Values).

    Is there any other way to do it?

    Yes:

    Java Code:
    if(someCondition) {
        method1();
    } else {
        method2();
    }

  3. #3
    subith86 is offline Senior Member
    Join Date
    Jan 2011
    Location
    Bangalore, India
    Posts
    102
    Rep Power
    0

    Default

    thanks,

    this is the normal if... else...
    Anyway fine. Just wanted to know if there was any other alternative for single line condition.

Similar Threads

  1. Use of ternary
    By wulfgarpro in forum New To Java
    Replies: 1
    Last Post: 09-21-2010, 07:31 AM
  2. question about the operator ++
    By dardar in forum New To Java
    Replies: 10
    Last Post: 08-16-2010, 03:39 PM
  3. help with not equal to operator !=
    By manowar689 in forum New To Java
    Replies: 9
    Last Post: 06-15-2010, 01:10 AM
  4. Replies: 2
    Last Post: 02-27-2010, 08:10 AM
  5. bitwise not ~ operator
    By kezkez in forum New To Java
    Replies: 2
    Last Post: 02-10-2010, 07:49 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •