Literals

Figure 129. float and double Slide presentation Create comment in forum

Figure 130. Four ways representing 35 Slide presentation Create comment in forum
Code Result
System.out.println("Decimal "+ 35);
System.out.println("Binary " + 0b10_0011);
System.out.println("Hex "    + 0x23);
System.out.println("Octal "  + 043);
Decimal 35
Binary  35
Hex 35
Octal 35

Figure 131. Choose your output representation Slide presentation Create comment in forum
System.out.println("35 as Binary (Base 2):       " + Integer.toString(35, 2));
System.out.println("35 as Ternary (Base 3):      " + Integer.toString(35, 3));
System.out.println("35 as Octal (Base 8):        " + Integer.toString(35, 8));
System.out.println("35 as Hexadecimal (Base 16): " + Integer.toString(35, 16));

results in:

35 as Binary (Base 2):       100011
35 as Ternary (Base 3):      1022
35 as Octal (Base 8):        43
35 as Hexadecimal (Base 16): 23

exercise No. 18

Pretty may not be pretty Create comment in forum

Q:

Consider the following program:

public static void main(String[] args) {

int a = 20,
    b = 3,
    c = 9;

    System.out.println(a + " + " + b + " + " + c + " = " + (a + b + c));

}

This will run smoothly producing the expected output:

20 + 3 + 9 = 32

We now prettify our variable definitions by introducing right aligning numbers thereby padding leading positions with zeros:

public static void main(String[] args) {

  int a = 20,
      b = 03,
      c = 09; // Compiler error: The literal 09 of type int is out of  range

  System.out.println(a + " + " + b + " + " + c + " = " + (a + b + c));
}

The above code does not compile due to a compiler error when defining variable c.

Explain the underlying cause. In particular: Why is b = 03 just fine in contrast to c = 09 ?

Tip

Re-read the section on integer literal representations.

A:

Integer literals starting with 0 denote octal representation. The octal system's set of digits is {0,1,2,3,4,5,6,7}. Therefore 9 is no valid digit.

exercise No. 19

Strange output Create comment in forum

Q:

Consider the following code:

int a = 041;
System.out.println("Value = " + a);

On execution we receive the output Value = 33. Explain this result

A:

This problem is related to the previous exercise: The integer literal 041 defines octal representation. Changing from octal to decimal representation yields 4 * 8 + 1 = 33.

There are 11 types of people: Those, who know can read binary codes, those who know what binary is and those who don't have a clue about binary at all.

exercise No. 20

Representing emoticons. Create comment in forum

Q:

We may use the HEAVY WEDGE-TAILED RIGHTWARDS ARROW character in Java:

System.out.println("Arrow: " + "➽");

This results in:

Arrow: ➽

Strangely the SMILING FACE WITH SUNGLASSES' (U+1F60E) emoticon appears to be different. Answer the following questions:

  1. Why can't the emoticon be used accordingly?

    Tip

    Try to assign the corresponding int values like e.g. 0x27BD rather than using the symbol itself.

  2. How do we represent it in Java?

A:

  1. Our emoticon's decimal Unicode value is 128,526 or hexadecimal 1f60E . So its value is larger than 65535 and thus requires more than two bytes. Java however represents characters using just two bytes. Thus the emoticon does not fit into a single Java char value:

    char c = 0x1f60e; // Error: Incompatible types
                      // Required: char Found: int

    On contrary the arrow's decimal value of 10173 or hexadecimal 0x27BD fits perfectly well into a Java char variable:

    char c = 0x27BD;
    System.out.println("Arrow: " + c);
    System.out.println("Arrow value: " + (int)c);

    Result:

    Arrow: ➽
    Arrow value: 10173
  2. We may represent two two-byte codes in sequence:

    System.out.println("Cool smiley: " + "\uD83D\uDE0E");

    Resulting in:

    We may also convert the Unicode value directly:

    System.out.println(Character.toChars(0x1f60e));
Figure 132. Know your limits! Slide presentation Create comment in forum
System.out.println(10000000000L);  // o.K.
System.out.println(10000000000 );  // Compile time error: Integer number larger
                                   // than 2147483647 (2^31 - 1, Integer.MAX_VALUE)

