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) {     // procedure that is to be called, the "method"
        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

Build your own Jupyter Notebook meeting these College Board and CTE competencies. It is critical to understand Static versus Instance Now, this is College Board requirement!!!

  • Explain Anatomy of a Class in comments of 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).

Additional requirements (Pick something)

  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
  2. 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.

Java Hello Hacks

Person Dynamic Java Program

public class Person {
    String name;
    int age;
    String favColor;
    String car;
    String school;

    public Person(String personName, int personAge, String personFavColor, String personCar, String personSchool){
        name = personName;
        age = personAge;
        favColor = personFavColor;
        car = personCar;
        school = personSchool;

    }

    public static void main(String [] args){
        Person me = new Person("Emaad Mir", 16, "Blue", "Tesla Model X", "Del Norte High School");
        System.out.println("Name: " + me.name + "\nAge: " + me.age + "\nFavorite Color: " + me.favColor + "\nCar: " + me.car + "\nSchool: " + me.school);
        System.out.flush();

    }

}
Person.main(null);
Name: Emaad Mir
Age: 16
Favorite Color: Blue
Car: Tesla Model X
School: Del Norte High School

Location Dynamic Java Program

public class Location {
    String country;
    String state;
    String city;
    int zipCode;

    public Location(String country, String state, String city, int zipCode){
        this.country = country;
        this.state = state;
        this.city = city;
        this.zipCode = zipCode;
    }

    public void setCountry(String country) {
        this.country = country;
    }
    
    public void setState(String state) {
        this.state = state;
    }
    
    public void setCity(String city) {
        this.city = city;
    }

    public void setZipCode(int zipCode) {
        this.zipCode = zipCode;
    }
    
    public String getCountry() {
        return country;
    }
    
    public String getState() {
        return state;
    }
    
    public String getCity() {
        return city;
    }

    public int getZipCode() {
        return zipCode;
    }
    
    public static void main(String [] args){
        Location fuckthis = new Location("United States of America", "Idaho", "Meridian", 83642);
        System.out.println("LOCATION\n");
        System.out.println("Country: " + fuckthis.getCountry());
        System.out.println("\nState: " + fuckthis.getState());
        System.out.println("\nCity: " + fuckthis.getCity());
        System.out.println("\nZip Code: " + fuckthis.getZipCode());
    }
    }

Location.main(null)
LOCATION

Country: United States of America

State: Idaho

City: Meridian

Zip Code: 83642

Java Calculator Program

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;

public class DataSetCalculator {

    public static void main(String[] args) {
        ArrayList<Double> data_set = getData();
        System.out.println("Unsorted List: " + data_set);
        ArrayList<Double> sorted_data_set = sort(data_set);
        System.out.println("Sorted List: " + sorted_data_set);
        System.out.println("The mean of your data set is " + mean(data_set));
        System.out.println("The median of your data set is " + median(data_set));
        System.out.println("The mode of your data set is " + mode(data_set));
    }

    public static ArrayList<Double> getData() {
        ArrayList<Double> data_set = new ArrayList<>();
        System.out.println("Welcome to the data set calculator! Here you can input a set of data and find out all sorts of information about it!");

        boolean complete = false;
        Scanner scanner = new Scanner(System.in);

        while (!complete) {
            try {
                System.out.print("Enter a data point: ");
                double data = Double.parseDouble(scanner.nextLine());
                data_set.add(data);
            } catch (NumberFormatException e) {
                System.out.println("Invalid input. Please input a number.");
            }

            System.out.print("Would you like to keep entering points? (y/n) ");
            String answer = scanner.nextLine();
            if (answer.equalsIgnoreCase("n")) {
                complete = true;
            }
        }

        return data_set;
    }

    public static double mean(ArrayList<Double> data_set) {
        double sum = 0;
        for (double num : data_set) {
            sum += num;
        }
        return sum / data_set.size();
    }

    public static double median(ArrayList<Double> data_set) {
        int length = data_set.size();
        int middleIndex = length / 2;

        if (length % 2 == 1) {
            return data_set.get(middleIndex);
        } else {
            double middleValue1 = data_set.get(middleIndex - 1);
            double middleValue2 = data_set.get(middleIndex);
            return (middleValue1 + middleValue2) / 2;
        }
    }

    public static double mode(ArrayList<Double> data_set) {
        HashMap<Double, Integer> occurrences = new HashMap<>();
        double mode = 0;
        int most_times = 0;

        for (double num : data_set) {
            occurrences.put(num, occurrences.getOrDefault(num, 0) + 1);
            int count = occurrences.get(num);
            if (count > most_times) {
                most_times = count;
                mode = num;
            }
        }

        return mode;
    }

    public static ArrayList<Double> sort(ArrayList<Double> data_set) {
        int length = data_set.size();

        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length - i - 1; j++) {
                if (data_set.get(j) > data_set.get(j + 1)) {
                    double temp = data_set.get(j);
                    data_set.set(j, data_set.get(j + 1));
                    data_set.set(j + 1, temp);
                }
            }
        }

        return data_set;
    }
}

