Trimester 1 Notes

Casting Notes

  • Casting is when programmers are trying to assign a value from one data type to another data type
    • Widening Casting is when smaller data types convert to bigger data types
      • Happens automatically
    • Narrowing Casting is when larger data types convert to smaller data types
      • Happens manually
  • The chain of smallest to biggest data types is
    • byte, short, char, int, long, float, double
Widening Casting
public class Main {
    public static void main(String[] args) {
      int myInt = 9;
      double myDouble = myInt; // Automatic casting: int to double
  
      System.out.println(myInt);      // Outputs 9
      System.out.println(myDouble);   // Outputs 9.0
    }
  }
  Main.main(null);
9
9.0
Narrowing Casting
public class Main {
    public static void main(String[] args) {
      double myDouble = 9.78d;
      int myInt = (int) myDouble; // Manual casting: double to int
  
      System.out.println(myDouble);   // Outputs 9.78
      System.out.println(myInt);      // Outputs 9
    }
  }
  Main.main(null);
9.78
9
Casting with Division
  • Java typically assumes that an integer result is appropriate when doing division with integers
    • However, using a mixture of integers (int) and floating point numbers (double), Java assumes that a double result is appropriate
      • To do this though, one must use casting
        • Cast one of the integers to a double using (double), changing the “shape” or the data type of the variable
public class Test
{
   public static void main(String[] args)
   {
    // automatic casting here
     System.out.println(1 / 3);
     System.out.println(1.0 / 3);
     System.out.println(1 / 3.0);
     // manual casting here
     System.out.println((float) 1 / 3);
   }
}
Test.main(null);
0
0.3333333333333333
0.3333333333333333
0.33333334
Casting with Truncating
  • Truncating a number essentially means to round it
    • In division, using truncating would mean to remove the amount of decimal or fractional numbers to create an intended result
import java.io.*;   
public class TrunctionExample1  
{   
//driver code  
public static void main(String args[])   
{   
//the number to truncate      
double num = 19.87874548973101;   
//number of digits to take after decimal  
int digits = 5;   
System.out.println("The number before truncation is: "+num);   
//calling user-defined method that truncates a number  
truncateNumber(num, digits);   
}  
//user-defined method to truncate a number      
static void truncateNumber(double n, int decimalplace)   
{   
//moves the decimal to the right   
n = n* Math.pow(10, decimalplace);   
//determines the floor value  
n = Math.floor(n);   
//dividing the floor value by 10 to the power decimalplace  
n = n / Math.pow(10, decimalplace);   
//prints the number after truncation  
System.out.println("The number after truncation is: "+n);   
}   
}  
TrunctionExample1.main(null);
The number before truncation is: 19.87874548973101
The number after truncation is: 19.87874

Wrapper Classes

  • Is essentially the practice of using primitive data types as objects
  • You can use certain methods to get information about the specific object Methods like the following are used to get the value associated with the respective wrapper object
      intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), booleanValue()
public class Main {
    public static void main(String[] args) {
      Integer myInt = 5;
      Double myDouble = 5.99;
      Character myChar = 'A';
      System.out.println(myInt.intValue());
      System.out.println(myDouble.doubleValue());
      System.out.println(myChar.charValue());
    }
  }
Main.main(null);
5
5.99
A
  • The to String() method can be used when converting wrapper object to strings
    • The length() outputs the length of the "string" when converting an int to a string
public class Main {
    public static void main(String[] args) {
      Integer myInt = 100;
      String myString = myInt.toString();
      System.out.println(myString.length());
    }
  }
Main.main(null);
3

Concatenation

  • Combining two or more strings to form a new string
    • Happens by appending the next string to the end of the previous strings
    • In Java, two strings can be concatenated by using the + or += operator, or the concat() method in the java.lang.String class
  • Example
    • H E L L O + W O R L D becomes
    • H E L L O W O R L D
Concatenation Using + Operator
class HelloWorld {
    public static void main( String args[] ) {
        String first = "Hello"; 
        String second = "World";

        // way 1
        String third = first + second;
        System.out.println(third);

        // way 2
        first += second;
        System.out.println(first);        
    }
}
HelloWorld.main(null);
HelloWorld
HelloWorld
Concatenation Using Concat Method
class HelloWorld {
    public static void main( String args[] ) {
        String first = "Hello"; 
        String second = "World";

        String third = first.concat(second); 
        System.out.println(third);
    }
}
HelloWorld.main(null);
HelloWorld

