Homework TOC
Week # | CB Topics | Score |
---|---|---|
Week 1 | 01 Primitive Types 02 Using Objects |
Unit 1: 1/1 Unit 2: 1/1 |
Week 2 | 03 Boolean Expressions and if Statements 04 Iteration 05 Writing Classes |
Unit 3: 0.8/1 Unit 4: 1/1 Unit 5: 0.85/1 |
Week 3 | 06 Array |
public class Test
{
public static void main(String[] args)
{
double x=4.567, y=15.356;
double d = y/x;
int z = (int)(y/x);
System.out.println(d);
System.out.println(z);
}
}
Test.main(null);
Wrapper Classes (Related to Unit 1: Primitive Types and Casting)
Wrapper classes can be used to turn primitive data types into an object to be used in object oriented code. Primitives are immutible and so are wrapper classes with primitives. Allows Java to technically be completed object oriented. Also allows us to use primitives and to work with collections like HashMaps and ArrayLists and perform complex operations.
public class Main {
public static void main (String args[]) {
int num = 67;
// int variable used as value of the wrapper class constructor
Double myDouble = new Double(num); // using Double wrapper class
// showing the double value
System.out.println("My double is " + myDouble);
}
}
Main.main(null);
public class Main {
public static void main (String[] args) {
int myInt = 67;
Double myDouble = Double.valueOf(myInt);// converting int to double using the Double valueOf() method
System.out.println("My double is " + myDouble);
}
}
Main.main(null);
Another example is the setStats API from the FRQ #2 practice.
Math Class (Related to all Units since this is helpful everywhere)
The Math Class has a lot of helpful methods that can be used in our code. It is vital to calculations and an example of its use it in the calculator code that we worked on during trimester 1. It does not need to be imported because it is in Java Lang Package
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
System.out.println("Input a angle in degrees");
int angle = user.nextInt();
double rangle = Math.toRadians(angle);
System.out.println("Your angle in randians is: " + Math.toRadians(angle));
System.out.println("Sine of " + angle + " is " + Math.sin(rangle));
System.out.println("Cosine of " + angle + " is " + Math.cos(rangle));
System.out.println("Tangent of " + angle + " is " + Math.tan(rangle));
}
}
Main.main(null);
Truth Tables (Related to Unit 3)
Truth tables are a combination of and (&&) and or (||)statements. They can help us see the results of conditionals and how ands and ors work together. Helpful for visualizing outcomes and potential results based on the input trues and falses that the conditional recieves
x | y | x && y | !x | !y | (!x && !y) | (x && y) \ | \ | (!x && !y) |
---|---|---|---|---|---|---|---|---|
T | T | T | F | F | F | T | ||
T | F | F | F | T | F | F | ||
F | T | F | T | F | F | F | ||
F | F | F | T | T | T | T |
Comparing Numbers (This could be all of the units but it mostly relates to Unit 3: Boolean Expressions and if Statements/ Unit 4: Iteration)
To compare two number you can use the two equal signs which indicates the comparison operator is being used. This is most frequently used in if statements or while statements. This only works for primitive data types. Other methods of comparison include greater than (>), less than (<), greater than and equals to (>=), and less than and equals to (<=), and not equals (!=).
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner user = new Scanner(System.in);
System.out.println("Give me a number!");
Scanner user2 = new Scanner(System.in);
System.out.println("Give me another number!");
int num1 = user.nextInt();
int num2 = user.nextInt();
System.out.println(num1);
System.out.println(num2);
if (num1 > num2){
System.out.println(num1 + " is greater than " + num2);
}
else if (num1 == num2){
System.out.println(num1 + " is equal to " + num2);
}
else if (num1 < num2){
System.out.println(num1 + " is less than " + num2);
}
}
}
Main.main(null);
Comparing Objects (This is most related to the Unit 2: Using Obects)
== and != operators can be used for wrapper classes and comparing them to a primitive value. To use those operators to compare the two objects you must use the format assertThat(a == b).isTrue(). Additionally there is the equals() method that serves the same purpose as the double equals operator. However, this equals method can be overridden to compare objects based on their internal details within a class. There are also comparator interface methods that you must implement yourself including compareTo(), compareBy___(), and more.
public class Person {
private String firstName;
private String lastName;
public Person(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person that = (Person) o;
return firstName.equals(that.firstName) &&
lastName.equals(that.lastName);
}
Person.main(null);
while loop versus do while loop (Related to Unit 4: Iteration)
while loop executes while a condition is true and terminates otherwise. do while loop is guaranteed to execute at least one time. the do will execute and then the while condition is checked and the program will either continue to execute or terminate.
Wrapper Classes, why wrap int, double. Show examples Math class, specifically Random usage Truth Tables Comparing Numbers Comparing Objects while loop versus do while loop Creating a Class, describe Naming Conventions Accessor methods, relationship to getter Static variables, Class variables, show use case in code Static methods, Class methods main method, tester methods Subclass constructor, super Keyword Overriding a method, same signature of a method Standard methods: toString(), equals(), hashCode() Polymorphism: any of overloading, overriding, late binding
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}while(i<=10);
}
}
DoWhileExample.main(null);
Creating a Class, describe Naming Conventions (Related to Unit 5: Writing Classes)
Naming convention is lowercase first word then any words after that should be title case. A class is a set of objects that have common methods and attributes. Class is a blueprint for objects. Class has groups of variables and group of methods. To create a class use the word class and specify the access modifier.
Syntax: access_modifier class Class declarations can have modifiers, class keywords, class names, superclasses, or interfaces. An accessor method is a method that gets private data that is sotred in an object. This allows a way to get the value of each instance variable from outside of the class. Allows data use in other places than just the class that it was declared in. Accessor methods are know as getters. (Similar to how an API gets a response from a request sent from outside of the API) Mutator methods reset the value of a private variable. It gives other classes the ability to modify the value stoed in that variable without having direct access to the variable itself. Allows the user to set/mutate the value of the private variables of a class object. aka setters. Used along with getters to protect sensitive information (private) in a class. A static variable (same as class variable) is a variable that is declared in the class and can only be used by objects and methods in that class. However it can be used in all instances of the class. Static variabiles can be accessed using class names and they can be accessed by static and non static methods. Only initialized once. The variable belongs to the class. Example of this use is in the math classes we worked with during trimester 1 Public: allows access from any class Private: restricts access to only the class that declared the structure Default: acccess allowed withint the same package Protected: access allowed within the class/package and outside of the class/package only if there is a child class/package. the only way to access is through inheritance A static method is a method that belongs to the class and not a specific object of the class. It can only access static data and not non-static data. It can call other static methods and can be accessed by the class name. It cannot refer to "this" or "super". Static methods are methods that can be called within a program without creating an object of the class Subclass inherits all the members which include fields, methods, and nested classes from its superclasss. constructors are not inheritted by the subclass. inheritance helps you create a new class out of a class that already exists. Subclasses have their own code of their own that are initialized.The invocation of a super class constructor must be the first line of the subclass constructuor Overriding is when the child class has a method that is present in the parent class. The child class must have a different implementation of the method that is already present in the parent class. depending on which method is called the result is different based on the overriden method toString(): returns a string representing the object. converts an object to a primitive value equals(): compares two strings and objects and returns true if the strings are equals and false if not hashCode(): returns an integer value generated by a hasing algorithm. it finds the hash values of given input object and returns a value that represents the hash value. hash values are used throughout codepublic class Students{
// Body of the class
}
private class studentIDs{
// Body of the Class
}
public class Person{
int age,height,weight;
public Person(int age, int height, int weight){
this.age = age;
this.height = height;
this.weight = weight;
}
}
public class Main{
public static void main(String args[]){
Person person1 = new Person(18, 67, 120);
}
}
Accessor methods, relationship to getter (Related to Unit 5: Writing Classes)
public class TesterClass
{
// main method for testing
public static void main(String[] args)
{
Student s1 = new Student("Skyler", "skyler@sky.com", 123456);
System.out.println("Name:" + s1.getName() );
System.out.println("Email:" + s1.getEmail() );
System.out.println("ID: " + s1.getId() );
}
}
/** Class Student keeps track of name, email, and id of a Student. */
class Student
{
private String name;
private String email;
private int id;
public Student(String initName, String initEmail, int initId)
{
name = initName;
email = initEmail;
id = initId;
}
// accessor methods - getters
/** getName() @return name */
public String getName()
{
return name;
}
/** getEmail() @return email */
public String getEmail()
{
return email;
}
/** getName() @return id */
public int getId()
{
return id;
}
}
TesterClass.main(null);
Mutator methods, relationship to setter, describe void return type
import java.util.Arrays;
public class Student {
private String name;
private Integer ID;
private String DOB;
private double GPA;
private String[] courses;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getID() {
return ID;
}
public void setID(Integer iD) {
this.ID = iD;
}
public String getDOB() {
return DOB;
}
public void setDOB(String dOB) {
this.DOB = dOB;
}
public double getGPA() {
return GPA;
}
public void setGPA(double gPA) {
this.GPA = gPA;
}
public String[] getCourses() {
return courses;
}
public void setCourses(String[] courses) {
this.courses = courses;
}
public static void main(String[] args) {
Student student1 = new Student();
System.out.println("Student Bio [ Before using Accessors & Mutators ]");
// calling accessor methods
System.out.print("Name: " + student1.getName());
System.out.print("\tID: " + student1.getID());
System.out.print("\tGPA: " + student1.getGPA());
System.out.print("\tDOB: " + student1.getDOB());
System.out.println("\tCourses: " + Arrays.toString(student1.getCourses()));
// calling mutator methods
student1.setName("Alex Coy");
student1.setID(3115);
student1.setGPA(2.79);
student1.setDOB("08/08/1998");
String[] courses = { "Object Oriented Programming", "Cryptography", "Photography", "Network Security" };
student1.setCourses(courses);
System.out.println("\nStudent Bio [ After using Mutators & Accessors ]");
// calling accessor methods
System.out.print("Name: " + student1.getName());
System.out.print("\tID: " + student1.getID());
System.out.print("\tGPA: " + student1.getGPA());
System.out.print("\tDOB: " + student1.getDOB());
System.out.println("\tCourses: " + Arrays.toString(student1.getCourses()));
}
}
Student.main(null);
Static variables, Class variables, show use case in code (Relates to Unit 5: Writing Classes)
public abstract class Fibo {
String name; // name or title of method
int size; // nth sequence
int hashID; // counter for hashIDs in hash map
ArrayList<Long> list; // captures current Fibonacci sequence
HashMap<Integer, Object> hash; // captures each sequence leading to final result
// Static variables being initialized once for use throughout the entire class
Show use case of access modifiers: Public, Private, Protected (This relates to Unit 5: Writing Classes)
Static methods, Class methods (Relates to Unit 5: Writing Classes)
public class Main{
// static method
public static int getTotal(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int x = 3;
int y = 2;
System.out.println(getTotal(x,y)); // Prints: 5
}
}
Main.main(null);
public class Demo{
public static void main(String args[]){
Student s1 = new Student();
s1.showData();
Student s2 = new Student();
s2.showData();
Student.b++;
s1.showData();
}
}
class Student {
int a; //initialized to zero
static int b; //initialized to zero only when class is loaded not for each object created.
Student(){
//Constructor incrementing static variable b
b++;
}
public void showData(){
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
//public static void increment(){
//a++;
//}
}
Demo.main(null);
public class Demo {
public static void main(String args[]){
System.out.print("Hello world!");
}
}
Demo.main(null);
Subclass constructor, super Keyword (This relates to Unit 5: Writing Classes)
public class Subclass extends Superclass {
public static void main(String args[]){
super();
}
}
Overriding a method, same signature of a method
public class Adult{
public void knowAge(){
System.out.println("You are an adult!");
}
}
public class Child extends Adult{
public void knowAge(){
System.out.println("You are a child!");
}
}
public class Main{
public static void main(String args[]){
Adult person = new Adult();
person.knowAge();
Child kid = new Child();
kid.knowAge();
}
}
Main.main(null);
Standard methods: toString(), equals(), hashCode()
// Java Program for Method overloading
// By using Different Types of Arguments
// Class 1
// Helper class
class Helper {
// Method with 2 integer parameters
static int Multiply(int a, int b)
{
// Returns product of integer numbers
return a * b;
}
// Method 2
// With same name but with 2 double parameters
static double Multiply(double a, double b)
{
// Returns product of double numbers
return a * b;
}
}
// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// Calling method by passing
// input as in arguments
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(5.5, 6.3));
}
}
GFG.main(null);