Figure 133. Literal examples Slide presentation Create comment in forum
System.out.println("Hello");     // A String literal

System.out.println(33452);       // An int literal

System.out.println(34.0223);     // An double (floating point) literal

System.out.println(2147483648L); // An long literal

Figure 134. int literals Slide presentation Create comment in forum
System.out.println("Value 1: " + 29);
System.out.println("Value 2: " + 0b11101);
System.out.println("Value 3: " + 0x1D);
System.out.println("Value 4: " + 035);
Value 1: 29
Value 2: 29
Value 3: 29
Value 4: 29

Figure 135. int literals explained Slide presentation Create comment in forum
Literal Discriminator Type Value
29

base 10

Decimal 2 × 10 1 + 9 × 10 0
0b11101 0b, base 2 Binary

1 × 2 4 + 1 × 2 3 + 1 × 2 2

+ 0 × 2 1 + 1 × 2 0

0x1D 0x, base 16 Hexadecimal 1 × 16 1 + 13 × 16 0
035 0, base 8 Octal 3 × 8 1 + 5 × 8 0

Figure 136. Java primitive literals Slide presentation Create comment in forum
byte, short -
char 'A', '\u0041'
int 29, 0b1_1101, 0x1D, 035, -29,
long 35L, 0b10_0011L, 0x23L, 043L, -35L,...
float 55.43F, 1.7E-23F, -17.F, 100_342.334_113F
double 55.43, 1.7 E -23, -17.
boolean true, false

Figure 137. Java String and null literals Slide presentation Create comment in forum
String "Hello", "Greek Δ", "Greek \u0394"
null

exercise No. 21

Poor mans ASCII table Create comment in forum

Q:

We want to construct a list of printable ASCII characters. Write a Java application printing the character literals ' ', '!', '"', '#', '$', '%', '&' among with their respective decimal ASCII values. The intended output is:

 : 32
!: 33
": 34
#: 35
$: 36
%: 37
&: 38

Notice the empty space being represented by decimal 32.

Tip

A char value being represented by two bytes may be assigned to an int variable.

A:

Since char values may be assigned to int variables we code:

{
  char c = ' '; // space
  int value = c;
  System.out.println(c + ": " + value);
}
{
  char c = '!';
  int value = c;
  System.out.println(c + ": " + value);
}
{
  char c = '"';
  int value = c;
  System.out.println(c + ": " + value);
}
...

Using an explicit type conversion from char to int (a so called cast) yields an identical result:

System.out.println(' ' + ": " + ((int) ' '));
System.out.println('!' + ": " + ((int) '!'));
System.out.println('"' + ": " + ((int) '"'));
System.out.println('#' + ": " + ((int) '#'));
System.out.println('$' + ": " + ((int) '$'));
System.out.println('%' + ": " + ((int) '%'));
System.out.println('&' + ": " + ((int) '&'));
...

exercise No. 22

Integer value hexadecimal representation Create comment in forum

Q:

As you may know the RGB color model uses triplets of numbers to define color value components representing intensities of its three base colors Red, Green and Blue. The component values range from 0 to 255, the latter defining maximum intensity.

The color red for example is being represented by (255, 0, 0). So the red component has maximum intensity while blue and green are zero.

It is however common to use hexadecimal in favour of decimal values. Thus the same color red in the subsequent HTML example's heading font is now being represented by (FF,0,0):

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>A simple color example</title>
  </head>

  <body><h1 style="color: #FF0000;">My heading</h1></body>
</html>

Write a program printing the hexadecimal representation C0 16 as a decimal value.

