Primitives Notes

Data Types

  • primitive data types: lowercase

    • boolean
    • integers
    • doubles
    • float
    • character
  • non primitive data types: uppercase

    • wrapper class - string
    • arrays
  • wrapper classes used to convert any data type into an object

public class DefinePrimitives {
    public static void main(String[] args) {
      int anInt = 100;
      double aDouble = 89.9;
      boolean aBoolean = true;

      // not primitives but essential
      String aString = "Hello, World!";   // wrapper class shortcut assignment
      String aStringFormal = new String("Greetings, World!");
  
      System.out.println("anInt: " + anInt);
      System.out.println("aDouble: " + aDouble);
      System.out.println("aBoolean: " + aBoolean);
      System.out.println("aString: " + aString);
      System.out.println("aStringFormal: " + aStringFormal);
    }
  }
  DefinePrimitives.main(null)
anInt: 100
aDouble: 89.9
aBoolean: true
aString: Hello, World!
aStringFormal: Greetings, World!

Input Primitives

  • hard coded: variables are assigned values beforehand
  • dynamic: variable values are determined by user input
  • scanner: java utility class for console input
// java style to import library
import java.util.Scanner;

// class must alway have 1st letter as uppercase, CamelCase is Java Class convention
public class ScanPrimitives {
    public static void main(String[] args) {    
        Scanner input;

        // primitive int
        input = new Scanner(System.in);
        System.out.print("Enter an integer: ");
        try {
            int sampleInputInt = input.nextInt();
            System.out.println(sampleInputInt);
        } catch (Exception e) {  // if not an integer
            System.out.println("Not an integer (form like 159), " + e);
        }
        input.close();

        // primitive double
        input = new Scanner(System.in);
        System.out.print("Enter a double: ");
        try {
            double sampleInputDouble = input.nextDouble();
            System.out.println(sampleInputDouble);
        } catch (Exception e) {  // if not a number
            System.out.println("Not an double (form like 9.99), " + e);
        }
        input.close();

        // primitive boolean
        input =  new Scanner(System.in);
        System.out.print("Enter a boolean: ");
        try {
            boolean sampleInputBoolean = input.nextBoolean();
            System.out.println(sampleInputBoolean);
        } catch (Exception e) {  // if not true or false
            System.out.println("Not an boolean (true or false), " + e);
        }
        input.close();

        // wrapper class String
        input =  new Scanner(System.in);
        System.out.print("Enter a String: ");
        try {
            String sampleInputString = input.nextLine();
            System.out.println(sampleInputString);
        } catch (Exception e) { // this may never happen
            System.out.println("Not an String, " + e);
        }
        input.close();
    }
}
ScanPrimitives.main(null);
Enter an integer: 89
Enter a double: 89.0
Enter a boolean: true
Enter a String: hello

Output Primitive Data

  • Examples show descriptions of the mathematical operation combine with the result of the operation:
public class PrimitiveDivision {
    public static void main(String[] args) {
        int i1 = 7, i2 = 2;
        System.out.println("Integer Division");
        System.out.println("\tint output with concatenation: " + i1 + "/" + i2 + " = " + i1/i2);
        System.out.println(String.format("\tint output with format: %d/%d = %d",i1, i2, i1/i2));
        System.out.printf("\tint output with printf: %d/%d = %d\n",i1, i2, i1/i2);

        double d1 = 7, d2 = 2;
        System.out.println("Double Division");
        System.out.println("\tdouble output with concatenation: " + d1 + "/" + d2 + " = " + d1/d2);
        System.out.println(String.format("\tdouble output with format: %.2f/%.2f = %.2f",d1, d2, d1/d2));
        System.out.printf("\tdouble output with printf: %.2f/%.2f = %.2f\n",d1, d2, d1/d2);

        System.out.println("Casting and Remainders");
        System.out.printf("\tint cast to double on division: %d/%d = %.2f\n",i1, i2, i1/(double)i2);
        System.out.println("\tint using modulo for remainder: " + i1 + "/" + i2 + " = " + i1/i2 + " remainder " + i1%i2);
    }
}
PrimitiveDivision.main(null);
Integer Division
	int output with concatenation: 7/2 = 3
	int output with format: 7/2 = 3
	int output with printf: 7/2 = 3
