Hello, World!

This article shows the basic language structures and constructs of Java (aka anatomy). In async order, it is critical to understand these examples and learn vocab for OOP and Creating Objects:

Static example

The class HelloStatic contains the classic “Hello, World!” message that is often used as an introduction to a programming language. The “public static void main(String[] args)”, or main method, is the default runtime method in Java and has a very specific and ordered definition (signature).

The key terms in HelloStatic introduction:

  • “class” is a blueprint for code, it is the code definition and must be called to run
  • “method” or “static method” in this case, is the code to be run/executed, similar to a procedure
  • “method definition” or “signature” are the keywords “public static void” in front of the name “main” and the parameters “String[] args” after the name.
  • “method call” is the means in which we run the defined code
// Define Static Method within a Class
public class HelloStatic {
    // Java standard runtime entry point
    public static void main(String[] args) {    
        System.out.println("Hello World!");
    }
}
// A method call allows us to execute code that is wrapped in Class
HelloStatic.main(null);   // Class prefix allows reference of Static Method
Hello World!

Dynamic Example

This example starts to use Java in its natural manner, using an object within the main method. This example is a very basic illustration of Object Oriente Programming (OOP). The main method is now used as a driver/tester, by making an instance of the class. Thus, it creates an Object using the HelloObject() constructor. Also, this Class contains a getter method called getHello() which returns the value with the “String hello”.

The key terms in HelloStatic introduction:

  • “Object Oriented Programming” focuses software design around data, or objects.
  • “object” contains both methods and data
  • “instance of a class” is the process of making an object, unique or instances of variables are created within the object
  • “constructor” special method in class, code that is used to initialize the data within the object
  • “getter” is a method that is used to extract or reference data from within the object.
// Define Class with Constructor returning Object
public class HelloObject {
    private String hello;   // instance attribute or variable
    public HelloObject() {  // constructor
        hello = "Hello, World!";
    }
    public String getHello() {  // getter, returns value from inside the object
        return this.hello;  // return String from object
    }
    public static void main(String[] args) {    
        HelloObject ho = new HelloObject(); // Instance of Class (ho) is an Object via "new HelloObject()"
        System.out.println(ho.getHello()); // Object allows reference to public methods and data
    }
}
// IJava activation
HelloObject.main(null);
Hello, World!

Dynamic Example with two constructors

This last example adds to the basics of the Java anatomy. The Class now contains two constructors and a setter to go with the getter. Also, observe the driver/tester now contains two objects that are initialized differently, 0 and 1 argument constructor. Look at the usage of the “this” prefix. The “this” keyword helps in clarification between instance and local variable.

The key terms in HelloDynamic introduction:

  • “0 argument constructor” constructor method with no parameter ()
  • “1 argument constructor” construct method with a parameter (String hello)
  • “this keyword” allows you to clear reference something that is part of the object, data or method
  • “local variable” is a variable that is passed to the method in this example, see the 1 argument constructor as it has a local variable “String hello”
  • “dynamic” versus “static” is something that has option to change, static never changes. A class (blueprint) and objects (instance of blueprint) are generally intended to be dynamic. Constructors and Setters are used to dynamically change the content of an object.
  • “Java OOP, Java Classes/Objects, Java Class Attributes, Java Class Methods, Java Constructors” are explained if more complete detail in W3 Schools: https://www.w3schools.com/java/java_oop.asp
// Define Class
public class HelloDynamic { // name the first letter of class as capitalized, note camel case
    // instance variable have access modifier (private is most common), data type, and name
    private String hello;
    // constructor signature 1, public and zero arguments, constructors do not have return type
    public HelloDynamic() {  // 0 argument constructor
        this.setHello("Hello, World!");  // using setter with static string
    }
    // constructor signature, public and one argument
    public HelloDynamic(String hello) { // 1 argument constructor
        this.setHello(hello);   // using setter with local variable passed into constructor
    }
    // setter/mutator, setter have void return type and a parameter
    public void setHello(String hello) { // setter
        this.hello = hello;     // instance variable on the left, local variable on the right
    }
    // getter/accessor, getter used to return private instance variable (encapsulated), return type is String
    public String getHello() {  // getter
        return this.hello;
    }
    // public static void main(String[] args) is signature for main/drivers/tester method
    // a driver/tester method is singular or called a class method, it is never part of an object
    public static void main(String[] args) {  
        HelloDynamic hd1 = new HelloDynamic(); // no argument constructor
        HelloDynamic hd2 = new HelloDynamic("Hello, Nighthawk Coding Society!"); // one argument constructor
        System.out.println(hd1.getHello()); // accessing getter
        System.out.println(hd2.getHello()); 
    }
}
// IJava activation
HelloDynamic.main(null);
Hello, World!
Hello, Nighthawk Coding Society!

Hacks

  • Explain Anatomy of a Class in comments of a program (Diagram key parts of the class).
  • Comment in code where there is a definition of a Class and an instance of a Class (ie object)
  • Comment in code where there are constructors and highlight the signature difference in the signature
  • Call an object method with parameter (ie setters).

These can all be seen in the provided Person object.

