Logo/
LogoJava Templates

Made with ScholarlyTurn your own files into documents like this

Shared with you

Java Templates

Unit One

Classes and Objects

  • Classes are blueprints for creating objects, and objects are instances of classes that encapsulate data and behavior.
public class MyClass {
    // Class code goes here
}

Instintiating Objects

  • Instantiating an object refers to creating a new instance of a class using the "new" keyword, which allocates memory for the object and calls its constructor to initialize it.
public class MyClass {
    public static void main(String[] args) {
        MyClass obj = new MyClass(); // Object instantiation
    }
}

Methods

  • Methods in Java are functions defined within a class that perform specific tasks or operations.
public class MyClass {
    public void myMethod() {
        // Method code goes here
    }
}

Methods w/ Parameters

  • Methods with parameters are functions that accept input values (parameters) to process or utilize in their operations.
public class MyClass {
    public void myMethod(int parameter1, String parameter2) {
        // Method code goes here
    }
}

Loops

  • Loops in Java, such as for, while, and do-while loops, are control flow structures that execute a block of code repeatedly based on a condition.
public class MyClass {
    public static void main(String[] args) {
        // Loop code goes here
    }
}

Inheritance

  • Inheritance is a feature of object-oriented programming that allows a class to inherit properties and behaviors from another class.
public class ChildClass extends ParentClass {
    // Child class code goes here
}

Selection Statements

  • Selection statements, like the "if" statement, allow a program to make decisions and execute different blocks of code based on specific conditions.
public class MyClass {
    public static void main(String[] args) {
        // Selection statement code goes here
    }
}

Two-Way Selection Statements

  • Two-way selection statements, such as the "if-else" statement, enable a program to choose between two alternative courses of action based on a condition.
public class MyClass {
    public static void main(String[] args) {
        // Two-way selection statement code goes here
    }
}

Unit Two

Attribute

  • An attribute in Java refers to a data member (or field) of a class, representing the state of the object.
// Attribute declaration template in Java
[access modifier] [data type] [attribute name];

// Example
private String name;

No-Arguement Constructor 

  • You usually use the "this.variable = variable;" inside of these.
  • A no-argument constructor, also known as a default constructor, is a constructor with no parameters.
public class MyClass {
    // No-argument constructor
    public MyClass() {
        // Constructor code here
        this.var1 = var1;
        var2 = 32;
    }
}

Parameterized Constructor

  • You usually use the "this.variable = variable;" inside of these.
  • A parameterized constructor is a constructor with parameters used to initialize the object with specific values at the time of creation.
public class MyClass {
    // Instance variables
    private int myVariable;

    // Parameterized constructor
    public MyClass(int value) {
        // Assign value to instance variable
        myVariable = value;
        
    }
}

The This Keyword

  • The "this" keyword in Java is used to refer to the current instance of the class and is used to differentiate between instance variables and parameters with the same name.
public class MyClass {
    // Instance variables
    private int myVariable;

    // Parameterized constructor
    public MyClass(int myVariable) {
        // Use "this" keyword to refer to the instance variable
        this.myVariable = myVariable;
    }
}

Constructor

  • A constructor is a special type of method that is used to initialize an object's state when it is created.
class Animal {
    String name;

    Animal(String name) {
        this.name = name;
    }

    void sound() {
        System.out.println("The animal makes a sound");
    }
}

class Dog extends Animal {
    String breed;

    Dog(String name, String breed) {
        super(name); // Calling the constructor of the parent class
        this.breed = breed;
    }

    @Override
    void sound() {
        super.sound(); // Calling the sound() method from the parent class
        System.out.println("The dog barks");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog myDog = new Dog("Rex", "Labrador");
        myDog.sound();
    }
}

Variables

  • Variables are used to store data that can be manipulated and referenced within a program.
// Variable declaration and initialization
<datatype> <variableName> = <initialValue>;

// Example:
int age = 25;

Accessor Method 

  • An accessor method, often referred to as a getter method, is used to access the value of an attribute in a class.
// Accessor method
public <datatype> get<VariableName>() {
  return <variableName>;
}

// Example:
public int getAge() {
  return age;
}

