Colorado State University

Recitation R22 - Miscellaneous Java
Spring 2014

CS160: Foundations in Programming


The purpose of this lab is to practice some miscellaneous Java language features, and to write numerical conversion code to manipulate binary numbers.

Miscellaneous Java


Binary Literals

Java allows programmers to specify ints, doubles and chars down to the bit level. There are four kinds of numeric literals in Java: decimal (base 10), hexadecimal (base 16), octal (base 8), and binary (base 2).

Create an R22 project in Eclipse and an associated class. Define each of the four variables exactly as shown below and print them using System.out.println(<variable>); to verify the decimal values. Now print them again in binary and see what you get, using System.out.println(Integer.toBinaryString(<variable>));.

Bitwise Operations

In addition to the operators +, -, *, /, &&, || that we you have previously learned, there are also the bitwise operators shown below. Copy the left side of each equality comparison into a System.out.println(Integer.toBinaryString(<expression>)) statement and verify the answers shown.

Writing a Number Converter

  1. The TA will show you a simple algorithm for converting a number between bases.
  2. Implement methods with the following signatures and test them in main.

    // This converts an int (decimal value) to a String representing the binary value
    public static String toBinaryString(int decimalNumber){ }

    // This converts a String representing a binary value to an int (decimal value)
    public static int parseBinaryString(String binaryString){ }


Wrapper Classes

While primitives are the fundamental units of data in Java, they lack the functionality of classes like String. Wrapper classes such as Integer, Double, Character, and Boolean are designed to give primitives extra functionality. You have already used the Character class to find out if a character is an uppercase or lowercase letter, digit, etc. One of the most useful features of these classes is parsing, for example parseInteger(String s), parseDouble(String s), and parseBoolean(String s). These methods convert Strings into their associated primitive representations, thus making it unnecessary to write number conversion.

For this part of the lab, call the Integer methods parseInt(String s, int radix), toBinaryString(int value), and toHexString(int value) to check your code from above. Your results should be the same as the results from the Integer methods, though you may have additional leading zeros.
Show your R22.java program to the TA for grading and submit to RamCT to get credit for this lab.

© 2014 CS160 Colorado State University. All Rights Reserved.