knowledge-kitchen
/
course-notes
class: center, middle # Data Types Allocate yourself some space --- # Agenda 1. [Primitive types](#data-types) 1. [Utility/Helper/Wrapper classes](#helper-classes) 1. [Apache Commons Lang](#commons-lang) 1. [Java New Input/Output](#java-nio) 1. [Strings Are Not Primitives](#string-objects) 1. [Converting Data Types](#conversion) 1. [Conclusions](#conclusions) --- name: data-types # Primitive Types -- ## Overview Java natively supports 8 fundamental [primitive data types](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html): - `byte` = 8-bit signed integer - `short` = 16-bit signed signed integer - `int` = 32-bit signed integer (**the default** for integer literals) - `long` = 64-bit signed floating-point number - `float` = 32-bit floating point floating-point number - `double` = 64-bit floating point number (**the default** for floating point literals) - `char` = 16-bit Unicode character code - `boolean` = 1-bit true (1) or false (0) value - **arrays**, while not a data type, are a fundamental primitive data structure in Java --- template: data-types ## Observations - `float` and `double` are [fundamentally inaccurate](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). Use [`java.math.BigDecimal`](https://docs.oracle.com/javase/8/docs/api/java/math/BigDecimal.html) for accuracy. - there is no `String` primitive data type in Java. [`String`](https://docs.oracle.com/javase/8/docs/api/java/lang/String.html) is a `class` 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_. --- name: helper-classes # 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. --- template: helper-classes ## 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. --- name: commons-lang # 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](https://apache.org) sponsors a project called [Commons Lang](https://commons.apache.org/proper/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](https://commons.apache.org/proper/commons-lang/apidocs/index.html) for dealing with data of non-primitive types. -- Commons Lang is perhaps most well-known for its `String`-related helper classes: [`StringUtils`](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringUtils.html), [`WordUtils`](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/text/WordUtils.html), and [`StringEscapeUtils`](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/StringEscapeUtils.html). --- name: java-nio # 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 `/`). --- template: java-nio ## 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. ```java String path = "C:\\Users\\fernando\\Documents\\my_file.txt"; ``` -- This type of problem borders on the absurd. --- template: java-nio ## java.nio.file.Path The Java API offers a "new" solution to this problem in the form of the [`java.nio.file.Path`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Path.html) class, which allows us to deal with file paths in a platform-independent way. ```java 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: ```java String cwd = Paths.get("").toAbsolutePath().toString(); String another_path = Paths.get(cwd, "data", "my_other_file.txt").toString(); ``` --- name: string-objects # 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 ```java String x = "hello"; String y = "hello"; boolean theSameMemoryAddress = (x == y); // -> most likely true, but not guaranteed to be so ``` -- ```java 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 ``` --- template: string-objects ## 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 a `true`, when comparing two Strings, even those with the same text. - So use the `.equals()` method for Strings instead. ```java String x = "hello"; String y = "hello"; boolean theSameMemoryAddress = x.equals(x); // -> true if they contain the same text, false otherwise ``` --- template: string-objects ## 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. ```java 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); ``` --- name: conversion # Converting Data Types -- ## Double to int ```java Double dbl = new Double(5.0); int integer = dbl.intValue(); ``` --- template: conversion ## Integer to String ```java String str = Integer.toString(5); // or String str = "" + 5; ``` --- template: conversion ## Double to String ```java String str = Double.toString(5.0); ``` --- template: conversion ## Long to String ```java String str = Long.toString(50L); ``` --- template: conversion ## Float to String ```java String str = Float.toString(5.0F); ``` --- template: conversion ## String to Integer ```java int i = Integer.valueOf("5").intValue(); // or int i = Integer.parseInt("5"); ``` --- template: conversion ## String to Double ```java double d = Double.valueOf(str).doubleValue(); // or double d = Double.parseDouble(str); ``` --- template: conversion ## String to Long ```java long l = Long.valueOf("5").longValue(); // or long l = Long.parseLong("5"); ``` --- template: conversion ## String to Float ```java float f = Float.valueOf("5").floatValue(); ``` --- template: conversion ## Decimal to Binary ```java String bin = Integer.toBinaryString(50); ``` --- template: conversion ## Decimal to Hexadecimal ```java String hexstr = Integer.toHexString(50); //or String hexstr = Integer.toString(50, 16); ``` --- template: conversion ## Hexadecimal to Decimal ```java int i = Integer.valueOf("B8DA3", 16).intValue(); //or int i = Integer.parseInt("B8DA3", 16); ``` --- template: conversion ## Char to String ```java String s = String.valueOf('c'); ``` --- template: conversion ## Integer to ASCII code ```java int i = (int) "A"; ``` --- template: conversion ## Catching Exceptions Use **exception handline** to handle any problems encountered while attempting to convert one data type to another. ```java 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 } ``` --- name: conclusions # Conclusions -- Now we understand a bit about data types in Java. -- - Thank you. Bye.