knowledge-kitchen

Data Types (in Java)

Allocate yourself some space

  1. Primitive types
  2. Utility/Helper/Wrapper classes
  3. Apache Commons Lang
  4. Java New Input/Output
  5. Strings Are Not Primitives
  6. Converting Data Types
  7. Conclusions

Primitive Types

Overview

Java natively supports 8 fundamental primitive data types:

Observations

Utility/Helper/Wrapper classes

Overview

The Java API (a set of classes written in Java that are distributed with Java) offers a set of object-oriented utility classes to help manipulate data of the fundamental primitive data types and structures.

These classes are especially helpful when converting a value of one data type to another.

Observations

Apache Commons Lang

Overview

Due to the limitations of working with primitive data types and the conservative nature of the Java API’s included Utility/HelperWrapper/ classes, the Apache Software Foundation sponsors a project called Commons Lang that aims to provide functionality that many programmers regret is not present in the Java API. This library includes additional helper classes, such as:

Commons Lang is perhaps most well-known for its String-related helper classes: StringUtils, WordUtils, and StringEscapeUtils.

Java New Input/Output

Incompatible file paths

Despite Java’s proclamed “Write once, run anywhere” paradigm, writing programs that deal consistently with file paths across Windows, Mac, Linux, and Unix computers is annoying problematic.

Example Windows file path:

C:\Users\fernando\Documents\my_file.txt

Equivalent Mac/Unix/Linux file path:

/Users/fernando/Documents/my_file.txt

As you can see, the root of the file path is different (C:\ versus an initial /), and the separator between directories is different (e.g. \ versus /).

Escaping escape characters

Furthermore, the standard string escape character, \ happens to be used in Windows as a file paths. So to avoid that back slash being interpreted as an escape character, it must itself be escaped.

String path = "C:\\Users\\fernando\\Documents\\my_file.txt";

This type of problem borders on the absurd.

java.nio.file.Path

The Java API offers a “new” solution to this problem in the form of the java.nio.file.Path class, which allows us to deal with file paths in a platform-independent way.

String path = Paths.get("C:", "Users", "fernando", "Documents", "my_file.txt").toString();

It also contains useful methods to find out the current working directory, which can be useful for determing the file paths of files in subdirectories of the current working directory:

String cwd = Paths.get("").toAbsolutePath().toString();
String another_path = Paths.get(cwd, "data", "my_other_file.txt").toString();

Strings Are Not Primitives

Overview

The == operator performs a comparison of the position in memory where two values are stored in memory.

String x = "hello";
String y = "hello";
boolean theSameMemoryAddress = (x == y); // -> most likely true, but not guaranteed to be so
Scanner scn = new Scanner(System.in);
String x = "hello";
String y = scn.nextLine(); // let's imagine the user enters the same text, "hello"...
boolean theSameMemoryAddress = (x == y); // -> most likely false!, but not guaranteed to be so

String is a class

String is not a primitive data type, it’s an object-oriented class.

String x = "hello";
String y = "hello";
boolean theSameMemoryAddress = x.equals(x); // -> true if they contain the same text, false otherwise

StringBuilder

There is also a StringBuilder class, which is a utility class for the String class.

StringBuilder str = new StringBuilder();
str.append("goodbye");
str.append("foo");
str.append("world!");
str.delete(7,10); // remove the characters at index positions 7-9, i.e. "foo"
str.insert(" ", 7); // insert a space at index position 7
str.replace(0, 7, "hello"); // replaces the characters at index positions 0-6 (i.e. "goodbye) with "hello"
String result = str.toString(); // -> "hello world!";
System.out.println(result);

Converting Data Types

Double to int

Double dbl = new Double(5.0);
int integer = dbl.intValue();

Integer to String

String str = Integer.toString(5);
// or
String str = ""  +  5;

Double to String

String str = Double.toString(5.0);

Long to String

String str = Long.toString(50L);

Float to String

String str = Float.toString(5.0F);

String to Integer

int i = Integer.valueOf("5").intValue();
// or
int i = Integer.parseInt("5");

String to Double

double d = Double.valueOf(str).doubleValue();
// or
double d = Double.parseDouble(str);

String to Long

long l = Long.valueOf("5").longValue();
// or
long l = Long.parseLong("5");

String to Float

float f = Float.valueOf("5").floatValue();

Decimal to Binary

String bin = Integer.toBinaryString(50);

Decimal to Hexadecimal

String hexstr = Integer.toHexString(50);
//or
String hexstr = Integer.toString(50, 16);

Hexadecimal to Decimal

int i = Integer.valueOf("B8DA3", 16).intValue();
//or
int i = Integer.parseInt("B8DA3", 16);

Char to String

String s = String.valueOf('c');

Integer to ASCII code

int i  = (int) "A";

Catching Exceptions

Use exception handline to handle any problems encountered while attempting to convert one data type to another.

String aString = "foo bar baz bum"; //  a string that has no obvious int equivalent

try{
	// try to do the conversion...
	i = Integer.parseInt(aString); // will fail and produce an Exception
}
catch(NumberFormatException e) {
	// this block of code will run if there was a failure
	System.out.println(e); // will output the Exception but not crash the program
}

Conclusions

Now we understand a bit about data types in Java.