Search code examples
javastringcharconditional-statementsternary

Can strings be used in a ternary conditional statement?


I'm (very) new to Java and have been using Codecademy, and after learning about ternary conditionals I was wondering if a string could be used in place of char? I know that strings aren't a real primitive data type in Java whereas char is, but it seems like you should be able to print out a string rather than a single character without having to use if/else statements or something similar.

//my ternary with char
public class dogBreeds
{
   public static void main(String[] args)
   {
       int dogType = 2;
       char dalmation = (dogType == 2) ? 'Y':'N';
   }
}

//my ternary with string (or something like it) in place of char
public class dogBreeds
{
   public static void main(String[] args)
   {
      int dogType = 2;
      String dalmation = (dogType == 2) ? 'Yes':'No';
   }
}

Solution

  • When representing Strings, use double quotes as they signify a string literal. Single quotes signify a char literal:

    String dalmation = (dogType == 2) ? "Yes" : "No";
    

    There are differences with String and char types. Strings are immutable and cannot be changed after they are created. When a String object is created and the constructor is called, it can't be changed. If you want to use Strings, consider StringBuilder if you want it to be mutable.