Additional requirements

  1. Go through code progression of understanding Class usage and generating an Instance of a Class (Object). a. Build a purposeful dynamic Class, using an Object, generate multiple instances: - Person: Name and Age - Dessert: Type and Cost - Location: City, State, Zip b. Create a static void main tester method to generate objects of the class. c. In tester method, show how setters/mutators can be used to make the data in the Object dynamically change

I did this by having users initially created in a Person database that can be modified.

  1. Go through progression of understanding a Static Class. Build a purposeful static Class, no Objects.
    • Calculate common operations on a Date field, age since date, older of two dates, number of seconds since date
    • Calculate stats functions on an array of values: mean, median, mode.

I did this a ton with my updated console games hacks, but I decided to also make an object that

Dynamic Person Class

I created a dynamic class for Person. A database of three of them can be edited using the main method provided.

// person Class
public class Person {
    // creating private object variables
    private String name;
    private int age;
    private String koubutsu;
    // private Object location;
    // THIS IS THE CONSTRUCTOR
    public Person(String name, int age, String koubutsu) {
        this.name = name;
        this.age = age;
        this.koubutsu = koubutsu;
    }
    // SETTERS AND GETTERS
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getKoubutsu() {
        return koubutsu;
    }
    public void setKoubutsu(String koubutsu) {
        this.koubutsu = koubutsu;
    }
    public static Person[] makePeople() {
        // create a new people in an array
        Person[] people = new Person[3];
        people[0] = new Person("John", 30, "Ice Cream");
        people[1] = new Person("Timothee", 25, "Chocolate");
        people[2] = new Person("Lebron", 38, "Crème brûlée");
        // return the people array
        return people;
    }
    // main method
    public static void main(String[] args) {
        // creating the people database
        Person[] database = makePeople();
        // making the system active baby woooooooo
        boolean active = true;
        // introduction text
        System.out.println("Welcome to the Rich People Luxury Paradise database!\nThere are already three people signed up for attendance this year.\nThis list is now set in stone. (Unless...)");
        Scanner input = new Scanner(System.in);  // create a Scanner object
        // to be repeated while active
        while (active) {
            System.out.println("\t1. See the list\n\t2. HACK THE DATABASE (CHOOSE THIS ONE)\n\t3. Hear a short description of Rich People Luxury Paradise\n\t4. Exit");
            String selection = input.nextLine();  // read user input
            if ("1".equals(selection)) {
                System.out.println("");
                for (int i = 0; i < database.length; i++) {
                    System.out.println("Attendee " + Integer.toString(i + 1) + ":");
                    System.out.println("\tName: " + database[i].getName());
                    System.out.println("\tAge: " + database[i].getAge());
                    System.out.println("\tFavorite Dessert: " + database[i].getKoubutsu());
                }
                System.out.println("");
            } else if ("2".equals(selection)) {
                System.out.println("\nWhich user would you like to hack? (Enter their attendee number as an integer.)");
                for (int i = 0; i < database.length; i++) {
                    System.out.println("\tAttendee " + Integer.toString(i + 1) + ": " + database[i].getName());
                }
                String hackee = input.nextLine(); // read user input again
                int dataIndex = Integer.parseInt(hackee) - 1; // turn the string into an integer
                Person selectedPerson = database[dataIndex];
                // options setup
                System.out.println("What would you like to do with this user?\n\t1. Change Name\n\t2. Change Age\n\t3. Change Favorite Desert\n\t4. Replace User");
                String hackSelection = input.nextLine(); // hack selection from input line
                if ("1".equals(hackSelection)) {
                    System.out.println("What would you like the new name to be?");
                    String nameSelection = input.nextLine();
                    selectedPerson.setName(nameSelection); // USING SETNAME
                    System.out.println("Excellent choice, hacker. This person's name is now " + nameSelection + ".");
                } else if ("2".equals(hackSelection)) {
                    System.out.println("What would you like the new age to be? (Input an integer, please.)");
                    String ageSelection = input.nextLine();
                    int newAge = Integer.parseInt(ageSelection);
                    selectedPerson.setAge(newAge); // USING SETAGE
                    System.out.println("Excellent choice, hacker. This person's age is now " + ageSelection + ".");
                } else if ("3".equals(hackSelection)) {
                    System.out.println("What would you like the new favorite dessert to be?");
                    String koubutsuSelection = input.nextLine();
                    selectedPerson.setKoubutsu(koubutsuSelection); // USING SETKOUBUTSU
                    System.out.println("Excellent choice, hacker. This person's favorite dessert is now " + koubutsuSelection + ".");
                } else if ("4".equals(hackSelection)) {
                    // combination of all other selections
                    System.out.println("What would you like the new name to be?");
                    String nameSelection = input.nextLine();
                    selectedPerson.setName(nameSelection); // USING SETNAME
                    System.out.println("What would you like the new age to be? (Input an integer, please.)");
                    String ageSelection = input.nextLine();
                    int newAge = Integer.parseInt(ageSelection);
                    selectedPerson.setAge(newAge); // USING SETAGE
                    System.out.println("What would you like the new favorite dessert to be?");
                    String koubutsuSelection = input.nextLine();
                    selectedPerson.setKoubutsu(koubutsuSelection); // USING SETKOUBUTSU
                    System.out.println("Excellent work, hacker. A new person can now attend the Rich People Luxury Paradise.");
                } else {
                    System.out.println("Invalid input. The system has crashed. Great, NOW look what you've done...\nERROR CODE 80085: IDIOT USING DATABASE");
                    input.close();
                    return;
                }
            } else if ("3".equals(selection)) {
                //describe the paradise yo
                System.out.println("\nThe Rich People Luxury Paradise is a luxury resort that can only be attended by three (incredibly) rich people per year.");
                System.out.println("Once the payment has been processed, the rich person is added to the database. This includes first name, age and favorite dessert.");
                System.out.println("The only way for this to change would be for someone to input someone else's information into the database by hacking...but that'll never happen!\n");
            } else if ("4".equals(selection)) {
                System.out.println("\nThank you for using the Rich People Luxury Paradise database!");
                input.close();
                return;
            } else {
                System.out.println("Invalid input. The system has crashed. Great, NOW look what you've done...\n\u001B[31mERROR CODE 80085: IDIOT USING DATABASE");
                input.close();
                return;
            }
        }
    }
}