Java Math Class.random

  • The java.lang.Math.random() is used to return a pseudorandom double type number that is >= 0.0 and < 1.0
    • Random number always between 0 and 1
public class MathClass  
{  
    public static void main(String[] args)   
    {  
        // generate random number  
        double a = Math.random();  
        double b = Math.random();  
        // Output is different every time this code is executed    
        System.out.println(a);  
        System.out.println(b);  
    }  
}  
MathClass.main(null);
0.22257006893484987
0.6831401769648252
Ranged Results
  • For specific range of values, you have to multiply the returned value with the magnitude of the range
    • To get the random number between 0 to 20, the resultant address has to be multiplied by 20 to get the desired result
public class RangedResult  
{  
    public static void main(String[] args)   
    {  
        // Generate random number between 0 to 20  
        double a = Math.random() * 20;  
        double b = Math.random() * 20;  
        // Output is different every time this code is executed    
        System.out.println(a);  
        System.out.println(b);  
    }  
}  
RangedResult.main(null);
5.542133912557907
4.062478517038832

Compound Boolean Expressions

  • Three compound boolean logical operators
    • Operand1 must be a boolean variable and op may be &, |, or ^
    • Java does not have any operators like &&= and ||=
  • Compound Boolean Logical Assignment Operators are used in the form operand1 op= operand2 which essentially means operand1 = operand1 op operand2
  • For &= operator, if both operands evaluate to true, &= returns true. Otherwise, it returns false.
    boolean b = true;
    b &= true;  // Assigns true to b
    b &= false; // Assigns false to b
public class Permission
{
   public static void main(String[] args)
   {
     boolean cleanedRoom = true;
     boolean didHomework = false;
     if (cleanedRoom && didHomework)
     {
         System.out.println("You can go out");
     }
     else
     {
         System.out.println("No, you can't go out");
     }
   }
}
Permission.main(null);
No, you can't go out

Truth Tables

  • Shows result for P && Q when P and Q are both boolean expressions (can be true or false)
    • An expression involving logical operators like (P && Q) evaluates to a Boolean value, true or false
    • P && Q is only true if both P and Q are true.

Truth Table with &&

  • Shows the result for P || Q when P and Q are both boolean expressions
    • P || Q is true if either P or Q is true
      • Also true when both of them are true

Truth Table with ||

De Morgan's Law

  • This law came after the man named Augustus De Morgan who developed it in the 1800s. The law states how to determine what the code will execute when negation rules are applied. For example, if a and b are both boolean values, then:
  • !(a && b) is equivalent to !a || !b
  • !(a || b) is equivalent to !a && !b

The following negation conditions will also apply under De Morgan's law:

  • < becomes >=
  • ">" becomes <=
  • == becomes !=
  • <= becomes >
  • = becomes <
  • != becomes ==
String state = "HI";

// !(a || b) is equivalent to !a && !b
if (!(state.equals("TX") || state.equals("HI"))) {
    System.out.println("The state is not Texas or Hawaii");
}
else {
    System.out.println("The state is either Texas or Hawaii");
}

// !(a && b) is equivalent to !a || !b
if (!(state.equals("TX") && state.equals("HI"))) {
    System.out.println("The state is either Texas or Hawaii");
}
else {
    System.out.println("The state is not Texas or Hawaii");
}
The state is either Texas or Hawaii
The state is either Texas or Hawaii

Comparing in Java

Comparing Numbers
  • To check two numbers for equality in Java, we can use the Equals() method as well as the == operator
    • First, you must set the Integers
      Integer val1 = new Integer(5);
      Integer val2 = new Integer(5);
  • Next check their equality using the == operator
    (val1 == val2)
public class CompareNum {
    public static void main( String args[] ) {
       Integer val1 = new Integer(5);
       Integer val2 = new Integer(5);
       Integer val3 = new Integer(10);
       System.out.println("Integer 1 = "+val1);
       System.out.println("Integer 2 = "+val2);
       System.out.println("Integer 3 = "+val3);
       System.out.println("val1 is equal to val2 = "+(val1 == val2));
       System.out.println("val2 is not equal to val3 = "+(val2 != val3));
    }
 }