Double Division
	double output with concatenation: 7.0/2.0 = 3.5
	double output with format: 7.00/2.00 = 3.50
	double output with printf: 7.00/2.00 = 3.50
Casting and Remainders
	int cast to double on division: 7/2 = 3.50
	int using modulo for remainder: 7/2 = 3 remainder 1

Grade Calculator

  • Lab uses primitive double and Wrapper Class double
  • Uses ArrayList
public class GradeCalculator {
    // introduction to Double wrapper class (object)
    ArrayList<Double> grades;   // similar to Python list

    // constructor, initializes ArrayList and call enterGrades method
    public GradeCalculator() {
        this.grades = new ArrayList<>();
        this.enterGrades();
    }

    // double requires test for zero versus threshold, DO NOT compare to Zero
    private boolean isZero(double value){
        double threshold = 0.001;
        return value >= -threshold && value <= threshold;
    }


    // enterGrades input method using scanner
    private void enterGrades() {
        Scanner input;

        while (true) {
            input = new Scanner(System.in);
            System.out.print("Enter a double, 0 to exit: ");
            try {
                double sampleInputDouble = input.nextDouble();
                System.out.println(sampleInputDouble);
                if (isZero(sampleInputDouble)) break;       // exit loop on isZero
                else this.grades.add(sampleInputDouble);    // adding to object, ArrayList grades
            } catch (Exception e) {  // if not a number
                System.out.println("Not an double (form like 9.99), " + e);
            }
            input.close();
        }
    }

    // average calculation 
    public double average() {
        double total = 0;   // running total
        for (double num : this.grades) {    // enhanced for loop
            total += num;   // shortcut add and assign operator
        }
        return (total / this.grades.size());  // double math, ArrayList grades object maintains its size
    }

    // static main method, used as driver and tester
    public static void main(String[] args) {
        GradeCalculator grades = new GradeCalculator(); // calls constructor, creates object, which calls enterGrades
        System.out.println("Average: " + String.format("%.2f", grades.average()));  // format used to standardize to two decimal points
    }
}
// IJava activation
GradeCalculator.main(null);
Enter a double, 0 to exit: 100.0
Enter a double, 0 to exit: 90.0
Enter a double, 0 to exit: 80.0
Enter a double, 0 to exit: 70.0
Enter a double, 0 to exit: 80.0
Enter a double, 0 to exit: 60.0
Enter a double, 0 to exit: 50.0
Enter a double, 0 to exit: 0.0
Average: 75.71

Primitives Hacks

Temperature Converter (Celcius to Kelvin)

import java.util.Scanner;
public class CelciustoKelvin {
    public static void main (String[] args) {
        Scanner input;

        //we used a wrapper class to introduce our program to the user.
        String aString = "This is our program to convert Celcius to Kelvin. We are using it for our AP Chemistry class.";
        System.out.println(aString);

        //we used the string to greet the user
        input = new Scanner(System.in);
        System.out.println("Enter your name as a string: ");
        String name = input.nextLine();
        System.out.println("Hello " + name );
        input.close();

        //the integer is used to get the age of the user
        input = new Scanner(System.in);
        System.out.println("Enter your age as an integer: ");
        String age = input.nextLine();
        System.out.println("You are " + age + " years old." );
        input.close();

        //boolean is used to get a true or false answer about whether the user is in AP Chemistry
        input = new Scanner(System.in);
        System.out.println("Are you in AP Chemistry? Enter your answer as a Boolean: ");
        String chem = input.nextLine();
        System.out.println("Your answer: " + chem);
        input.close();

        //double is used to get a number from the user and convert it using arithmetic expression
        input = new Scanner(System.in);
        System.out.println("Enter a degree in Celsius as a double: ");
        double celsius = input.nextDouble();
        double kelvin = (celsius + 273.0);
        System.out.println( celsius + " degree Celsius is equal to " + kelvin + " in Kelvin");
        input.close();
    }
}
CelciustoKelvin.main(null);
This is our program to convert Celcius to Kelvin. We are using it for our AP Chemistry class.
Enter your name as a string: 
Hello Vidhi
Enter your age as an integer: 
You are 16 years old.
Are you in AP Chemistry? Enter your answer as a Boolean: 
Your answer: True
Enter a degree in Celsius as a double: 
54.3 degree Celsius is equal to 327.3 in Kelvin