Person.main(null)

Stat Function Calculator

This is a Static Object that can be used to find the mean, median, and mode of an array of data.

import java.util.*;

public class StatCalculator {
    // mean calculator
    public static double calculateMean(double[] numbers) {
        // calculate number sum
        double sum = 0.0;
        for (double num : numbers) { //this is a for each loop that i learned about
            sum += num;
        }

        // Calculate the mean
        if (numbers.length > 0) {
            return sum / numbers.length;
        } else {
            // if the list is empty
            return 0.0;
        }
    }
    // median calculator
    public static double calculateMedian(double[] numbers) {
        // uses the Arrays util
        Arrays.sort(numbers);
        // finding length and using it to find the middle value(s)
        int n = numbers.length;
        if (n % 2 == 0) {
            // even number of elements means middle two values need to be averaged
            int middle1 = n / 2;
            int middle2 = middle1 - 1;
            return (numbers[middle1] + numbers[middle2]) / 2.0;
        } else {
            // odd number of elements means the midpoint of the dataset
            int middle = n / 2;
            return numbers[middle];
        }
    }
    // mode calculator
    public static List<Double> calculateMode(double[] numbers) {
        Map<Double, Integer> frequencyMap = new HashMap<>(); //using hashmaps babyyyyyyy
        // iterating through numbers and adding to the HM value of each double key
        for (double num : numbers) { // another for each loop
            frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
        }
        // find the number(s) with the most frequency
        int maxFrequency = Collections.max(frequencyMap.values());
        List<Double> modes = new ArrayList<>();
        // iterating through the frequency map entries and comparing to the maxiumum frequency
        // this determines which of the potentially multiple keys is a/the mode
        for (Map.Entry<Double, Integer> entry : frequencyMap.entrySet()) {
            if (entry.getValue() == maxFrequency) {
                modes.add(entry.getKey());
            }
        }
        return modes; //all done
    }

    public static void main(String[] args) {
        // create user input scanner
        Scanner statInput = new Scanner(System.in);
        // create new ArrayList object for user to fill
        ArrayList<Double> statList = new ArrayList<>();
        boolean dataAdding = true;
        System.out.println("Please enter some numbers to use for data proofs.");
        while (dataAdding) {
            System.out.println("What number should be added? It can be any real number, including decimals.");
            String newNumber = statInput.nextLine();
            statList.add(Double.parseDouble(newNumber));
            System.out.println("Continue adding data? (Enter y or n.)");
            String continueResponse = statInput.nextLine();
            if ("n".equals(continueResponse)) {dataAdding = false;}
        }
        // close scanner
        statInput.close();
        // converting to double[]
        double[] doubleArray = new double[statList.size()];
        for (int i = 0; i < statList.size(); i++) {
            doubleArray[i] = statList.get(i);
        }
        System.out.println("Running stats methods now...");
        System.out.println("\tMean: " + Double.toString(calculateMean(doubleArray)));
        System.out.println("\tMedian: " + Double.toString(calculateMedian(doubleArray)));
        String modesText = "";
        for (double num : calculateMode(doubleArray)) {
            modesText = modesText + Double.toString(num) + " ";
        }
        System.out.println("\tMode(s): " + modesText);
    }
}

StatCalculator.main(null);
Please enter some numbers to use for data proofs.
What number should be added? It can be any real number, including decimals.
Continue adding data? (Enter y or n.)
What number should be added? It can be any real number, including decimals.
Continue adding data? (Enter y or n.)
What number should be added? It can be any real number, including decimals.
Continue adding data? (Enter y or n.)
What number should be added? It can be any real number, including decimals.
Continue adding data? (Enter y or n.)
What number should be added? It can be any real number, including decimals.
Continue adding data? (Enter y or n.)
Running stats methods now...
	Mean: 4.4
	Median: 3.4
	Mode(s): 2.6