CompareNum.main(null);
Integer 1 = 5
Integer 2 = 5
Integer 3 = 10
val1 is equal to val2 = false
val2 is not equal to val3 = true
Comparing Strings
  • There are five different ways to compare strings in Java
    • Using user-defined function
    • Using String.equals()
    • Using String.equalsIgnoreCase()
    • Using Objects.equals()
    • Using String.compareTo()
  • In general both equals() and == operator both are used to compare objects to check equality
    • There are some differences between the two
      • one is method and other is operator
      • == operators is for reference comparison and .equals() method is for content comparison
    • Essentially, == checks if both objects point to the same memory location whereas .equals() actually compares the values of two objects
Comparing Objects
  • You can compare objects in Java by using the == and != operators, which tells if two Java objects are the same or not
    • This also works when comparing a primitive value with its wrapper type counterpart
      Integer a = new Integer(1);
      assertThat(1 == a).isTrue();
  • The equals method can also be used to compare objects
    • The methods returns true if both objects are the same and false if the two objects are different

For, Enhanced For, While, and Nested Loops

For Loops
  • simplifies code by allowing it to repeat itself
  • while loops have two portions: the boolean expression and the brackets that have some code in them
    • the boolean expression is checked before the loop starts
      • every time the loop ends and is about to start anew
    • changes conditions again and again until returns false and ends the while loop
    • iterates over numerous elements
  • for loops has three portions: initialization, test condition, and change
    for (int x = 1; x <= 5; x++) {
      System.out.println(x);
    }
  • when the loop condition is false, execution will continue at the next statement after the body of the loop.
  • strings can also be manipulated through the use of iteration ``` String name = "CodeCodeCode";

for (int i = 0; i < name.length(); i+=2) { System.out.println(name.substring(i,i+2)); } ```

While Loops
  • The while loop loops through a block of code as long as a specified condition is true
    int i = 0;
    while (i < 5) {
    System.out.println(i);
    i++;
    }
Do While Loops
  • A variant of the while loop
    • Executes the code block once, before checking if the condition is true, then it repeats the loop as long as the condition is true
      int i = 0;
      do {
      System.out.println(i);
      i++;
      }
      while (i < 5);
Enhanced For Loops
  • there are also nested while loops
    • aren't very practical though
  • for each loops are similar to for loops
    • three portions to it
      • array, item, dataType
public class ForEachLoops {

    public static void main(String[] args) {

            // create an array
        int[] data = {2, 10, 5, 12};
    
            // for each loop 
        for (int number: data) {
        System.out.println(number);

    }
}
}
ForEachLoops.main(null);
2
10
5
12
Nested Loops
  • nested iteration is where there is a loop within a loop
    • similar to nested conditionals
      for (int row = 0; row < 5; row ++) {
      for (int column = 0; column < 4; column++) {
        System.out.print('*');
      }
      System.out.println();
      }

Creating a Class

  • There are a couple of steps to writing a class
    • make sure to use the class keyword to create a class in the start
    • To create an object of Main, specify the class name, followed by the object name, and use the keyword new
      • Constructors are used to create new objects
  • Instance variables are used to store any information regarding objects created in a class
  • Methods are used to show programs a new command they must run
    • specific methods are used to perform specific tasks in a class
Naming Conventions
  • For variables, the Java naming convention is to always start with a lowercase letter and then capitalize the first letter of every subsequent word
    • Variables can't contain white space, so variables made from compound words are to be written with a lower camel case syntax
      • firstName
      • timeToFirstLoad
      • index

Naming Conventions in Java

Constructors

  • A constructor in Java is a special method that is used to initialize objects
    • Called when an object of a class is created
    • Used to set initial values for object attributes
public class Main {
    int x;  // Create a class attribute
  
    // Create a class constructor for the Main class
    public Main() {
      x = 5;  // Set the initial value for the class attribute x
    }
  
    public static void main(String[] args) {
      Main myObj = new Main(); // Create an object of class Main (This will call the constructor)
      System.out.println(myObj.x); // Print the value of x
    }
  }
Main.main(null);
5
No Returns
  • What actually happens with the constructor is that the runtime uses type data generated by the compiler to determine how much space is needed to store an object instance in memory
  • Includes all members variables and after the space is designated, the constructor is called as an internal part of the instantiation and initialization process
  • The constructor exits, the runtime returns the newly-created instance
    • Can't return a value because it's not called directly by your code, it's called by the memory allocation and object initialization code in the runtime