Vocabulary and its Integration
Homework Assignments
Type Casting in Java
when you assign a value of one primitive data type to another type.
Two types of casting in Java:
- Widening Casting (automatically) - converting a smaller type to a larger type size
byte -> short -> char -> int -> long -> float -> double
- Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte
Casting, specifically for Division
- Integer and integer resulting in integer
- If you want it to become a decimal, make it into a double
- Type promotion (with an integer and a double value) makes it more complicated, resulting in the decimal
//example
public class Variables {
public static void main (String[] args) {
}
}
System.out.println(10.0/15);
public class Variables
{
public static void main(String[] args)
{
}
}
int x=10;
int y=15;
System.out.println(1 / 3);
System.out.println(1.0 / 3);
System.out.println(1 / 3.0);
System.out.println((double) x / y);
//type promote; produces decimal answer
//modulus
public class Variables
{
public static void main(String[] args)
{
}}
System.out.println(15%10);
Casting, specifically for Truncating or Rounding
Truncation vs. Rounding
- Rounding a number in the range [2.5, 3.5) returns the number 3
- Truncating a number in the range [3.0, 4.0) returns the number 3
- Where a square bracket '[' denotes inclusion in the range, and a parenthesis '(' denotes non-inclusion in the range -- ie. [3.0, 4.0) is the range of all numbers between 3 and 4, including 3 but not including 4.
- truncation; chops off decimal portion
//truncation
public class truncation
{
public static void main(String[] args)
{}}
//example
int a, b, c;
double d, e;
//declare variables
a = 5;
b = -13;
d = 2.8;
c = a + (int)d; //typecasting
//truncation, cut off decimal
//d became 2 instead of 2.8, so 2 + 5 = 7
System.out.println("c is: " + c);
//rounding
public class rounding
{
public static void main(String[] args)
{}}
double number = 2.8;
System.out.println( "before rounding: " + number );
number = Math.round(number);
System.out.println( "after rounding: " + number );
double number = 2.4;
System.out.println( "before rounding: " + number );
number = Math.round(number);
System.out.println( "after rounding: " + number );
Wrapper Classes
- Why wrap int, double, etc?
- way to use primitive data types as objects
Primitive Data Type | Wrapper Class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
boolean | Boolean |
char | Character |
- Primitive type and corresponding wrapper class
- Wrapper classes are used to convert any data type into an object. The primitive data types are not objects; they do not belong to any class; they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language.
public class wrappers
{
public static void main(String[] args)
{}}
// int x = 10;
// System.out.println(x.toString()); ------ doesn't work because x is a primitive data type, not a modifiable object
Integer x = new Integer(10);
//to get around this, you define an integer wrapper class
System.out.println(x.toString());
//x is now an object, not a primitive data type
Integer x = new Integer(15);
//ex
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));
class concatenation
{
public static void main(String arg[])
{
}
}
String str1 = "hello", str2 = " to you", str3 = " too";
str1 = str1 + str2 + str3; // LINE A
System.out.println(str1);
//line a is '+' operator
str2 = str2.concat(str3);
System.out.println(str2); //line B
//concat() method
boolean folklore = true;
boolean evermore = false;
System.out.println("Folklore is a great album." + "\nThis statement is " + folklore); // LINE C
System.out.println("Folklore is a bad album." + "\nThis statement is " + evermore);
//concatenation of a boolean to a string
import java.lang.Math;
//java.lang.Math.random()
class random {
// driver code
public static void main(String args[])
{
}
}
double rand = Math.random();
System.out.println("Random Number:" + rand);
//ex
//want to play video games, but parents only let you if you've finished your homework and taken a shower
public class compoundBooleans
{
public static void main(String[] args)
{
boolean didHomework = true;
boolean tookShower = false;
if (tookShower && didHomework)
{
System.out.println("You can play");
}
else
{
System.out.println("No, you can't play");
}
}
}
//demorgans law
//has to be back home before 10, and has to walk the dog
public class demorgans
{
public static void main(String[] args)
{
boolean backby10 = true;
boolean walkedDog = false;
if (!(backby10 && walkedDog))
//means not A OR not B
{
System.out.println("True. You were back by 10 but didn't walk the dog");
}
else
{
System.out.println("You were back in time and walked the dog");
}}}
public class demorgans
{
public static void main(String[] args)
{
boolean backby10 = true;
boolean walkedDog = false;
if (!(backby10 || walkedDog))
//means not A AND not B
{
System.out.println("False. You were back by 10 but didn't walk the dog");
}
else
{
System.out.println("You were back in time and walked the dog");
}
}
}
//comparing numbers
public class wrappers
{
public static void main(String[] args){}
}
int x = 10;
int y = 14;
if(x==(y)) {
System.out.println("Both x and y are equal");
}
else
System.out.println("x and y are not equal");
public class wrappers
{
public static void main(String[] args){}
}
// int x = 10;
// System.out.println(x.toString()); ------ doesn't work because x is a primitive data type, not a modifiable object
Integer x = new Integer(10);
//to get around this, you define an integer wrapper class
System.out.println(x.compareTo(15));
//x is now an object, not a primitive data type
System.out.println(x.compareTo(5));
//-1 is b/c 10 is less than 15
//1 is because 5 is less than 10
int xy = 83;
int yz = 20;
int compare = Integer.compare(xy, yz);
if(compare>0) {
System.out.println("xy is greater than yz");
}
else if (compare<0){
System.out.println("xy is less than yz");
}
else
System.out.println("xy and yz are equal");
class comparingStrings{
public static void main(String args[]){
}
}
String s1="hello";
String s2="goodbye";
String s3=new String("hello");
String s4="you're a good friend";
String s5="goodbye";
if (s2 == s5){
System.out.println("true");
}
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
class Food {
//attributes
String cuisine;
String name;
int mealsConsumed;
//constructor
Food(String cuisine, String name, int mealsConsumed)
{
this.cuisine = cuisine;
this.name = name;
this.mealsConsumed = mealsConsumed;
}
}
//objects
Food Dal1 = new Food("Indian", "Mango Dal", 10);
Food Dal2 = new Food("Indian", "Moong Dal", 4);
System.out.println("Dal1 = Dal2 is " + Dal1.equals(Dal2));
For, While, Nested Loops
while loop
- executed while something is happening
- iterates over elements
- can be infinite if boolean is always true
do-while loop
- condition is checked after executed statements
for loop
- certain amt of loops thru code block
nested loop
- loop w/in loop
for-each loop
- traverses an array in java
int x = 10;
while (i<10) {
System.out.println(i);
i++;
}
public class arrays
{
public static void main(String[] args)
{
}}
public static void main(String[] args) {
int[] numbers = {2, 4, 6, 8, 10};
int i = 0;
while (i < numbers.length) {
System.out.println(numbers[i]);
i++;
}}
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
//for-each loop
int arr[]={10,20,30,40,50};
for(int j:arr){
System.out.println(j);
}
Writing Classes
- blueprint for objects
- has constructors, methods, variables, attributes
- objects are instances of a class
- attributes are components
- methods are object actions
- public/private -- accessible/not accessible outside the class
- constructors initialize instance variables when objects are created
- Naming Conventions: CamelCase (simple, descriptive, straightforward)
class Food {
//attributes
private String cuisine;
private String name;
private int mealsConsumed;
//instance variables
//constructor
Food(String cuisine, String name, int mealsConsumed)
{
this.cuisine = cuisine;
this.name = name;
this.mealsConsumed = mealsConsumed;
}
public String getName(){
return name;
}
}
public class Foodmain {
public static void main(String[] args) {
Food newFood = new Food("Indian", "Idli", 20);
System.out.println(newFood.getName());
}
}
Foodmain.main(null)
import java.util.Scanner; //allows scanners to be in program
public class averages {
public static void main(String[] args) {
}}
Scanner in = new Scanner(System.in); //creates a scanner
System.out.print("Input 1st number: "); //asks user for input
int num1 = in.nextInt(); //saves number and goes to next int
System.out.println(num1);
System.out.print("Input 2nd number: "); //same as above
int num2 = in.nextInt();
System.out.println(num2);
System.out.println("The average of those numbers are " + (num1 + num2)/(2));
//prints out
//num you want to divide is however many numbers you want to average out
averages.main(null)
public class Main {//main class
int modelYear;
String modelName;//attributes
public Main(int year, String name) {//constructor
modelYear = year;
modelName = name;
}
public static void main(String[] args) {
Main myCar = new Main(1969, "Mustang");//objects
System.out.println(myCar.modelYear + " " + myCar.modelName);
}
}
// Outputs 1969 Mustang
Main.main(null);
//basic example
public class Person {
private String name; // private = restricted access
// Getter
public String getName() {
return name;
}
// Setter
public void setName(String newName) {
this.name = newName;
}
}
import java.util.Scanner;
public class Main {
//static variables
private static String[] words = {"words", "to", "put", "in"};
private static String word = words[(int) (Math.random() * words.length)];
private static String asterisk = new String(new char[word.length()]).replace("\0","*");
private static int count = 0;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//create a while loop when count is less than 7 and
//when asterisk contains *
while (count < 7 && asterisk.contains("*")) {
//print guess any letter in the word
//print asterisk
//take in guess and scan it in (string guess and take in scan)
//hang(guess)
System.out.println("Guess any letter in the word");
System.out.println(asterisk);
String guess = sc.next();
hang(guess);
}
sc.close();
}}
//private
import java.util.*; //import scanner
public class Main {
private static String reverse_str_order(String input_sentence) { //
if (input_sentence == null) {
throw new IllegalArgumentException("Null"); //no empty strings
}
StringBuilder stringBuilder = new StringBuilder();
String[] words = input_sentence.split(" ");
for (int i = words.length - 1; i >= 0; i--) {
stringBuilder.append(words[i]); //place words in order
if (i != 0) { //keep going until no more words are left
stringBuilder.append(" ");
}
}
return stringBuilder.toString();
}
}
public static void main(String[] args) { //prepares for scanning
Scanner scanner = new Scanner(System.in);
System.out.print("Input string: "); //asks for user input
String input = scanner.nextLine(); //takes in next line
System.out.println("\nResult: " + reverse_str_word(input));
}
//public
import java.util.*; //import scanner
public class Main {
public static String reverse_str_order(String input_sentence) { //
if (input_sentence == null) {
throw new IllegalArgumentException("Null"); //no empty strings
}
StringBuilder stringBuilder = new StringBuilder();
String[] words = input_sentence.split(" ");
for (int i = words.length - 1; i >= 0; i--) {
stringBuilder.append(words[i]); //place words in order
if (i != 0) { //keep going until no more words are left
stringBuilder.append(" ");
}
}
return stringBuilder.toString();
}
}
public static void main(String[] args) { //prepares for scanning
Scanner scanner = new Scanner(System.in);
System.out.print("Input string: "); //asks for user input
String input = scanner.nextLine(); //takes in next line
System.out.println("\nResult: " + reverse_str_word(input));
}
//protected
import java.util.*; //import scanner
public class Main {
protected static String reverse_str_order(String input_sentence) { //
if (input_sentence == null) {
throw new IllegalArgumentException("Null"); //no empty strings
}
StringBuilder stringBuilder = new StringBuilder();
String[] words = input_sentence.split(" ");
for (int i = words.length - 1; i >= 0; i--) {
stringBuilder.append(words[i]); //place words in order
if (i != 0) { //keep going until no more words are left
stringBuilder.append(" ");
}
}
return stringBuilder.toString();
}
}
public static void main(String[] args) { //prepares for scanning
Scanner scanner = new Scanner(System.in);
System.out.print("Input string: "); //asks for user input
String input = scanner.nextLine(); //takes in next line
System.out.println("\nResult: " + reverse_str_word(input));
}
public class friends
{
// instance variables
private String name;
private String email;
private String phoneNumber;
// Static counter variable
public static int personCounter = 0;
// static method to print out counter
public static void printPersonCounter() {
System.out.println("Person counter: " + personCounter);
}
// constructor
public friends(String initName, String initEmail, String initPhone)
{
name = initName;
email = initEmail;
phoneNumber = initPhone;
personCounter++;
}
// toString() method
public String toString()
{
return name + ": " + email + " " + phoneNumber;
}
// main method for testing
public static void main(String[] args)
{
// call the constructor to create a new person
friends p1 = new friends("Sana", "sana@gmail.com", "123-456-7890");
friends p2 = new friends("Jean", "jean@gmail.com", "404 899-9955");
friends.printPersonCounter();
}
}
//class methods
public class Main {
static void myMethod() {
System.out.println("Hello World!");
}
}
//methods declared within a class
//ex
public class Main {
int x;
// Constructor with a parameter
public Main(int x) {
this.x = x;
}
//this used to
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
//ex
class school {
protected String brand = "work"; // attribute
public void pencil() { // method
System.out.println("write, write!");
}
}
class classwork extends school {
private String modelName = "google doc"; // attribute
public static void main(String[] args) {
// Create a new school object
School mySchool = new School();
// Call the pencil() method (from the school class) on the work object
mySchool.pencil();
// Display the value of the brand attribute (from the Vehicle class) and the value of the modelName from the Car class
System.out.println(mySchool.brand + " " + mySchool.modelName);
}
}
Subclass constructor, super Keyword
- subclass; inheriting class
- super: refers to parent objects; calls superclass methods
Overloading a method, same name different parameters
- java feature allowing classes to have more than one method that is named the same (but it must have different parameters)
- easier to overload one instead of having to define two identically-functioning methods
Overriding a method, same signature of a method
- when a subclass has the same method has the parent class
- implements a certain aspect of method declared by a parent class
Abstract Class, Abstract Method
- is a method that has just the method definition but no actual implementation
- can be subclassed, not instantiated
Standard methods: toString(), equals(), hashCode()
- toString returns string
- hashCode returns hashCode of a string
public class toString
{
public static void main(String[] args)
{}}
Integer x = new Integer(10);
System.out.println(x.toString());
System.out.println(x.toString(90));
public class hashCode
{
public static void main(String[] args)
{}}
String str_New = "yay!";
System.out.println(str_New.hashCode());
Late binding of object
- name of method looked up at runtime
- compiler doesn't perform argument checks and leaves it up to runtime
Polymorphism
- class has different implementations of a method
- same action performed differently
Big O notation for Hash map, Binary Search, Single loop, Nested Loop
- language for runtime length
- related to efficiency
hashmap: single operation to obtain position of a searched element
O(1) binary search
O(1) eliminates half the elements each time single loop
O(n) The next loop executes N times, if we assume the statement inside the loop is O(1), then the total time for the loop is N*O(1), which equals O(N) also known as linear time nested loop
O(N*N) the first loop may execute N times, but for how many first loop executes, the inner loop executes N times