Skip to content

Commit cccf40d

Browse files
author
Ram swaroop
committed
added content
1 parent 70c10fd commit cccf40d

1 file changed

Lines changed: 36 additions & 0 deletions

File tree

_posts/2015-05-14-variables-and-literals.md

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,11 +173,47 @@ double g = 987.897; // No 'D' suffix, but OK because the
173173

174174
#### Boolean Literals
175175

176+
Boolean literals can be either `true` or `false`. In C (and some other languages) it is common to use numbers to
177+
represent true or false, but this will not work in Java. For example,
176178

179+
{% highlight java %}
180+
boolean t = true; // Legal
181+
boolean f = 0; // Compiler error!
182+
int x = 1; if (x) { } // Compiler error!
183+
{% endhighlight %}
177184

178185
#### Character Literals
179186

187+
A char literal is represented by a single character in __single quotes__:
188+
189+
{% highlight java %}
190+
char a = 'a';
191+
char b = '@';
192+
{% endhighlight %}
193+
194+
You can also assign unicode value to a `char` variable, like:
195+
196+
{% highlight java %}
197+
char letterN = '\u004E'; // The letter 'N'
198+
{% endhighlight %}
199+
200+
Note, characters are nothing but __16-bit unsigned integers__. So, you can assign a number literal, assuming it will fit
201+
into the unsigned 16-bit range (0 to 65535) to a `char` variable. For example, the following are all __legal__:
202+
203+
{% highlight java %}
204+
char a = 0x892; // hexadecimal literal
205+
char b = 982; // int literal
206+
char c = (char)70000; // The cast is required; 70000 is
207+
// out of char range
208+
char d = (char) -98; // Ridiculous, but legal
209+
{% endhighlight %}
210+
211+
And the following are __not legal__ and produce compiler errors:
180212

213+
{% highlight java %}
214+
char e = -29; // Possible loss of precision; needs a cast
215+
char f = 70000; // Possible loss of precision; needs a cast
216+
{% endhighlight %}
181217

182218
#### String Literals
183219

0 commit comments

Comments
 (0)