Data Types (in Java)
Allocate yourself some space
- Primitive types
- Utility/Helper/Wrapper classes
- Apache Commons Lang
- Java New Input/Output
- Strings Are Not Primitives
- Converting Data Types
- Conclusions
Primitive Types
Overview
Java natively supports 8 fundamental primitive data types:
byte
= 8-bit signed integershort
= 16-bit signed signed integerint
= 32-bit signed integer (the default for integer literals)long
= 64-bit signed floating-point numberfloat
= 32-bit floating point floating-point numberdouble
= 64-bit floating point number (the default for floating point literals)char
= 16-bit Unicode character codeboolean
= 1-bit true (1) or false (0) value- arrays, while not a data type, are a fundamental primitive data structure in Java
Observations
float
anddouble
are fundamentally inaccurate. Usejava.math.BigDecimal
for accuracy.- there is no
String
primitive data type in Java.String
is aclass
that is written in object-oriented Java code. - because it contains “primitive” data types, rather than only
class
types, Java is not a purely object-oriented language.
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.
Byte
Short
Integer
Long
Float
Double
Character
Boolean
Arrays
These classes are especially helpful when converting a value of one data type to another.
Observations
- Utility classes contain useful methods for manipulating the types of data usually stored as fundamental primitive data types.
- They are often called “wrapper” or “helper” classes because they offer additional functionality built around primitive data types.
- These are fully-objected-oriented correlates of the fundamental primitive data types.
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:
NumberUtils
CharUtils
BooleanUtils
ArrayUtils
- … and many more for dealing with data of non-primitive types.
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.
- It does not compare the values stored at those locations of 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
.
- Only primitive data types with the same value are guaranteed to be stored in the same spot in memory
- So two Strings with the same value may be stored in different spots in memory
- So the
==
operator may not always result in atrue
, when comparing two Strings, even those with the same text. - So use the
.equals()
method for Strings instead.
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.
- Even though
String
is actually fully object-oriented, Strings are immutable. - The
StringBuilder
class is a convenient mutable equivalent of 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.
- Thank you. Bye.