Operators and Expressions (math)

  • Operators and expressions are used to perform computations and comparisons in Java, allowing for the manipulation of variables and values.
public class ExpressionExample {
    public static void main(String[] args) {
        // Writing and evaluating expressions using arithmetic operators
        int a = 5;
        int b = 3;
        int result = a + b; // Addition
        System.out.println("Addition result: " + result);

        // Evaluating expressions and data types
        double x = 10.0;
        int y = 3;
        double divisionResult = x / y; // Division
        System.out.println("Division result: " + divisionResult);

        // Compound assignment operators
        int num = 10;
        num += 5; // Equivalent to: num = num + 5
        System.out.println("Compound assignment result: " + num);

        // Mod operator
        int modResult = a % b; // Modulus
        System.out.println("Modulus result: " + modResult);
    }
}

Mutator Method - Setting it up.

  • A mutator method, often referred to as a setter method, is used to modify the value of an attribute in a class.
// Mutator method template
public void setPropertyName(DataType propertyName) {
    this.propertyName = propertyName;
}

// Example of a mutator method
public void setName(String newName) {
    this.name = newName;
}

Mutator Method - Calling it

// Calling a mutator method template
objectName.setPropertyName(propertyValue);

// Example of calling a mutator method
// Creating an instance of the Painter class
Painter alice = new Painter();
alice.setName("John");

Printing Objects using toString()

  • This involves overriding the toString() method in a class to return a string representation of the object's state.
public class MyClass {
    private int field1;
    private String field2;

    // Constructor

    // Getter and Setter methods

    // toString() method
    public String toString() {
        return "MyClass[field1=" + field1 + ", field2=" + field2 + "]"; //Use super.toString() to use the toStrings from the superclass
    }
}

Unit Three

One-Dimensional Array

  • A one-dimensional array is a linear collection of elements of the same type, referenced by a single variable name.
// Declaration and Instantiation
int[] intArray = new int[5];

// Initialization with Values
int[] intArray = {3, 3, 5};

Modifying Elements

  • Modifying elements in a one-dimensional array involves accessing a specific element at a particular index and assigning it a new value.
// assigning a new value to the first element of the array
intArray[0] = 10;

Traversing Arrays w/ For Loops

  • Traversing an array with a for loop enables the sequential access and processing of each element within an array.
for (int i = 0; i < intArray.length; i++) {
    System.out.println(intArray[i]);
}

Preconditions and Postconditions

  • Preconditions are the conditions that must be true before a method is executed, while postconditions are the conditions that must be true after the method has executed.
// Preconditions: the array must not be null
// Postconditions: the array will be sorted in ascending order
public void sortArray(int[] array) {
    // sorting logic
}

Polymorphism

  • Polymorphism allows methods to be called on objects of different classes and have them behave differently based on their implementation. 
// Shape is the superclass
class Shape {
    void draw() {
        System.out.println("Drawing a shape");
    }
}

// Circle is a subclass of Shape
class Circle extends Shape {
    @Override
    void draw() {
        System.out.println("Drawing a circle");
    }
}

Enhanced For Loop

  • An enhanced for loop allows easy traversal of arrays or collections without using an index.
  • You would use this when: 
// iterating over an array using an enhanced for loop
for (int num : intArray) {
    System.out.println(num);
}

Array Algorithms

  • Various algorithms can be applied to arrays, such as search, sort, and manipulation algorithms. An example is the binary search algorithm for searching an element in a sorted array.

Finding Duplicates

  • To find duplicates in an array, you can use a nested for loop to compare each element with every other element in the array and identify duplicates based on the comparison results.

Unit Four

The Theater

  • The Theater class contains static methods such as drawScene, playSound, writeNotes, and loadImage to perform drawing operations, play sounds, write notes, and load images, respectively. The final keyword is used to declare constant fields WIDTH and HEIGHT, while the class utilizes graphical operations through the java.awt and javax.swing packages to display the theater scene.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;

public class Theater {
    private static final int WIDTH = 800;
    private static final int HEIGHT = 600;

    public static void main(String[] args) {
        JFrame frame = new JFrame("Theater");
        Canvas canvas = new Canvas();
        canvas.setSize(WIDTH, HEIGHT);
        frame.add(canvas);
        frame.pack();
        frame.setVisible(true);
        drawScene(canvas);
    }

