Casting

Type casting is when you assign a value of one primitive data type to another type.

Widening: (automatically) - converting a smaller type to a larger type size

Narrowing: (manually) - converting a larger type to a smaller size type

// casting in the case of division 

public class division{
    public static void main(String args[]){
    int a = 2;
    int b = 3;

    System.out.println(b/a);
}
    
}

division.main(null);
1
public class casting{
    public static void main(String args[]){
    int a = 2;
    double b = a;

    double c = 2.99;
    int d = (int)c;

    System.out.println("Widening");
    System.out.println(a);
    System.out.println(b);
    System.out.println("------");

    System.out.println("Narrowing");
    System.out.println(c);
    System.out.println(d);
}
    
}
casting.main(null);
Widening
2
2.0
------
Narrowing
2.99
2

Wrapper Classes

In cases such as arrayLists, sometimes data can only be stored as objects. To get around this, we used wrapper classes to store primitive data types as objects.

These wrapper classes also have corresponding methods

ArrayList<int> myNumbers = new ArrayList<int>(); // it cannot store integers
|   ArrayList<int> myNumbers = new ArrayList<int>(); // it cannot store integers
unexpected type
  required: reference
  found:    int

|   ArrayList<int> myNumbers = new ArrayList<int>(); // it cannot store integers
unexpected type
  required: reference
  found:    int
ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // stores the object as an integer wrapper class

Concatenation

Concatenation is combining two or more strings using the "+", "+=", or concat() method

You must use the Datatype.toString(var) method to convert different datatypes to strings

public class concat{
    public static void main(String args[]){
        String text1 = "ora";
        String text2 = "nge";

        String fruit1 = text1 + text2;
        String fruit2 = text1.concat(text2);

        System.out.println(fruit1);
        System.out.println(fruit2);
}
    
}
concat.main(null);
orange
orange

Math Class

The Java Math class provides several methods to perform calculations and other functions involving numbers.

public class random{
    public static void main(String args[]){
        double random = Math.random();
        System.out.println(random);
}
    
}
random.main(null);
0.4452733827420724

Compound Boolean Expressions

Using the (AND) && and (OR) || operations in conditionals

public class compoundBooleans {
    public static void main(String args[]){
        int a = 1;

        if (a < 10 && a > 0){
            System.out.println("a is between 0 and 10");
        }
        else {
            System.out.println("a is either negative or greater than 10");
        }
}
    
}
compoundBooleans.main(null);
a is between 0 and 10

Truth Tables

Booleans return only true or false, and we use truth tables to organize the outputs of an operation

a=true, b=false, c=true, d=true

AND OR XOR
A, B False True True
C, D True True False

De Morgan's Law

A law that simplifies boolean expressions

Examples: !(a && b) is equivalent to !a || !b !(a || b) is equivalent to !a && !b

Comparing Numbers

You can use the compare() method or an == operator to compare two different numeric values.

The compare() method returns 0 if true, -1 if value one is less than value two, and 1 if value one is greater than value two

public class comparingNumbers {
    public static void main(String args[]){
        int a = 3;
        int b = 3;

        System.out.println(Integer.compare(a, b));

        System.out.println(a == b);

}
    
}
comparingNumbers.main(null);
0
true

Comparing Strings

There are many ways to compare strings. Some of the common ways include using the String.equals() method

Here is a link to other possible methods

public class comparingStrings {
    public static void main(String args[]){
        String fruit = new String("Banana");
        String fruit2 = new String("Banana");

        System.out.println(fruit.equals(fruit2));

    }

}

comparingStrings.main(null);
true

Comparing Objects

Similarly to numbers and strings, you can use the == operators or the equals() method.

== will see if the objects have the same identity, while .equals will see if the objects hold the same value

It is also common to use the assert method which must be imported. Here are outside examples

public class comparingObjects {
    public static void main(String args[]){
        Integer a = new Integer(1);
        Integer b = new Integer(1);

        if(a.equals(b)){
            System.out.println("true");
        }
        else{
            System.out.println("false");
        }

    }
}

comparingObjects.main(null);
true

For Loops and Enhanced For Loops

For loops are a great tool for iteration. For loops can be incremented by whatever value you wish, while enhanced for loops (for-each) must execute code in a sequence.

Enhanced for loops are often used to traverse arrays/arrayLists

import java.io.*;
import java.util.*;

public class forLoops{
    public static void main(String args[]) {
        //for loop
        for (int i = 0; i < 6; i+=2 ){
            System.out.print("Code ");
        }

        //enhanced for loop
        int[] num = { 1, 2, 3};
    
        for (int a : num) {
            System.out.print(a);
            }
    }
}

forLoops.main(null);
Code Code Code 123

While Loop vs. Do While Loop

While loops execute a block of code while a condition is true

While do loops execute code until a condition is true

public class whileLoop{
    public static void main(String args[]) {
        //while loop
        int a = 3;
        while ( a > 0 ){
            System.out.print("code ");
            a--;
        } 
        //while do loop
        int b = 3;
        do {
            System.out.println(b);
            a++;
        } while (b > 7);
    
}
}

whileLoop.main(null);
code code code 3

Nested Loops

Nested loops are loops within loops

public class nestedLoops {
    public static void main(String[] args) {
  
      int weeks = 2;
      int days = 7;
  
      // outer loop prints weeks
      for (int i = 1; i <= weeks; ++i) {
        System.out.println("Week: " + i);
  
        // inner loop prints days
        for (int j = 1; j <= days; ++j) {
          System.out.println("  Day: " + j);
        }
      }
    }
  }

nestedLoops.main(null);
Week: 1
  Day: 1
  Day: 2
  Day: 3
  Day: 4
  Day: 5
  Day: 6
  Day: 7
Week: 2
  Day: 1
  Day: 2
  Day: 3
  Day: 4
  Day: 5
  Day: 6
  Day: 7

Creating a Class

A class is a blueprint for creating object and contains attributes and methods

public class Class {
    int x = 5;
  
    public static void main(String[] args) {
      Class obj = new Class();
      System.out.println(obj.x);
    }
  }

Class.main(null);
5

Constructor

A constructor is a special method that is used to initialize objects

// Create a Main class
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
    }
  }
  
  // Outputs 5

Main.main(null);
5

Accessor Methods

Accessor methods return value of private variables and give other classes access to that value

public class accessor{
    private int num;
    
    //An accessor method
    public int getBalance(){
      return this.num;
    }
  }

Mutator Methods

Mutator methods reset the value of a private variable and gives other classes to change the value stored in the variable

public class mutator{
    private int num;
    
    //A mutator method
    public void setNum(int newNum){
      this.num = newNum;
    }
  }

Static Variables and Class Variables

Both static and non-static methods can access or change the values of static variables

Access Modifiers (Public, Private, Protected)

public: anyone can access

private: only are accessible within the class

protected: can only be accessed within its own package

Static Methods and Class Methods

Static methods can be called within a program without creating an object of a class.

Static methods are associated with the class as a whole

// 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
  }

this Keyword

The this keyword is used to designate difference between instance variables and local variables. Variables with this. reference an instance variable

public class Keyword{
    public void exampleMethodOne(){
      System.out.println("Hello");
    }
  
    public void exampleMethodTwo(){
      //Calling a method using this.
      this.exampleMethodOne();
      System.out.println("There");
    }
  }