## Literals

No. 18

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

No. 19

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

No. 20

### 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) '&'));
...

No. 21

### 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">
<title>A simple color example</title>

<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);

No. 22

### 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);
}

No. 23

### 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 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 code 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 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.

Finally using a cast strips off the two leading bytes from the int representation leaving us with the desired pattern for a short representing -32768:

  int                short

00000000
00000000
10000000  cast --> 10000000
00000000           00000000

No. 24

### 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 these inner braces.

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. We start by omitting the inner braces. This results in:

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

We inspect the first expression "Decimal:" + 512. Java implicitly converts the int literal 512 into a String "512". Then the two + operator concatenates both Strings 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" in order to be concatenated with the preceding "Decimal:" string.

No. 25

### 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."); }

No. 26

### 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(System.out.println("""
Some "special" words.""");

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

No. 27

### Supplementary string exercises

 Q: Solve the following external exercises: