JAVA 1-100

Java Programming Language

  • Java is a popular programming language used on billions of devices.

  • Java is both a programming language and an environment to run code.

  • Programs are written in Java and run on the Java Virtual Machine (JVM).

Object-Oriented Programming (OOP) in Java

  • Java is inherently an OOP language.

  • All code must be defined inside a class.

  • A class can be called anything, but every program must have a public static void main(String[] args) method (function).

  • Example: java public class FirstProgram { public static void main(String[] args) { System.out.println("Hello, world!"); } }

    • Defines a class.

    • Specifies where the program starts.

    • Prints a String to the user.

Compilation in Java

  • Java is a compiled language.

  • Source code (.java file) is compiled into a program before running (.class file).

  • Compiling performs optimizations and creates instructions the computer can execute.

  • Advantage: Only need to share programs, not source code.

  • Programs run in the Java Virtual Machine (JVM), which understands .class files.

  • JVM provides portability.

  • Available on desktops, laptops, servers, phones, embedded devices, etc.

  • Commands:

    • ~$ javac FirstProgram.java: Compiles .java files into .class files.

    • ~$ java FirstProgram: Runs the FirstProgram.class, starting in the main method.

Compiled vs. Interpreted Languages

  • Compiled Languages

    • Source code is converted separately into program files.

    • Examples: Java, C, C++, C#, Objective-C, Rust

  • Interpreted Languages

    • Source code is interpreted line-by-line, not converted separately.

    • Can be faster to develop/test, allow for interactive changes.

    • Usually slower to execute.

    • Examples: Python, R, Javascript, SQL

Java Syntax

  • Java relies heavily on specific syntax rules.

  • Every instruction ends with a semi-colon (;).

  • Conditions for if-statements and loops need opening ( and closing ) parentheses.

  • The body of a class, method, loop, conditional, etc. begin with a left curly brace { and end with a right curly brace }.

  • Indentation does not matter (but use tabs to make code easier to read).

  • Opposite of Python where syntax is simplified but indentation is significant.

  • Common mistake: forgetting a ; or }.