DataSetCalculator.main(null)
Welcome to the data set calculator! Here you can input a set of data and find out all sorts of information about it!
Enter a data point: Would you like to keep entering points? (y/n) Enter a data point: Would you like to keep entering points? (y/n) Enter a data point: Would you like to keep entering points? (y/n) Unsorted List: [28.0, 239.0, 37112.0]
Sorted List: [28.0, 239.0, 37112.0]
The mean of your data set is 12459.666666666666
The median of your data set is 239.0
The mode of your data set is 28.0

More Java Programs (For Fun!)

import java.util.Scanner;
public class Main {

    static int numLeapYears(int year1, int year2){
        int leapYears = 0;
        for(int i = year1; i<year2; i++){
            if((i % 4 == 0) && (i % 100 != 0) || (i % 4 == 0) && (i % 100 == 0) && (i % 400 == 0 )){
                    System.out.format("%d is a leap year between %d and %d\n",i,year1,year2);
                    leapYears++;

            }
        }
        return leapYears;



    }


    public static void main(String[] args) {

        System.out.println("This program will prompt you to enter two years and will provide you with the leap years between those two years as well as the actual number of leap years. ");

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter the first year: ");

        int year1 = sc.nextInt();

        Scanner sc1 = new Scanner(System.in);

        System.out.print("Enter the second year: ");

        int year2 = sc1.nextInt();

        System.out.format("Between the years %d and %d, there are %d leap years",year1,year2,numLeapYears(year1,year2));
        
    }
}

Main.main(null);
This program will prompt you to enter two years and will provide you with the leap years between those two years as well as the actual number of leap years. 
Enter the first year: Enter the second year: 1832 is a leap year between 1829 and 2012
1836 is a leap year between 1829 and 2012
1840 is a leap year between 1829 and 2012
1844 is a leap year between 1829 and 2012
1848 is a leap year between 1829 and 2012
1852 is a leap year between 1829 and 2012
1856 is a leap year between 1829 and 2012
1860 is a leap year between 1829 and 2012
1864 is a leap year between 1829 and 2012
1868 is a leap year between 1829 and 2012
1872 is a leap year between 1829 and 2012
1876 is a leap year between 1829 and 2012
1880 is a leap year between 1829 and 2012
1884 is a leap year between 1829 and 2012
1888 is a leap year between 1829 and 2012
1892 is a leap year between 1829 and 2012
1896 is a leap year between 1829 and 2012
1904 is a leap year between 1829 and 2012
1908 is a leap year between 1829 and 2012
1912 is a leap year between 1829 and 2012
1916 is a leap year between 1829 and 2012
1920 is a leap year between 1829 and 2012
1924 is a leap year between 1829 and 2012
1928 is a leap year between 1829 and 2012
1932 is a leap year between 1829 and 2012
1936 is a leap year between 1829 and 2012
1940 is a leap year between 1829 and 2012
1944 is a leap year between 1829 and 2012
1948 is a leap year between 1829 and 2012
1952 is a leap year between 1829 and 2012
1956 is a leap year between 1829 and 2012
1960 is a leap year between 1829 and 2012
1964 is a leap year between 1829 and 2012
1968 is a leap year between 1829 and 2012
1972 is a leap year between 1829 and 2012
1976 is a leap year between 1829 and 2012
1980 is a leap year between 1829 and 2012
1984 is a leap year between 1829 and 2012
1988 is a leap year between 1829 and 2012
1992 is a leap year between 1829 and 2012
1996 is a leap year between 1829 and 2012
2000 is a leap year between 1829 and 2012
2004 is a leap year between 1829 and 2012
2008 is a leap year between 1829 and 2012
Between the years 1829 and 2012, there are 44 leap years
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {

        int numMonths = 12;
        int percent = 100;

        Scanner sc = new Scanner(System.in);

        System.out.print("Enter a principal loan amount:\n ");

        int principal = sc.nextInt();



        Scanner sc1 = new Scanner(System.in);

        System.out.print("Enter your annual interest rate (as a percent):\n ");

        float annualInterestRate = sc1.nextFloat();

        float monthlyInterestRate = annualInterestRate / percent / numMonths ;

        Scanner sc2 = new Scanner(System.in);

        System.out.print("Enter a period (in years):\n ");

        int period = sc2.nextInt();

        int numPayments = period * numMonths;

        float mortgage = (float) ((principal * monthlyInterestRate * Math.pow(1+monthlyInterestRate, numPayments)) / (Math.pow(1+monthlyInterestRate,numPayments)-1));

        System.out.println("Calculated Monthly Mortgage: $"+mortgage);

        }
    }

    Main.main(null);
Enter a principal loan amount:
 Enter your annual interest rate (as a percent):
 Enter a period (in years):
 Calculated Monthly Mortgage: $5.395197