Literals

Figure 94. float and double Slide presentation

Figure 95. Four ways representing 35 Slide presentation
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 96. Choose your output representation Slide presentation
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. 16

Pretty may not be pretty

Q:

Consider the following program:

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 by padding leading positions with zeros:

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 even compile.

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 octal digit.

exercise No. 17

Strange output

Q:

Consider the following code:

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

On execution we receive Value = 33. Explain this result

A:

This problem is related to the previous exercise: The integer literal 041 defines octal representation of an int value.

Converting octal to decimal representation yields 4 * 8 + 1 = 33.

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

Figure 97. Know your limits! Slide presentation
System.out.println(1000000000);    // o.K.
System.out.println(2147483647);    // o.K.: Largest int value 2^31 - 1

System.out.println(10000000000L);  // o.K.: Using type long
System.out.println(10000000000 );  // Compile time error: Integer number
                                   // larger than 2147483647 or 
                                   // 2^31 - 1, Integer.System.out.println("i carrying double: " + i))

Figure 98. Literal examples Slide presentation
System.out.println("Hello");     // A String literal

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

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

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

Figure 99. int literals Slide presentation
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

exercise No. 18

Poor mans ASCII table

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!

Produce the above output by solely using the character representations ' ' to '&'. How do you get the corresponding int values 32 to 38?

Tip

A char can be assigned to an int variable.

A:

We assign our char values to int variables:

{
  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 (cast) from char to int 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. 19

Integer value hexadecimal representation

Q:

You may be familiar with the color model using triplets of numbers defining colors. These triplets represent the tree color component intensities of this model's 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): The red component having maximum intensity while blue and green are zero.

In RGB it's common using hexadecimal in favour of decimal values. Thus the aforementioned color red in the subsequent HTML example's heading font may also be represented by (FF, 0, 0) or "#FF0000":

<!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 hexadecimal representations of a single intensity like 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.

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. 20

Binary literals

Q:

  1. Using the decimal system to represent integer values we tend to ignore other important numbering systems. Code 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 manual calculation.

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

    Tip

A:

  1. The decimal's indentation is aligned with corresponding positions within the binary literal:

    Code
    System.out.println(" Binary:" +  0B11_10100100);
    
    System.out.println("Decimal:" +   (512
                                      + 256
                                        + 128
                                         + 32
                                             + 4));
    Result
     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 without a trailing l or L 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:

    Code
    System.out.println(0B10000000_00111001_01101001_01110100);
    Result
    -2143721100

exercise No. 21

Testing the limits (Difficult)

Q:

  1. 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.

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

    final short MINIMUM = 0B10000000_00000000, // short: two-byte
                MAXIMUM = 0B01111111_11111111; // two-complement.
    
    System.out.println("Minimum short value:" + MINIMUM);
    System.out.println("Maximum short value:" + MAXIMUM);

    Our programmer is baffled:

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

      Type mismatch: cannot convert from int to short

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

    3. Surprise: Using a cast yields the intended result:

      final short MINIMUM = (short) 0B10000000_00000000,...

    Explain all three observations.

    Tip

    Which integer literals are being defined by the Java standard?

A:

  1. Variables of type short use signed two-byte two-complement representation ranging from - 2 15 to 2 15 - 1 . Thus intensity values ranging from 0 to 255 will thus be easily accommodated in a variable of type short.

    As an aside: Using just byte would suffice as well: Our programmer might map the intended intensity values from [ 0 , 2 8 - 1 ] to a byte's range of [ - 2 7 , 2 7 - 1 ] by subtracting -128.

  2. The next questions are more difficult to answer:

    1. The Java standard defines int, long and char but no short or byte integer literals.

      The 0B10000000_00000000 literal of type int actually relates to the four byte pattern 00000000_00000000_10000000_00000000 or 32768 equalling 2 15 . This is beyond Short.MAX_VALUE 2 15 - 1 by one thus causing a compiler error message. In particular it is not even close to the intended Short.MIN_VALUE of -32768 or - 2 15 .

    2. 0B01111111_11111111 or decimal 32767 equals Short.MAX_VALUE or 2 15 - 1 and can thus be assigned to our variable MAXIMUM: In absence of data loss the compiler will accept the implicit narrowing conversion from int to short.

    3. The int to short cast removes the two upper bytes in 00000000_00000000_10000000_00000000 containing just zeros. The result of type short thus becomes 10000000_00000000 being the intended -32768 or - 2 15 minimum of a short in 2 byte 2 complement representation.

    Conclusion: Our programmer thought he was using two byte 2 complement representation. But in fact he was using four byte 2 complement instead.

exercise No. 22

Why using braces in System.out.println(...) ?

Q:

  1. Consider the following code snippet:

    Code Output
    System.out.println("Result: " + 11 + 22);
    System.out.println(11 + 22 + " is our result");
    Result: 1122
    33 is our result

    Explain the different outcomes.

    Tip

    Depending on the types of its two operands left and right different + operations are being carried out by a compiler:

    4 + 3

    The usual arithmetic sum operator resulting in the integer value 7.

    "Hello," + " World"

    The operator acts on two literals of type String. In this case the + operator denotes string concatenation of its two operands resulting in "Hello, World" of type String again.

    "Days: " + 20 or "20 + days"

    The string concatenation operator again: Behind the scenes the int literal 20 is being converted into the string "20" prior to being concatenated into a single "Days: 20" or "20 days" String respectively.

  2. The solution of Binary literals is related to a similar problem:

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

    Why are the inner braces grouping (512 + 256 + 128 + 4) being required?

Tip

Execute the above code omitting the inner braces pair.

A:

  1. We start by considering System.out.println("Result: " + 11 + 22). Expressions involving the + operator are being evaluated from left to right. The result is thus:

    System.out.println("Result: " + 11 + 22);
                             ↘     ↙     ↙
                         "Result: 11"  ↙  
                              ↘      ↙
                          "Result: 1122"

    Explanation: In the "Result: " + 11 expression the + operator has got an operand of type String to its left and an int of value 11 to its right. In this case the compiler:

    • Implicitly converts the int 11 into a String of value "11".

    • Concatenates both strings "Result: " and "11" into "Result: 11".

    This step repeats when evaluating "Result: 11" + 22.

    The second line of code will be evaluated differently:

    System.out.println(11 + 22 + " is our result");
                         ↘ ↙           ↙
                          33         ↙  
                             ↘     ↙
                       "33 is our result"

    This time the expression 11 + 22 is just the ordinary addition of two int values. The subsequent 33 + " is our result" expression is then again being evaluated as string concatenation.

  2. Omitting the inner braces results in:

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

    For the leftmost expression part "Decimal:" + 512 the int literal 512 is being implicitly converted into a String "512" prior to being concatenated into "Decimal:512". Evaluating the whole expression from left to right this pattern keeps repeating. Like in the aforementioned example the above code is thus equivalent to:

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

    Each + operator again defines the concatenation of its left and right string operands rather than the usual integer arithmetics. Thus all six components get joined together into a single result string.

    Conversely supplying additional inner braces results in an expression (512 + 256 + 128 + 32 + 4) solely involving integer value arithmetics:

    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" and then again being concatenated into Decimal:932.

exercise No. 23

Composing strings of literals and variables

Q:

Consider the following code:

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:

final int games = 3, playersPerGame = 22;

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

exercise No. 24

Escaping double quotes

Q:

Consider the following code:

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 three 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 clumsier

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

System.out.println("Some " + '"' + "special" + '"' + " words.");
Better: Multi line strings

Java 15 introduces strings possibly spanning multiple lines being delimited by pairs of """. This construct allows for " and "" (but obviously not for """) within a given multi line string:

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

Note

Notice the necessity of a newline after the starting """ sequence.

exercise No. 25

Supplementary string exercises

Q:

Solve the following external exercises:

Figure 100. Just kidding ... Slide presentation
int year = MMXIV; // Roman numerals representation

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

Could this happen?

Olympic winter games: 2014