Data Types

Primitives

  • int: aka integer, holds non-fractional number values
  • byte: similar to int, but only takes 8 bits of memory (only numbers rom -128 to 127)
  • short: in between an int and a byte
  • long: larger than an int
  • float: basic fractional numbers, which loses precision after 6 decimal places
  • double: it is a double-precision decimal number, with 64 bits of memory. It can go to further decimal places with higher precision.
  • boolean: only two values of true or false.
  • char: an integer that represents a unicode encoded character.
int x = 12425;
byte b = 40;
short s = 10452;
long l = 81849583;
float f = 6.4224f;
double d = 5.42624574367345;
boolean b = false;
char c = 'a';

Wrapper class

Primitive data types also have a class in Java that "wrap" the class.

  • Integer wraps int
  • Byte wraps byte
  • Short wraps short
  • Long wraps long
  • Float wraps float
  • Double wraps double
  • Boolean wraps boolean
  • Character wraps char

Wrapper classes are used when working with collections, or putting the data into an ArrayList or other data structures. Methods can also be called on wrapper classes, with an example being toString().

  • one use case is in parsing other types of primitives into something else, for example using the parseInt method of the wrapper class
Integer exampleInt = 10; // defining variable with wrapper class 
System.out.println(exampleInt); // printing the variable value
System.out.println(exampleInt.intValue()); // using the method to get the value in the object
10
10

Strings are a special wrapper class, being a sequence of characters or a character array.

String exampleString = "hello world";
System.out.println(exampleString + "!");
hello world!

Hacks

SI unit converter

import java.util.Scanner;
import java.util.Arrays;
public class UnitConvertor {
    double[] conversionFactors = new double[]{0.001, 0.01, 0.1, 1, 10, 100, 1000}; // the conversion factors with meters as a reference, has decimals so double
    String[] unitList = {"millimeter", "centimeter", "decimeter", "meter", "decameter", "hectometer", "kilometer"}; // the units themselves, so a string to match
    public static double inputMeasurement; // below are the global variables that get called later, double here as the measurement is going to be a number with possible decimals
    public static String inputUnits; // the unit name, so string
    public static int unitIndex; // this is used to store the index of the unit that is typed, which is an integer

    
    public static String unitMessage = "Enter the units for that measurement (millimeter, centimeter, decimeter, meter, decameter, hectometer, kilometer), type exit to exit: "; // message that can change
    int firstUnitIndex; // index is integer
    int secondUnitIndex; // index is integer
    private String firstUnit; // the name of unit so String
    private String secondUnit; // name of unit so string

    // constructor, calls the functions to enter the fields of data and saves them as attributes
    public UnitConvertor() {
        this.enterMeasurement();
        this.enterUnits();
        this.firstUnitIndex = unitIndex;
        this.firstUnit = inputUnits;
        unitMessage = "Enter the units to convert to (millimeter, centimeter, decimeter, meter, decameter, hectometer, kilometer), type exit to exit: ";
        this.enterUnits();
        this.secondUnitIndex = unitIndex;
        this.secondUnit = inputUnits;
    }

    // method to check if string matches exit, booleon because yes or no (takes string as input as it has to compare to the string)
    private boolean isExit(String inputMeasurement) {
        return inputMeasurement.matches("exit"); 
    }

    // enterMeasurement input method, with scanner
    private void enterMeasurement() {
        Scanner measurement;
        while (true) {
            System.out.print("Enter the first measurement (only numbers), type any letter to exit: ");
            measurement = new Scanner(System.in);
            try {
                inputMeasurement = measurement.nextDouble();
                System.out.println(inputMeasurement);
                measurement.close();
                break; // breaks the loop, continues on with program
            }   catch (Exception e) {
                System.out.println("See you later!");
                System.exit(0); // end program if not a number
            }
        }
    }

