Literals

Figure 93. float and double Slide presentation

Figure 94. 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 95. 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. 12

Pretty may not be pretty

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

Strange output

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 can read binary codes, those who know what binary is and those who don't have a clue about binary at all.

Figure 96. 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.MAX_VALUE)

Figure 97. 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 98. 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

Figure 99. int literals explained Slide presentation
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 100. Java primitive literals Slide presentation
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 101. Java String and null literals Slide presentation
String "Hello", "Greek Δ"
"Greek \u0394"
Arbitrary classes null

exercise No. 14

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.

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

Integer value hexadecimal representation

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 hexadecimal representations 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.

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

Binary literals

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

Testing the limits (Difficult)

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.

  • Surprise: Using a cast yields the intended result:

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

Tip

Which integer literals are being defined by the Java standard?

A:

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 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, long and char but no short or byte integer literals. The given example is thus equivalent to:

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

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

On contrary the four-byte two complement int value 0B00000000_00000000_10000000_00000000 equals 2 15 or 32768. This is one step above a short's range [ - 2 15 , 2 15 - 1 ] and thus cannot be assigned to a short variable.

Using a cast cuts off the two leading bytes of 00000000_00000000_10000000_00000000 forcing the remaining two lower bytes into a short variable 10000000_00000000. In 2-byte two complement representation this is the lowest possible value - 2 15 or -32768.

exercise No. 18

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 its two operands different + operators are being chosen by your compiler:

    4 + 3

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

    "Hello," + " World"

    The string concatenation operator resulting in the String "Hello, World".

    "Current temperature: " + 20

    The string concatenation operator again. Behind the scenes the integer value of 20 is being converted into the string "20" prior to being concatenated into a single "Current temperature: 20" string.

  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"

    The second line will be evaluated in a different manner:

    System.out.println(11 + 22 + " is our result");
                         ╲ ╱           ╱ 
                          33          ╱  
                            ╲        ╱
                         "33 is our result"
  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 this exercises first 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 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. 19

Composing strings of literals and variables

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

Escaping double quotes

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 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 more clumsy

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

System.out.println("Some " + '"' + "special" + '"' + " words.");
Using 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. 21

Supplementary string exercises

Q:

Solve the following external exercises:

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

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

Could this happen?

Olympic winter games: 2014