Skip to the content
onlineexamguide
  • Home
  • Courses
  • Engg. Interview
    • Placement Papers
    • Electrical Engineering
    • Mechanical Engineering
    • Automobile Engineering
    • Civil Engineering
    • Computer Science Engineering
    • Chemical Engineering
    • CS & IT Engg.
      • C programming Tests
      • C++ programming Tests
      • Java Programming Tests
  • Online Exam
    • NTA UGC NET Exam
    • SSC Examination quiz
    • TET Examination Quiz
    • Banking Exam
    • Aptitude Tests
    • Computer Knowledge Tests
    • Logical Reasoning Tests
    • English Language Tests
    • Staff Nurse Exams
    • General Knowledge Tests
    • Networking Tests
  • Ghatna Chakra
  • Register
    • Instructor Registration
    • Student Registration
    • About us
    • Privacy Policy
  • Cart
  • User Login
  • Home
  • Courses
  • Engg. Interview
    • Placement Papers
    • Electrical Engineering
    • Mechanical Engineering
    • Automobile Engineering
    • Civil Engineering
    • Computer Science Engineering
    • Chemical Engineering
    • CS & IT Engg.
      • C programming Tests
      • C++ programming Tests
      • Java Programming Tests
  • Online Exam
    • NTA UGC NET Exam
    • SSC Examination quiz
    • TET Examination Quiz
    • Banking Exam
    • Aptitude Tests
    • Computer Knowledge Tests
    • Logical Reasoning Tests
    • English Language Tests
    • Staff Nurse Exams
    • General Knowledge Tests
    • Networking Tests
  • Ghatna Chakra
  • Register
    • Instructor Registration
    • Student Registration
    • About us
    • Privacy Policy
  • Cart
  • User Login

Ternary Operator in Java (Conditional) Interview MCQ

Ternary Operator in Java

Study and learn Interview MCQ Questions and Answers on Ternary Operator in Java or Conditional Operator. Attend job interviews easily with these Multiple Choice Questions

Java language has a special operator called Ternary Operator that works like a Shortcut IF ELSE control statement. It is also called a Conditional Operator.

Ternary Operator in Java (?:) or Conditional Operator Explained

Ternary Operator in Java (?:) or Question Mark Colon Operator tests a condition and moves the control to two branching points, one for true and one for false.

Syntax:

(condition)? (true part expression): (false part expression)

The condition can be a direct relational operation or a boolean logical expression or a simple true/false. True Part and False Part must return a value. So you can not write a Ternary operator statement that does not return anything. You can not even put Functions returning void.

You can use Ternary Operator with any control statement that expects a boolean type value. So, you can use Ternary Operator with IF, ELSE IF, WHILE, DO WHILE, FOR and more.

Java Ternary operator has got the least priority among all other operators like Arithmetic, Relational, Bitwise and Logical. It has more priority than Assignment operators and Lambda operator.

Example Error 1: Assignments and Return Value in Ternary Operator

You can not use Java Ternary Operator alone as a standalone statement. So, do not write a Ternary operator without an assignment operation. Also return value is a must. You can not put void returning method calls inside branching expressions of a Ternary Operator. You get the following errors.

  1. Syntax error, insert “AssignmentOperator Expression” to complete Expression
  2. The left-hand side of an assignment must be a variable
  3. void is an invalid type for the variable
  4. Type mismatch: cannot convert from void to int
class TernaryOperator1
{
  public static void main(String args[])
  {
    int a =5;
    (a<6)?5:6;	//Error
    int b = (a<6)?5:6; //WORKS
    int c = (a>6)?5:6; //WORKS
    int d = true?show():show(); //ERROR. No Return Value
  }
  static void show()
  {
    System.out.println("SHOW METHOD");
  }
}
//ERROR:
//Left Hand side of an assignment must be a variable
//Solution: Use a variable and assign
//Now b holds 5 as a<6 is true
//Now c holds 6 as a>6 is false
//show method returns void. It is not valid in Java.

Example 2: Ternary Operator in Java with boolean values

