-1

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';
   }
}

4 Answers4

2

Should be

String dalmation = (dogType == 2) ? "Yes": "No";
Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
1

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.

Andrew Li
  • 55,805
  • 14
  • 125
  • 143
0

It should be like

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

Strings are enclosed using double quotes where are character is mentioned with in single quotes

Bhargav Kumar R
  • 2,190
  • 3
  • 22
  • 38
0

You have a typo.. When you do this

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

You are using the char sign (single quotes ), it must be done with double quotes. . Like:

String dalmation = (dogType == 2) ? "Yes": "No";
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97