    // enterUnits method with scanner, checks the input and matches the string
    public void enterUnits() {
        Scanner units;
        while (true) {
            System.out.print(unitMessage); // prints the message (which changes because it has to be called twice for different purposes)
            units = new Scanner(System.in);
            try {
                inputUnits = units.nextLine();
                System.out.println(inputUnits);
                if (isExit(inputUnits)) { // check if user wants to stop program, then exits
                    System.out.println("See you next time!");
                    System.exit(0);
                }
                unitIndex = Arrays.asList(unitList).indexOf(inputUnits); // find index of the unit that the user inputted in the array, write to variable unitIndex to be stored later
                if (unitIndex == -1) { // if not found in the array, then ask user to retype
                    System.out.println("not a valid unit choice "); 
                } else {
                    break; // if is found in array, stop the loop and continue
                }
            } catch (Exception e) {
                System.out.println("Not a valid string, " + e);
            }
            units.close();
        }
    }

    // calculation of the unit change, divides the conversion factors like in dimensional analysis; returns double because the initial inputMeasurement is a double
    public double changeCalculation() {
        return (inputMeasurement * conversionFactors[this.firstUnitIndex]/conversionFactors[this.secondUnitIndex]);
    } 

    // asks user if they want to add a number onto their converted measurement
    public void add() {
        Scanner yesOrNo;
        while (true) {
            System.out.print("Would you like to add by another number of the same unit? (y/n) ");
            yesOrNo = new Scanner(System.in);
            try {
                String roundYN = yesOrNo.nextLine(); // asks user input for y/n
                System.out.println(roundYN);
                if (roundYN.matches("n")) { // if no, skip over adding
                    yesOrNo.close();
                    break;
                } else if (roundYN.matches("y")) { // if yes, create another scanner to ask for the number
                    Scanner adding;
                    while (true) {
                        System.out.print("enter the number to add: ");
                        adding = new Scanner(System.in);
                        try { 
                            double addInput = adding.nextDouble(); // gets user input, as a double because the number inputted can have decimals as a measurement
                            System.out.println(addInput);
                            adding.close();
                            double finalCalculation = this.changeCalculation(); // gets the value of the original converted measurement, which is a double and writes to variable
                            finalCalculation += addInput; // compound assignment operator, adds the user input to the converted measurement quickly
                            System.out.println(finalCalculation + " " + this.secondUnit + "s."); // print the added number
                            break;
                        }   catch (Exception e) {
                            System.out.println("Not a double, " + e);
                        }
                    }
                } else { // if not yes or no, tells user to redo
                    System.out.println("not a valid input");
                }
            } catch (Exception e) {
                System.out.println("Not a valid string, " + e);
            }
            yesOrNo.close();
        }
    }

    // truncate the number if user wants to (whole number)
    private void truncating() {
        Scanner yesOrNo;
        while (true) { // asks user if wants to truncate or exit
            System.out.print("Would you like to truncate to the nearest whole number? (y/exit) ");
            yesOrNo = new Scanner(System.in);
            try {
                String roundYN = yesOrNo.nextLine();
                System.out.println(roundYN);
                if (isExit(roundYN)) { // if user types exit, the program completes
                    System.out.println("See you next time!");
                    yesOrNo.close();
                    System.exit(0);
                } else if (roundYN.matches("y")) { // if user says y, truncates
                    int truncatedConversion = (int)this.changeCalculation(); // casts the calculation into an int, truncating it to whole number
                    System.out.println(truncatedConversion + " " + this.secondUnit + "s.");
                    yesOrNo.close();
                    break;
                } else {
                    System.out.println("not a valid input"); // tells user to type valid input
                }
            } catch (Exception e) {
                System.out.println("Not a valid string, " + e);
            }
            yesOrNo.close();
        }
    }

    // static main method, creates object converting and outputs the conversion + calls the add or truncate methods in addition
    public static void main(String[] args) {
        UnitConvertor converting = new UnitConvertor();
        System.out.println("Your measurement of " + inputMeasurement + " " + converting.firstUnit + "s" + " is " + converting.changeCalculation() + " " + converting.secondUnit + "s.");
        converting.add();
        converting.truncating();
    } 
}

UnitConvertor.main(null);
Enter the first measurement (only numbers), type exit to exit: 56.32
Enter the units for that measurement (millimeter, centimeter, decimeter, meter, decameter, hectometer, kilometer), type exit to exit: meter
Enter the units to convert to (millimeter, centimeter, decimeter, meter, decameter, hectometer, kilometer), type exit to exit: decimeter
Your measurement of 56.32 meters is 563.1999999999999 decimeters.
Would you like to add by another number of the same unit? (y/n) y
enter the number to add: 67.53
630.7299999999999 decimeters.
Would you like to add by another number of the same unit? (y/n) n
Would you like to truncate to the nearest whole number? (y/exit) 7
not a valid input
Would you like to truncate to the nearest whole number? (y/exit) y
563 decimeters.