You can put an expression resulting in any data type say byte, short, char, int, long, float, double, String and Object as part of TRUE PART or FALSE PART of a Ternary Operator.

class TernaryOperator2
{
  public static void main(String args[])
  {
    boolean b;
    b = false?2<4: 5>7; //false?false:false
  }
}
//Now b = 5>7 ==> holds false

Example 3: Ternary Operator in Java with null object Checking

An object occupies memory. If it is set to NULL (null), the memory occupied by it will be released by the Garbage Collector. If an object is null, you can not use or reference any of its member variables or methods.

class TernaryOperator3
{
  public static void main(String args[])
  {
    String a = "Hello Java", b=null;
    b = (b==null)?a: b; //b =a
    System.out.println(b);

    b = (b==null)?a: "2 "+ b; // b = "2 " + b
    System.out.println(b);
  }
}
//Hello Java
//2 Hello Java

Example 4: String Assignments Inside in java

You can do assignment operations inside TRUE Part or FALSE Part of a Ternary Operator. Make sure, the return type is compatible with the assigning constants. We have done String assignments in this example.

class TernaryOperator4
{
  public static void main(String args[])
  {
    String a = "Hello Java";
    String b = a!=null? a="HELLO":(a="JAVA");
    System.out.println(b);
  }
}
//OUTPUT
//HELLO

Example 5: Nesting of Ternary Operator with Multiple Conditions

You can nest one Ternary operator inside another Ternary operator. You should carefully select the output data type of one Ternary operator sitting inside another ternary operator. Here, the first condition is NULL comparison and the second condition is EQUALS comparison.

class TernaryOperator5
{
  public static void main(String args[])
  {
    String a = "Java";
    String b = a!=null? a.equals("Java")?"YES JAVA":"NO JAVA":"JAVA ISLAND";
              //a!=null? (a.equals("Java")?"YES JAVA":"NO JAVA"):"JAVA ISLAND";
    String a = null;
    String b = a!=null? a.equals("Java")?"YES JAVA":"NO JAVA":"JAVA ISLAND";            
    System.out.println(b);
  }
}
//OUTPUT
//YES JAVA
//JAVA ISLAND

Example 6: Using IF ELSE statements in java

You can use Ternary Operator inside an IF or ELSE IF statements if it is returning a boolean data type constant.

class TernaryOperator6
{
  public static void main(String args[])
  {
    if(2>0?true:5<10)
    {
        System.out.println("Using Ternary Inside IF");
    }
  }
}
//OUTPUT
//Using Ternary Inside IF

Practice these examples to get more knowledge

Ternary Operator in Javascript

[WpProQuiz 86]

Write a comment Cancel reply

You must be logged in to post a comment.

Recent Posts

  • Atal Bihari Vajpayee | श्री अटल बिहारी वाजपेयी जीवन परिचय
  • सम्राट अशोक का जीवन परिचय (Emperor Ashoka)
  • Prithviraj Chauhan
  • बाल गंगाधर तिलक
  • स्वामी दयानंद सरस्वती
  • UPPSC Mines Inspector Recruitment 2022 Notification Out
  • AIIMS Delhi JR Vacancy 2022 [194 Post] Notification and Apply Online
  • भीमराव अम्बेडकर
  • डॉक्टर राजेंद्र प्रसाद का जीवन परिचय
  • श्रीनिवास रामानुजन का जीवन परिचय
  • Amnesty International day
  • World Economic Forum
  • UPSSSC VDO Syllabus and Exam Pattern 2022
  • RBI Officer Grade B Recruitment 2022
  • UKMSSB Assistant Professor Recruitment 2022 Apply Now 339 Post

About us

Free online test to practice for Competitive exams , Online Exam, Entrance and Interview. Learn and Practice online test for Free and Prepare for your exam online with us

Select Language

Follow us

Search

Learn and Earn

Register as Instructor - Create and sell online courses and coaching services with the best online platform onlineexamguide.com . Build a course, build a brand, earn money

Copyright © 2022 onlineexamguide.com - All Rights Reserved.
error: Content is protected !!

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.