Complete the following code by assigning the hexadecimal value C0 16 (The silver color's all three component's intensity in http://www.december.com/html/spec/color16codes.html) to get the output in decimal representation.

public static void main(String[] args) {
   short intensity = ...;

   System.out.println(intensity);
}

Tip

You may want to consider the Primitive Data Types section learning about hexadecimal integer value representation.

A:

Using hexadecimal literals we have:

short intensity = 0xC0;

System.out.println(intensity);

exercise No. 23

Literal problem Create comment in forum

Q:

Consider:

System.out.println(048);

This yields a compile time error Integer number too large. On contrary the following code will compile and run perfectly well:

System.out.println(047);

Explain the underlying problem.

A:

The literal 048 denotes octal representation. Digits in octal representation range from 0 to 7. So 047 is fine but 048 is again invalid.

exercise No. 24

Binary literals Create comment in forum

Q:

  1. Using the decimal system to represent integer values we tend to ignore other important numbering systems. Write an application which prints the decimal value of 1110100100 2 by writing the former as a binary int literal. Verify the printed value by an independent calculation.

  2. Construct a second binary literal representing a negative value of your choice.

    Tip

    An int is being represented by four bytes in Java.

A:

  1. public static void main(String[] args) {
    
       System.out.println(" Binary:" +  0B11_10100100);
       System.out.println("Decimal:" + (512
                                       + 256
                                         + 128
                                            + 32
                                                + 4));
    }

    This yields:

     Binary:932
    Decimal:932
  2. A negative value in Two's complement representation starts with a 1 at its highest bit. Binary literals in Java represent int values. An int in Java uses 4 bytes and thus occupies 4 x 8=32 bits. Therefore choosing a negative value is a simple task: Start with 1 and let it follow by 32 - 1 = 31 random bit values:

    public static void main(String[] args) {
       System.out.println(0B10000000_00111001_01101001_01110100);
    }

exercise No. 25

Testing the limits (Difficult) Create comment in forum

Q:

A careful programmer is worried whether a short variable is large enough to hold color intensity values ranging from 0 to 255. Give an answer being based on the specification and not just by try-and-error.

The programmer also looks for the smallest and largest short values using two-byte two-complement representation closely resembling the related int example:

final short MINIMUM = 0B10000000_00000000, // short: two-byte two-complement
            MAXIMUM = 0B01111111_11111111;

System.out.println("Minimum short value:" + MINIMUM);
System.out.println("Maximum short value:" + MAXIMUM);

Our programmer is baffled:

  • The first assignment MINIMUM = 0B10000000_00000000 gets flagged as a compile time error:

    Type mismatch: cannot convert from int to short

  • On contrary the second assignment MAXIMUM = 0B01111111_11111111 gets smoothly accepted.

Tip

Which integer literal types do exist according to the Java standard?

A:

Since variables of type short are signed having a two-byte two-complement representation their corresponding range is [ - 2 15 , 2 15 - 1 ] . Thus intensity values ranging from 0 to 255 will be easily accommodated.

In fact using just a byte might be sufficient as well: Our programmer simply needs to map the intended intensity values [ 0 , 2 8 - 1 ] to a byte's range of [ - 2 7 , 2 7 - 1 ] .

The second question is more difficult to answer: The Java standard only defines int but no short or byte literals. The given example thus actually reads:

final short MINIMUM = 0B00000000_00000000_10000000_00000000,
            MAXIMUM = 0B00000000_00000000_01111111_11111111;
...

The second int literal 0B01111111_11111111 representing 32767 is perfectly assignable to a short variable representing its maximum possible value as being intended.

On the contrary the four-byte two complement int value 00000000_00000000_10000000_00000000 evaluates to 2 15 (equal to 32768). But omitting the two leftmost bytes consisting of zero values the remaining two-byte two complement short value 10000000_00000000 represents -32768 (or - 2 15 ).

Avoiding this error requires representing - 2 15 as an int. Since 2 15 is being represented by 00000000_00000000_10000000_00000000 we get its four-byte two-complement negative counterpart by first inverting all positions and subsequently adding the value 1:

final short MINIMUM = 0B11111111_11111111_10000000_00000000;

Alternatively we may as well use 2 15 adding a unary minus sign:

final short MINIMUM = -0B10000000_00000000;

Despite the unary minus the latter resembles our initial faulty value.

The error in the first place is probably assigning a value of + 2 15 to a short variable mixing two-byte and four-byte two-complement representation.

exercise No. 26

Why using braces in System.out.println(...) ? Create comment in forum

Q:

Solution Binary literals contains:

...
System.out.println("Decimal:" +  (512 +
                                   256 +
                                     128 +
                                       32 +
                                          4)); ...

Why are the inner braces immediately preceding 512 and following 4 are being required?

Tip

  • Execute the above code omitting the inner braces.

  • Read about the + operator's role e.g. in System.out.println("Some" + " string").

A:

We start omitting the inner braces:

...
System.out.println("Decimal:" +  512 +
                                   256 +
                                     128 +
                                       32 +
                                          4); ...

This results in the following output:

...
Decimal:512256128324

The numbers are being treated as strings rather than integer values The above code is equivalent to:

...
System.out.println("Decimal:" +  "512" +
                                      "256" +
                                        "128" +
                                          "32" +
                                             "4"); ...

The + operator between two strings defines their concatenation. So all six components get joined into a single result string.

Supplying additional inner braces defines an expression (512 + 256 + 128 + 32 + 4) solely involving integer values. In this context each + operator effects the usual integer arithmetic:

...
System.out.println("Decimal:" + (512 +
                                      256 +
                                         128 +
                                            32 +
                                               4)); ...

+ operator concatenating the two strings "Decimal:" and "932".

+ operators computing the integer sum of 512, 256, 128, 32 and 4 yielding a value of 932. This value subsequently gets transformed into the String "932" in order to be compatible with the preceding "Decimal:" string.

exercise No. 27

Composing strings of literals and variables Create comment in forum

Q:

Consider the following code:

public static void main(String[] args) {
   final int games = 3, playersPerGame = 22;

   // ToDo ...
}

Complete the above snippet by adding code to produce the following output:

3 Games having 22 players each results in 66 players altogether.

Write your code in a way that changing i.e. final int games = 4 will result in a corresponding change of output.

A:

public static void main(String[] args) {
   final int games = 3, playersPerGame = 22;

   System.out.println(games + " Games having " + playersPerGame
         + " players each results in " + games * playersPerGame
         + " players altogether.");
}

exercise No. 28

Escaping double quotes Create comment in forum

Q:

Consider the following code:

public static void main(String[] args) {
   System.out.println("Some 'special' words.");
}

The corresponding output will be Some 'special' words.. Change the above code to replace the single quotes by double quotes producing the output Some "special" words. instead.

Tip

Hunt for java escape double quote and read about character literals in the Language Fundamentals / Literals section of [Kurniawan].

A:

There are at least two solutions on offer:

Perfectly obvious

Inside a string literal the string terminating character (") may be escaped using backslashes:

System.out.println("Some \"special\" words.");
Even more clumsy

Double quotes may be also represented by their char (not string!) literal:

System.out.println("Some " + '"' + "special" + '"' + " words.");

exercise No. 29

Supplementary string exercises Create comment in forum

Q:

Solve the following external exercises:

exercise No. 30

Unicode and emoticons Create comment in forum

Q:

Referring to Figure 102, “Some Unicode UTF-8 samples ” we may use a corresponding character literal representing Arabic:

final char arabicChar = 'ڜ'; // A character literal
System.out.println("Character: " + arabicChar);

Execution yields the expected output. On contrary the following code snippet using the smiley instead does not even compile:

Explain the underlying problem.

Tip

Consider the number of bytes being allocated for representing char values in Java.

A:

According to the Arabic block table the code point of 'ڜ' is U+069C or its decimal equivalent of 1692.

Java uses two bytes equivalent to 16 bits for representing positive char values. The highest representable code point value is thus 2 16 - 1 = 65535 . So 'ڜ' fits well into this range.

According to the Emoticons table the smiley's code point value is U+1F60E being equivalent to 128526 decimal. This exceeds the two byte unsigned limit of 65535 and thus prohibits the character literal in question.

Figure 138. Just kidding ... Slide presentation Create comment in forum
int year = MMXIV; // Roman numerals representation

System.out.println("Olympic winter games: " + year);

Could this happen?

Olympic winter games: 2014