Java: Data Typing

  • Java is a strongly typed language.

  • Must define (in advance) what type will be stored in every variable.

  • Cannot change the type during the running of the program.

    • Weakly typed languages (e.g., Python, Javascript) allow changing the type stored in a variable.

  • Three categories of types:

    • Primitives:

      • Whole numbers: int (also byte, short, long)

        • Differ in range of possible values.

      • Decimal numbers: double (also float)

        • Differ in precision (# of decimal places).

      • Single characters: char

      • true or false: boolean

    • Objects: types defined with classes (including String)

    • Arrays: one or more instances of a given type (data collection similar to a List)

  • When possible, can convert between types using casting.

    • Example:
      java double d = 0.0; int i = (int) d; // Becomes the value 0

  • Only need to specify a type when declaring a variable.

  • Can also assign a value at the same time, but not necessary.

    • Example:
      java int first, second; first = 2; second = 3; int sum = 0; sum = first + second; String message = “The sum of is” + sum; // also implicit conversion of sum to a String System.out.println(message);

Java: Operators

  • Basic mathematical operators:

    • + - * / % (modulus)

    • Follow PEMDAS (but no exponentiation operator).

  • Assignment operators:

    • += -= *= /= %=

      • Automatically assign new value to the variable.

      • Example: price += 10 is the same as price = price + 10

    • i++ adds 1 to i and returns the previous value of i

    • ++i adds 1 to i and returns the new value of i

    • Similar for i-- and --i (except they subtract 1)

    • Example:
      java int x = 0; System.out.println(x++); // Prints 0 and adds one to x (so it becomes 1) System.out.println(++x); // Adds 1 to x (so it becomes 2) then prints 2

  • Logical operators:

    • Equals: ==

    • Not equals: !=

    • Also < <= > >=

    • AND: && OR: ||

    • Both short circuit (stop comparing when know the correct answer).

Java: Conditionals

  • else if and else are both optional

    • Can also chain more than one else if

  • Parentheses and brackets are important syntax

    • If no brackets, then only the next line is the body of the conditional

  • Example if statements:

    if (condition) {
        // do something if
        // condition is true
    } else if (condition2) {
        // do something if
        // condition is false and
        // condition2 is true
    } else {
        // do something if
        // condition is false and
        // condition2 is false
    }
    

    Java: Conditionals- Switch

  • switch statement is similar to if else statements
    java switch (variable) { case value1: { // do something 1 break; } case value2: { // do something 2 break; } default: { // do something else break; } }

    • Note: must include break at the end of each case (otherwise next case also runs)

Java: Loops

  • Three parts to defining for loop variables:

    1. Initialize the loop variable (once at the start of the loop).

    2. How long should we keep looping? (checked at the start of each iteration).

    3. Update the loop variable (at the end of each iteration).

    • Example:
      java for (int i = 0; i <= 5; i++) { System.out.println(“i is ” + i); }

  • while loop is same as for loop:

    int i = 0;
    while (i <= 5) {
        System.out.println(“i is ” + i);
        i++;
    }
    
    //is the same as:
    for (int i = 0; i <= 5; i++) {
        System.out.println(“i is ” + i);
    }
    

Java: Functions

  • Function definitions can have four parts:

    1. Visibility [optional, will be discussed in OOP]

    2. Return type [required]

    3. Name [required]

    4. Parameters (inside parentheses) [optional]
      java public int sum(int x, int y) { return x + y; }

  • Special return type: void

    • Function returns nothing and cannot have a return statement

    • Also calling the function cannot be part of an assignment.

    • void functions are like verbs: they only perform actions.

    • Other functions are like nouns: they represent a returned value.

    • Example:
      java public void greetUser(String name) { System.out.println(“Hello, “ + name + “!”); }
      object-oriented programming

Object-Oriented Programming

  • Core idea: create new data types that are models of real-world entities/concepts/ideas relevant to the problem you are solving.

    • Environmental Dashboard: building, energy source

    • Banner Registration: student, course, instructor, classroom

    • Card Game: card, deck, players, game rules

  • Often easier to work with classes than trying to represent all aspects of problems with only primitive types

  • Need to make decision about two aspects of our new data types:

    1. What information do we need to keep track of? What do we need to remember while solving the problem?

    2. What actions can they perform? How do those actions get us closer to a solution?

  • Classes are used to represent each concept/idea/entity

    • Instance variables (attributes) store relevant information

      • Example: suit and rank of an individual card

    • Methods are functions that perform actions for a class

      • Example: shuffling a deck of cards

    • Objects are instances of a class

      • Example: the 3 of clubs vs. the ace of spades are two instances of the Card class

        • Both have a suit and a rank, but the values of those differ
          Public Enumerations

Enumerations

  • Enumerations are special types that allow us to give names to a limited number of options

  • Can be helpful to avoid mistyping Strings
    java public enum Suit = { Club, Diamond, Heart, Spade }

Defining Instance Variables

  • Note: the .java file should match the class name (e.g., Card.java) ```java /**

    • The Card class defines a card object for the {@link GoFish} game.
      *

    • @author CS Professors
      / public class Card { /* The {@link Suit} of the card. / private Suit suit; /* The rank of the card, limited to 2-10. */
      private int rank;
      // more code to follow
      }
      ```

  • Class Description (Javadoc Comment)

  • Defining Instance Variables (Javadoc Comments)

  • Defines the class

Java: Access Modifiers

  • Java allows us to define where variables can be modified using access modifiers:

    • public: A public variable can be modified in any .java file.

    • private: A private variable can be modified only in the class.

    • protected: A protected variable can be modified in any subclasses (and also any .java files in the same package).

    • default (unspecified): Can be modified only by any .java files in the same package.

  • Typically, make all instance variables private so that a class controls when they change values and can be read

    • Initially assigned in a constructor

    • Read in getter methods

    • Changed in setter methods

  • Typically, only constants are made public, and they get the additional terms final (cannot be changed) and static (class variable instead of instance variable)

  • Encapsulation: a class protects its contents so they cannot be modified elsewhere (provides data security)

Access Modifiers - Classes

  • Classes are also defined with an access modifier

    • public: A public class can be instantiated and used in any .java file

    • private: A private (nested) class is only accessible by the class that contains it

    • protected: A protected class can only be instantiated and used in the same package (or by subclasses of a class that contains it)

    • default (unspecified): Can be instantiated and used only by any .java files in the same package

  • Usually we make our classes public, except in special cases

Card Class - Constructor

  • A constructor always has the same name as its class.

  • Note: a constructor is the only function that does not have a return type
    java public class Card { // instance variables defined above /** * Creates a new Card with a given {@link Suit} and rank. * * @param suit The {@link Suit} of the card * @param rank The rank of the card */ public Card(Suit suit, int rank) { // save the instance variables this.suit = suit; this.rank = rank; } // more methods to follow }

  • Method Description (Javadoc Comment)

Access Modifiers - Methods

  • Methods are also defined with an access modifier

    • public: A public method can be called from any .java file

    • private: A private method can be called only in the class

    • protected: A protected method can be called in any subclasses (and also any .java files in the same package)

    • default (unspecified): Can be called only by any .java files in the same package

  • Access modifier of a constructor usually matches the class (almost always public)

Card Class - Methods

```java
public class Card {
    // instance variables and constructor defined above
    /**
     * Gets the {@link Suit} of the card.
     *
     * @return The card's {@link Suit}
     */
    public Suit getSuit() {
        return this.suit;
    }
    /**
     * Gets the rank of the card.
     *
     * @return The card's rank
     */
    public int getRank() {
        return this.rank;
    }
}

public class Deck {
    // instance variables and constructor defined here
    /**
     * Randomly shuffles the deck.
     */
    public void shuffle() {
        Collections.shuffle(this.cards);
    }
}
```

Methods

  • Methods can serve multiple purposes:

    • Perform an action (e.g., shuffle the deck, run one turn of the game)

    • Getters: lookup the value of a private instance variable (e.g., getRank)

    • Setters: modify the value of a private instance variable (e.g., setName)

    • equals: check if two instances of a class are the same or not

    • toString: converts an object to a String
      programming: polymorphism

Polymorphism

  • Java can reuse the same method name if each version has different parameters

  • Allows us to define multiple versions of the same method that need different inputs
    java public Card chooseCard() public Card chooseCard(Card receivedCard) public int updateScore(Card playedCard) public int updateScore(int chipsWon, int originalBet)

  • Question: Will Java allow this code?

Objects: Instances of Classes

  • Classes define what it means to be a data type

  • Objects are instances of classes – single entities of that type

  • Classes vs. instances

    • What it means to be a professor vs. Howard the Professor

  • Instances of a class all have the same instance variables, but different values for those variables

    • 3 of clubs vs. ace of spades

  • We access instance variables and methods using a period: T
    ells Java which instance we want to interact with (to the left of the period) Objects: Instances of Classes ```
    Card card1 = new Card(3, Suit.Club);
    Card card2 = new Card(1, Suit.Spade);
    Deck deck = new Deck();

Suit suit = card1.getSuit(); // Suit.Club
int rank = card2.getRank(); // 1

deck.shuffle();
```

  • We create instances of a class with the new keyword

  • New creates an object and saves its reference in the variable
    Howard and Clark are two different players

Object Usage

```java
Deck deck = new Deck();
Player player1 = new Player(“Howard”);
Player player2 = new Player(“Clark”);


// give everyone cards
player1.drawCards(deck);


player2.drawCards(deck);
// run the first turn
Card playedCard = player1.chooseCard();


player2.receiveCard(playedCard);
```
  • Ask different players to play their turns
    Alice and Bob are two different players
    Memory model

    Memory Model

    public class Card {
        // instance variables defined above
        /**
         *Creates a new Card with a given {@link Suit} and rank.
         *
         *@param suit The {@link Suit} of the card
         *@param rank The rank of the card
         */
        public Card(Suit suit, int rank) {
            // save the instance variables
            this.suit = suit;
            this.rank = rank;
        }
        // more methods to follow
    }
    
  • suit: Club rank: 3

  • : Diamond rank: 7

  • New creates an Object and saves its reference in the variable

  • Initial reference value for an Object is a special value called null

  • Card card3;

  • Assigning an existing Object to a new variable makes both variables point to the same Object in memory (shallow copy)

Checking Equals

```java
Card card1 = new Card(3, Suit.Club);
Card card2 = new Card(3, Suit.Club);


card1 == card2

//false since these refer to two different Objects Card class
return this.suit == otherCard.suit && this.rank == otherCard.rank;
```
*Since the two Objects have the same contents
Let’s say I have a parent class OberlinPerson, and two children classes Student and Faculty. Would it make sense to make the getID() method a static method defined in the parent class?
programming

Object-Oriented Programming: Inheritance

  • In many different real-world applications, we might want to model different types of the same concept/idea/entity

    • Environmental Dashboard: academic buildings and dorm buildings

  • We often have “is a” relationship between types

    • A student “is a” person, a dorm “is a” building

  • Types will have some instance variables and methods in common

  • One class inherits shared properties from another class or interface

  • What are the “is a” relationships between the following gardening entities:

Inheritance

  • One class (child) inherits from another class (parent) Subclasses

  • Superclasses can override the methods of a parent class
    ```java
    public class Tree extends Plant {
    protected Boolean leaves;

    public Tree(double waterNeeded, boolean leaves) {
        this.waterNeeded = waterNeeded;
        this.leaves = leaves;
    }
    
    
    public void shade() {
        System.out.println(“I’ll block the sun!”);
    }
    

    }

    public class Plant {

    Polymorphism

    • The keyword static is an attribute that belongs to the class as a whole, not to the instantiation of the object. * You can have static variables or static methods. * Placeholder for a method that needs to be defined later.