ECE366 - Lesson 2

More Java

Instructor: Professor Hong

Review & Questions

## Java Basics

Types

## Wrapper Classes - byte <=> Byte - short <=> Short - int <=> Integer - long <=> Long - float <=> Float - double <=> Double - boolean <=> Boolean - char <=> Character - Some objects require these wrapper classes as they have other properties (e.g. .toString())
## Variable Names - Case-sensitive - No white space in the namem - Can begin with a letter, $, or _ (cannot start with a number; $ and _ are discouraged) - Can contain some special characters (+ and $ are ok; - is not) - Cannot be keywords or reserved words (static, void, etc.) - Should be in camel case for multiple words - Should be in all caps for constants
## Fill in the Blanks (w/ User Input) Ask the user to provide: - Season of the year - Whole number (integer) - Adjective Store and Print: - Store the input in variables - Print a story by filling in the blanks with variables
## Create a new project - Create a new package called games - This will be used for different classes Slowness in WSL: - There is an open issue: [here](https://youtrack.jetbrains.com/issue/IDEA-293604/IntelliJ-is-slow-hanging-when-working-with-WSL-filesystem) - You can create projects in your windows folders as a workaround - You can cd into your C drive with ```cd /mnt/c```
## Sample Solution ``` package games; import java.util.Scanner; public class FillInTheBlanks { public static void main(String[] args){ Scanner scanner = new Scanner(System.in); System.out.println("Let's create a story!"); System.out.println("Enter an adjective"); String adjective = scanner.next(); System.out.println("Enter a season of the year"); String season = scanner.next(); System.out.println("Enter a whole number"); int number = scanner.nextInt(); scanner.close(); System.out.println("On a(n) " + adjective + " " + season + " day, I drink a minimum of " + number + " cups of Thai Iced Tea."); } } ```
## Docker Review Dockerfile ``` FROM eclipse-temurin:latest ADD . /app WORKDIR /app CMD java games/FillInTheBlanks.java ``` Building, Running, and Cleaning Up the Container ``` $ docker help $ docker build -t fillintheblank . $ docker run -i --name fillintheblank-app fillintheblank $ docker rm fillintheblank-app $ docker rmi fillintheblank ``` ```-i``` means interactive mode ```--rm``` removes the container after running
## Conditionals if-else if-else pattern Grades ``` package test_results; import java.util.Scanner; public class TestResults { public static void main(String[] args){ System.out.println("Enter your test score:"); Scanner scanner = new Scanner(System.in); double score = scanner.nextDouble(); scanner.close(); char grade; if(score < 60) { grade = 'F'; } else if(score < 70) { grade = 'D'; } else if(score < 80) { grade = 'C'; } else if(score < 90) { grade = 'B'; } else { grade = 'A'; } System.out.println("You received a(n) " + grade); } } ```
## Switch Statements Grades ``` package grade_message; import java.util.Scanner; public class GradeMessage { public static void main(String[] args){ System.out.println("Enter your letter grade: "); Scanner scanner = new Scanner(System.in); String grade = scanner.next(); scanner.close(); String message; switch(grade) { case "A": message = "Excellent job"; break; case "B": message = "Great job"; break; case "C": message = "Good job"; break; case "D": message = "You need to work a bit harder"; break; case "F": message = "Uh oh!"; break; default: message = "Invalid grade"; } System.out.println(message); } } ```
## Switch Expressions Grades ``` package grade_message; import java.util.Scanner; public class GradeMessage2 { public static void main(String[] args){ System.out.println("Enter your letter grade: "); Scanner scanner = new Scanner(System.in); String grade = scanner.next(); scanner.close(); String message = switch(grade) { case "A" -> "Excellent job"; case "B" -> "Great job"; case "C" -> "Good job"; case "D" -> "You need to work a bit harder"; case "F" -> "Uh oh!"; default -> "Invalid grade"; }; System.out.println(message); } } ```
## While Loops Gross Pay Validator ``` package gross_pay_input_validator; import java.util.Scanner; public class GrossPayInputValidator { public static void main(String[] args){ int payRate = 15; int maxHours = 40; System.out.println("How many hours did the employee work this week?"); Scanner scanner = new Scanner(System.in); double hoursWorked = scanner.nextDouble(); while(hoursWorked > maxHours) { System.out.println("Invalid entry. Your hours must be between 1 and 40. Try again."); hoursWorked = scanner.nextDouble(); } scanner.close(); double gross = payRate * hoursWorked; System.out.println("Gross pay: $" + gross); } } ```
## For Loops Cashier ``` package cashier; import java.util.Scanner; public class Cashier { public static void main(String[] args){ System.out.println("Enter the number of items you would like to scan:"); Scanner scanner = new Scanner(System.in); int quantity = scanner.nextInt(); double total = 0; for(int i=0; i < quantity; i++) { System.out.println("Enter the cost of the item:"); double price = scanner.nextDouble(); total += price; } scanner.close(); System.out.println("Your total is " + total); } } ```
## Methods Instant Credit Check ``` package instant_credit_check; import java.util.Scanner; public class InstantCreditCheck { public static void main(String args[]) { Scanner scanner = new Scanner(System.in); System.out.println("Enter your salary: "); double salary = scanner.nextDouble(); System.out.println("Enter your credit score:"); int creditScore = scanner.nextInt(); scanner.close(); boolean qualified = isUserQualified(creditScore, salary); notifyUser(qualified); } public static boolean isUserQualified(int creditScore, double salary){ double requiredSalary = 25000; int requiredCreditScore = 700; if(creditScore>=requiredCreditScore && salary >= requiredSalary){ return true; } else { return false; } } public static void notifyUser(boolean isQualified) { if(isQualified){ System.out.println("Congrats, you've qualified!"); } else { System.out.println("Sorry, declined!"); } } } ```
## Arrays and Variable Arguments Calculate Sum ``` package calculate_sum; public class CalculateSum { public static void main(String[] args){ calculateSum(); calculateSum(2, 4); calculateSum(2, 4, 6, 8, 10); calculateSum(new int[]{1, 2, 3, 4}); int[] arr = {10, 11, 12}; calculateSum(arr); } // variable arg must be last parameter; can only have 1 public static void calculateSum(int ...a) { int sum = 0; for (int i=0; i < a.length; i++) { sum += a[i]; } System.out.println("Sum: " + sum); } } ```
## String and Methods ``` package text_processing; public class TextProcessor { public static void main(String[] args) { countWords("I love Java"); reverseString("stop"); } public static void countWords(String text) { String[] words = text.split(" "); int numOfWords = words.length; String message = String.format("Your text contains " + " %d words", numOfWords); System.out.println(message); for (int i=0; i < numOfWords; i++) { System.out.println(words[i]); } } public static void reverseString(String text){ for (int i=text.length()-1; i>=0; i--) { System.out.print(text.charAt(i)); } } } ```
## Java Classes
## Constructors, Setters, Getters Rectangle Classes ``` package objects; public class Rectangle { private double length; private double width; public Rectangle(){ length=0; width=0; } public Rectangle(double length, double width){ setLength(length); setWidth(width); } public double calculatePerimeter(){ return (2*length) + (2*width); } public double calculateArea(){ return length*width; } public double getLength(){ return length; } public void setLength(double length){ this.length = length; } public double getWidth() { return width; } void setWidth(double width){ this.width = width; } } ```
## Constructors, Set/Getters Room Area Calculator ``` package objects; import java.util.Scanner; public class HomeAreaCalculatorWithMethods { static Scanner scanner = new Scanner(System.in); public static void main(String[] args){ Rectangle kitchen = getRoom(); Rectangle bathroom = getRoom(); double area = calculateTotalArea(kitchen, bathroom); System.out.println("The total area is: "+ area); scanner.close(); } public static double calculateTotalArea(Rectangle rectangle1, Rectangle rectangle2){ return rectangle1.calculateArea() + rectangle2.calculateArea(); } public static Rectangle getRoom(){ System.out.println("Enter the length of your room:"); double length = scanner.nextDouble(); System.out.println("Enter the width of your room:"); double width = scanner.nextDouble(); return new Rectangle(length, width); } } ``` To use a class, they must be within the same package.
## Compiling in the Command Line ``` $ javac -cp . objects/*.java $ java -cp . objects.HomeAreaCalculatorWithMethods ``` - This builds .class files and you can run them - ```-cp``` means classpath Dockerfile ``` FROM eclipse-temurin:latest ADD . /app WORKDIR /app CMD javac objects/*.java; java objects/HomeAreaCalculatorWithMethods.java ```
## Docker Commands ``` docker build -t java-iamge . docker run --rm --name java-app -d -i -t java-iamge /bin/sh docker exec -it java-app bash ```
## Inheritance Base Class ``` package inheritance; public class Person { private String name; private int age; private String gender; public Person(){ System.out.println("In Person default constructor"); } public Person(String name){ System.out.println("In Person 2nd constructor. " + "Name is set."); } 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 setGender() { return gender; } public void setGender(String gender) { this.gender = gender;} } ```
## Inheritance Derived Class ``` package inheritance; public class Employee extends Person{ private String employeeId; private String title; public Employee(){ super("John Doe"); System.out.println("In Employee default constructor"); } public String getEmployeeId() { return employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } public void setTitle(String title) { this.title = title; } public String getTitle() { return title; } } ``` - ```extends``` allows for inheritance - ```super``` runs the base class's constructor
## Inheritance Sample Main ``` package inheritance; public class InheritanceChecker { public static void main(String[] args){ Person person = new Person(); Employee employee = new Employee(); } } ```
## Overriding & Overloading Methods Rectangle ``` package inheritance; public class Rectangle { protected double length; protected double width; protected double sides = 4; public double getLength() { return length; } public void setLength(double length) { this.length = length; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } public double getSides() { return sides; } public void setSides(double sides) { this.sides = sides; } public double calculatePerimeter(){ return (2*length) + (2*width); } public void print(){ System.out.println("I am a rect."); } } ```
## Overriding & Overloading Square ``` package inheritance; public class Square extends Rectangle{ @Override public double calculatePerimeter(){ return sides*length; } public void print(String what){ System.out.println("I am a " + what); } } ```
## Overriding & Overloading Sample Main ``` package inheritance; public class InheritanceChecker { public static void main(String[] args){ Rectangle rectangle = new Rectangle(); Square square = new Square(); square.setLength(4); square.print("SQ"); System.out.println("Square perimeter " + square.calculatePerimeter()); } } ```
## Sealed and Final Classes - Sealed classes restrict which other classes may extend them ``` public sealed class Shape permits Rectangle, Circle {} public sealed class Rectangle extends Shape permits Square {} public non-sealed class Circle extends Shape {} ``` - Final classes cannot be extended further ``` public final class Square extends Rectangle {} ```
## Polymorphism Animal ``` package polymorphism; public class Animal { public void makeSound(){ System.out.println("unknown animal sound"); } } ``` - Subclass define own unique behavior, but shares some common features - Animals can “morph” to others
## Polymorphism Cat ``` package polymorphism; public class Cat extends Animal{ @Override public void makeSound(){ System.out.println("meow"); } public void scratch(){ System.out.println("I am a cat. I scratch things."); } } ```
## Polymorphism Dog ``` package polymorphism; public class Dog extends Animal{ @Override public void makeSound(){ System.out.println("woof"); } public void fetch(){ System.out.println("Fetch is fun!"); } } ```
## Polymorphism Sample Zoo ``` package polymorphism; public class Zoo { public static void main(String[] args) { Dog rocky = new Dog(); rocky.fetch(); rocky.makeSound(); feed(rocky); Animal sasha = new Dog(); sasha.makeSound(); sasha = new Cat(); sasha.makeSound(); ((Cat)sasha).scratch(); feed(sasha); } public static void feed(Animal animal){ if(animal instanceof Dog) { System.out.println("Here's your dog food"); } else if (animal instanceof Cat) { System.out.println("Here's your cat food"); } } } ``` - ```instanceof``` lets you see if something is an instance of x class
## Abstraction Shape ``` package abstraction; public abstract class Shape { abstract double calculateArea(); public void print(){ System.out.println("I am a shape"); } } ``` - Abstract classes & methods are templates that must be implemented by their subclasses - Abstract classes cannot be instantiated
## Abstraction Rectangle ``` package abstraction; public class Rectangle extends Shape{ private double length; private double width; public Rectangle(double length, double width){ setLength(length); setWidth(width); } @Override double calculateArea() { return length*width; } public double getLength() { return length; } public void setLength(double length) { this.length = length; } public double getWidth() { return width; } public void setWidth(double width) { this.width = width; } } ```
## Abstraction Shape Tester ``` package abstraction; public class ShapeTester { public static void main(String[] args){ Shape rectangle = new Rectangle(5, 7); System.out.println(rectangle.calculateArea()); } } ``` Docker ``` CMD javac abstraction/*.java; java abstraction.ShapeTester ```
## Interfaces - Purely abstract - No constructors - Fields are final - Must be implemented by other classes - Must be constant, static, and final; can’t be private - Can have abstract, default, and static functions - Adding new methods in interface - use ```default``` to keep it backwards compatible - Can be overridden; better to leave it abstract - Static methods aren't inherited; can only be accessed by interface
## Interfaces Product Interface ``` package interfaces; public interface Product { String getName(); void setName(String name); default double getPrice() {return 50;} default void setPrice(double price){} } ```
## Interfaces Book ``` package interfaces; public class Book implements Product{ private String name; private String author; private int page; private String isbn; @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } } ```
## Interfaces Library ``` package interfaces; public class Library { public static void main(String[] args){ Product book = new Book(); book.setName("In the Kitchen with H+ Sport"); System.out.println(book.getName()); Book book2 = new Book(); System.out.println(book2.getPrice()); } } ```