Java

Notes

Data types

8 primitive types in total

Below types are not primitive (are stored on heap instead of stack)

Variables

Operators

some operators (like +) are overloaded depending on the operads and position

Printing

User Input (Scanner Class)

import java.util.Scanner;

Scanner ip = new Scanner(System.in);

System.out.print("Enter something: ");
String something = ip.nextLine();
System.out.println("Something is " + something);

// <type> someVar = ip.next[Int | Float | Double | ...]();
// For next word use "next" (space terminates)
// For next line use "nextLine" (newline/enter terminates)
// Careful when using nextLine _after_ other next* as they leave newline in buffer

// VALIDATION
System.out.print("Enter an invalid int: ");
if (ip.hasNextInt()) {
  int x = ip.nextInt();
  System.out.println("it's a valid int: " + x);
} else {
  System.out.println("it's an invalid int: " + x);
}

input.close();

Type casting gotchas

Conditionals (Branching | Selection)

Loops

Strings

Arrays


// Syntax

// <type> [] <var_name> = new <type>[<capacity>];

// Example

int [] array_of_five_ints = new int[5];

String [] arrayOf10String = new String[10];

MyObject [] arrayOfCustomObj = new MyObject[3];

// Example to create with pre-filled data

char [] vowels = { 'a', 'e', 'i', 'o', 'u' }; // => new Char[5];

Classes & Objects

/*

Syntax:

<modifier> class <class_name> extends <another_class> implements <interfaces> {

    // fields
    <modifier> <type> <var_name>;

    // constructor
    <modifier> <class_name>(<type> <var>) {
      <var_name> = <var>;
    }

    // methods
    <modifier> <type> <fn_name>(<params>) {
        ...
    }
}

modifier = public, private, protected, static etc

constructor is optional and can be overloaded like methods

*/

// Example Public Bike Class

public class Bike {

  static int numWheels = 2;
  int fuelTank = 12; // Ltr

  public Bike(int fuelTankInLtr) {
    fuelTank = fuelTankInLtr;
  }
}

// Creating a new Bike Object

Bike b = new Bike(18);

OOP Pillars