    private static void drawScene(Canvas canvas) {
        Graphics2D g2d = (Graphics2D) canvas.getBufferStrategy().getDrawGraphics();
        
        // Drawing operations
        // Example operations:
        g2d.setColor(Color.RED);
        g2d.fillRect(100, 100, 50, 50); // Draws a red rectangle
        g2d.setColor(Color.BLUE);
        g2d.fillOval(200, 200, 50, 50); // Draws a blue oval
        // Other drawing operations...

        g2d.dispose();
        canvas.getBufferStrategy().show();
    }

    private static void playSound(String soundPath) {
        // Code for playing sounds
    }

    private static void writeNotes(String notes) {
        // Code for writing notes
    }

    private static BufferedImage loadImage(String imagePath) {
        // Code for loading and returning an image
        return null;
    }
}

Static Variables and Methods

  • Static variables and methods in Java belong to the class rather than instances of the class, with static variables representing shared data and static methods performing operations that are not tied to a specific instance of the class.
// TEMPLATE

public class MyClass {
    // static variable
    public static DataType variableName = value;

    // static method
    public static ReturnType methodName(ParameterType parameter1, ParameterType parameter2) {
        // method code goes here
    }
}

// EXAMPLE

public class Circle {
    // static variable
    public static final double PI = 3.14159;

    // static method
    public static double calculateArea(double radius) {
        return PI * radius * radius;
    }
}

Math Class

  • The Math class in Java provides a collection of static methods for performing common mathematical operations such as calculating square roots (sqrt), powers (pow), and absolute value (abs).
sqrt(34); // square root

pow(3, 4); // power - this would be like 3^4

abs(3); // absolute value

// etc...

Rounding and Casting

  • Rounding involves converting a floating-point number to the nearest integer, while casting involves explicitly converting a value from one data type to another in Java.
public class RoundingAndCastingExample {
    public static void main(String[] args) {
        // Rounding example
        double originalNumber = 7.89;
        long roundedNumber = Math.round(originalNumber); // roundedNumber will be 8

        // Casting example
        double doubleNumber = 7.89;
        int intNumber = (int) doubleNumber; // intNumber will be 7
    }
}
  • variableName = (variableType)(Math.round()*num1) + num2;
  • 0.9 * number1 = max
  • added or subtracted number (num2) is your min
  • Math.random() in Java returns a pseudo-random double value greater than or equal to 0.0 and less than 1.0.
int firstNumber = (int) (Math.random() * 6) + 5; // This will return a number between 11 and 5

int secondNumber = (int)(Math.random() * 10) + 1; // This will generate a number between 11 and 1
    
 int thirdNumber = (int)(Math.random() * 30) - 5; // This will generate a number between -5 and 25
  • The .random() method in Java returns a pseudo-random double value greater than or equal to 0.0 and less than 1.0.
double randomNumber = Math.random(); // Generates a random double value between 0.0 (inclusive) and 1.0 (exclusive)

int firstNumber = (int)(Math.random() * 6) + 5; // Between 5 and 11
    
    
int secondNumber = (int)(Math.random() * 10) + 1; // Between 1 and 11

int thirdNumber = (int)(Math.random() * 30) - 5; // Between -5 and 25

Random

  • Object aliases refer to multiple references to the same object in a program, while equality in Java refers to comparing two values or objects for equivalence.
// ALIASES

String s1 = "Hello";
String s2 = s1; // s2 is an alias for s1

// EQUALITY

int x = 5;
int y = 5;
boolean areEqual = (x == y); // areEqual will be true

// OVERRIDDEN EQUALS

 @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        MyClass myClass = (MyClass) obj;
        return value == myClass.value;
    }

Object Aliases and Equality

  • Nested conditionals refer to the use of conditional statements within other conditional statements, allowing for more complex decision-making within a program.
if (condition1) {
    // Code block for condition1 being true
    if (condition2) {
        // Code block for condition1 and condition2 both being true
    } else {
        // Code block for condition1 being true and condition2 being false
    }
} else {
    // Code block for condition1 being false
}

Nested Conditionals

Ask AI about this page

Answers cite the source. Free account, no credit card.