Casting, specifically for truncating or rounding

int truncatedConversion = (int)this.changeCalculation(); // casts the calculation into an int, truncating it to whole number

By casting the calculation (a double) into an int, it truncates to a whole number. This is one useful application of casting.

Casting, specifically for division

Another use of casting is for division. Usually for accurate division, the numbers need to be casted into doubles. If they were integers or longs, then the output would be a truncated whole number still, whic might not be too useful.

int a = 3;
int b = 2;

System.out.println(a/b); // will be truncated to 1

System.out.println((double) a/(double) b); // is cased to double so will be 1.5
1
1.5

Additional Information

Operators

Usually primitive manipulation can be done through math operators like +, -, *, or /.

int i = 3;
System.out.println(i/3); // 3/3 = 1
System.out.println(i*3); // 3*3 = 9
System.out.println(i + 3); // 3+3 = 6
System.out.println(i-3); // 3-3=0
1
9
6
0

Incrementing primitive data can also be achieved by adding itself to the number to increment.

int i = 4;
System.out.println(i);
i = i + 4; // add 4 to i and set i to that value
System.out.println(i);
4
8

However, this code is a little repetitive, having to type out the variable twice. So, there is built in syntax for doing this incrementation or decrementation.

The operator is in the form of: var (operator)= (amount to change)

  • in this, the operator can be *, /, +, -
  • the amount to change is the amount to add, subtract, divide, multiply, etc.

This is especially helpful in loops like for loops, where a variable has to be incremented every run. Shorthand makes code more readable and faster to type.

i = 5;
System.out.println(i);
i += 2;
System.out.println(i); // should be 7
5
7

Even this can sometimes be too much to write. Incrementations of one or decrementations of one are by far very common, especially when iterating. So, i++ or i-- do this exact thing.

i = 193;
i++;
System.out.println(i);
194

HACKS Grade Calculator

import java.util.Scanner;

/**
 * GradeCalculator
 */
public class GradeCalculator {

    public static void main(String[] args) {
        // scanner
        Scanner input = new Scanner(System.in);

        // check if in final
        System.out.print("Is the final in the tests category? ");
        Boolean testOrNot = input.nextBoolean();
        System.out.println(testOrNot);

        // taking inputs
        System.out.print("What is your current grade? ");
        double currentGrade = input.nextDouble();
        System.out.println(currentGrade);

        // if not a test (in separate)
        if (!testOrNot) {
            System.out.print("How much percent of your grade is the final? ");
            double finalPercent = input.nextDouble();
            System.out.println(finalPercent);

            System.out.print("What is your desired grade? ");
            double desiredGrade = input.nextDouble();
            System.out.println(desiredGrade);

            input.close();

            // found this formula off rapidtables
            double finalGrade = (desiredGrade/100 - (currentGrade/100)*(1-finalPercent/100))/(finalPercent/10000);

            System.out.print("You need a " + finalGrade + " on the test.");
        } else { // if is in tests category
            // collect inputs
            System.out.print("How much of your grade is the tests category? ");
            double testPercent = input.nextDouble();

            System.out.print("What is your current grade (in tests category)? ");
            double currentTestGrade = input.nextDouble();

            System.out.print("How many points is in the tests category currently? ");
            double currentTestPoints = input.nextDouble();

            System.out.print("How many points is the final? ");
            double finalPoints = input.nextDouble();

            System.out.print("What is your desired grade? ");
            double desiredGrade = input.nextDouble();
            System.out.println(desiredGrade);

            // WIP
            double currentPoints = currentTestGrade - testPercent * currentTestPoints;
            double finalNeedPoints = (desiredGrade/100)-((1-testPercent/100)*1);
        }
    }
}

GradeCalculator.main(null);
Is the final in the tests category? false
What is your current grade? 70.0
How much percent of your grade is the final? 20.0
What is your desired grade? 90.0
You need a 170.00000000000003 on the test.