Basics of Java

Page 1: Basics

  • Foundation concepts that establish the groundwork for programming principles.

Page 2: Lecture 0

  • Introduction to the course and its objectives.

Page 3: Basic Concepts

  • Content Explanation

    • Slides require explanation and context; not self-contained.

    • The ordering of slides may require revisiting for better understanding.

  • High-Level Overview

    • Aimed at giving a broad understanding of concepts.

    • Awareness that programmers often focus on details rather than the grand scheme of things.

  • Scope

    • Not an exhaustive list of necessary knowledge.

Page 4: Hello World Example

  • Java Program Skeleton:

    public class Hello {
        // The source file must be named Hello.java
        public static void main(String[] args) {
            // Required method to run code
            System.out.println("Hello, world"); // displays output
        }
    }

Page 5: Primitive Types and Objects

  • Primitive Types

    • Eight primitive types to memorize:

      • Types: boolean, byte, char, short, int, float, long, double

      • Characteristics:

        • Passed/assigned by value.

        • Cannot be null.

        • Have wrapper classes (objects).

  • Objects

    • Passed/assigned by reference.

    • Comparison using .equals() method.

    • Can be null.

    • Created with new operator.

  • Wrappers for Primitives:

    • Boolean, Byte, Character, Short, Integer, Float, Long, Double.

Page 6: Passing by Value

  • Example Program: Passing by Value

    public class Foo1 {
        static void foo(int n) {  
            n++;  // Local change only
        }
        public static void main(String[] args) {
            int x = 3;  // x is initialized to 3
            foo(x); // Method call does not affect x
            System.out.println(x); // Outputs 3
        }
    }

Page 7: Passing by Reference

  • Example Program: Passing by Reference

    public class Foo2 {
        static void foo(int[] n) {  
            n[0]++;  // Modifies the original array
        }
        public static void main(String[] args) {
            int[] x = new int[]{3};  // Array x[0] is initialized to 3
            foo(x);  // Method affects x by reference
            System.out.println(x[0]);  // Outputs 4
        }
    }

Page 8: Understanding Primitive and Object Equality

  • Example Program:

    public class IntVObj {  
        public static void main(String[] args) {  
            Integer a1 = 3, a2 = 3;  
            int b1 = 5, b2 = 5;  
            System.out.println("a1 == a2: " + (a1 == a2)); // True  
            System.out.println("b1 == b2: " + (b1 == b2)); // True  
            a1 += 124;  // Changes value of a1  
            a2 += 124;  // Changes value of a2  
            System.out.println("a1 == a2: " + (a1 == a2)); // False  
            a1++;  
            a2++;  
            System.out.println("a1 == a2: " + (a1 == a2)); // False!
        }
    }

Page 9: Object Comparison and Equality

  • Example Program:

    public class StrCmp {  
        public static void main(String[] args) {  
            String a1 = "Hello, world.";  
            String a2 = "Hello, ";  
            a2 += "world.";  
            System.out.println("a1 == a2: " + (a1 == a2)); // False!  
            System.out.println("a1 == a2: " + equals(a1, a2));  
        }
    
        // Custom equals method  
        public static boolean equals(Object a, Object b) {  
            if (a == b) return true;  
            if (a == null || b == null) return false;  
            return a.equals(b);  
        }
    }

Page 10: Increment Operators Example

  • Example Program:

    public class PlusPlus {  
        public static void main(String[] args) {  
            int a = 1;  
            System.out.println("a++: " + (a++));  // Outputs 1  
            System.out.println("a: " + a);  // Outputs 2  
            System.out.println("++a: " + (++a));  // Outputs 3  
            System.out.println("a: " + a);  // Outputs 3  
        }
    }

Page 11: Arrays and Array Lists Basics

  • Familiarity with arrays is assumed.

  • Typical Manipulation Pattern:

    • Determine the length of the resulting array.

    • Allocate the result array.

    • Populate the result array.

    • Return the result.

Page 12: Removing Even Numbers from Array

  • Example Program - Remove Even Numbers:

    public class RemoveEven {  
        static int[] removeEven(int[] array) {  
            int numOdd = 0;  
            for (int i = 0; i < array.length; i++)  
                if (array[i] % 2 == 1) numOdd++;  
            int[] result = new int[numOdd];  
            int n = 0;  
            for (int i = 0; i < array.length; i++)  
                if (array[i] % 2 == 1) result[n++] = array[i];  
            return result;  
        }
        public static void main(String[] args) {  
            for (int n : removeEven(new int[]{1, 2, 3, 4, 7, 8, 9, 10, 88, 89, 91}))  
                System.out.println(n);  
        }
    }

Page 13: Arrays vs. ArrayLists

  • List Characteristics

    • Simplicity of List manipulation vs. Arrays.

    • List allocation, filling, and return process.

    • Capability to print ArrayList directly (unlike arrays).

    • Use of methods to manage elements (get, set, add).

    • Determining size using size() method.

  • List Complexity

    • Conversion to Integer type introduces hidden complexities.

Page 14: Removing Even Numbers from ArrayList

  • Example Program - Remove Even from List:

    import java.util.List;  
    import java.util.ArrayList;  
    import java.util.Arrays;  
    public class RemoveEven2 {  
        static List<Integer> removeEven(List<Integer> array) {  
            List<Integer> result = new ArrayList<>();  
            for (int i = 0; i < array.size(); i++)  
                if (array.get(i) % 2 == 1) result.add(array.get(i));  
            return result;  
        }
        public static void main(String[] args) {  
            System.out.println(removeEven(Arrays.asList(new Integer[]{1, 2, 3, 4, 7, 8, 9, 10, 88, 89, 91, 92})));  
        }
    }

Page 15: Class Basics

  • Class Structures

    • Must contain a public static void main method.

    • Includes constructors and fields declarations.

  • Field Declarations:

    • Optional modifiers: public, static, final.

    • Required components: type, name (initial value optional).

Page 16: Method and Constructor Declarations

  • Method Declarations:

    • Optional modifiers: public, final, static.

    • Required components: return type, name, argument list.

  • Constructor Declarations:

    • Optional modifier: public.

    • No return type required.

    • Name must match class name, with an argument list.

Page 17: Static vs. Instance Fields

  • Static Fields:

    • One copy exists globally; accessible without object instance.

  • Instance Fields:

    • Each instance has a distinct value; accessed through the created object.

Page 18: Static vs. Instance Methods

  • Static Methods:

    • Can only access static fields.

    • Do not use this keyword.

    • Invoked from the class.

  • Instance Methods:

    • Can access all fields.

    • Use this keyword for instance fields.

    • Invoked from an instance only.

Page 19: Class Implementation Example

  • Example Program - FirstClass:

    public class FirstClass {  
        int a;  // Instance field  
        static int b;  // Static field  
        static int getB() { return b; }  // Static method  
        public int getA() { return a; }  // Instance method  
        public FirstClass() { a = 3; b = a; }  // Constructor  
        public FirstClass(int a) { this.a = a; b = a; }  // Constructor overload  
        public String toString() { return "FirstClass(" + a + "," + b + ")"; }  
        public static void main(String[] args) {  
            FirstClass fc = new FirstClass(9);  
            System.out.println("fc: " + fc);  
            FirstClass fc2 = new FirstClass();  
            System.out.println("fc: " + fc + ", fc2: " + fc2);  
        }
    }
  • Expected Output:

    • fc: FirstClass(9,9)

    • fc2: FirstClass(3,3)

Page 20: Lecture 1

  • Continuation of concepts in the course.

Page 21: Classes vs. Interfaces

  • Classes:

    • Have fields and method bodies.

    • Can be instantiated and extended.

    • Can implement multiple interfaces.

    • Inherit from java.lang.Object.

  • Interfaces:

    • Only contain static fields and methods without bodies.

    • Cannot be instantiated but can extend multiple interfaces.

Page 22: Class Extension Example

  • Example Program - SecondClass:

    public class SecondClass extends FirstClass {  
        public SecondClass() {}  
        public SecondClass(int a) { super(a); }  
        public SecondClass(int a, int b2) { this(a); b = b2; }  
        public static void main(String[] args) {  
            FirstClass fc = new SecondClass(2, 4);  
            System.out.println("fc: " + fc);  
            SecondClass fc2 = new SecondClass(9, 7);  
            System.out.println("fc: " + fc + " fc2: " + fc2);  
        }
    }
  • Expected Output:

    • fc: FirstClass(2,4)

    • fc2: FirstClass(9,7)

Page 23: Extending a Class Example

  • Example Program - Array4:

    import java.util.ArrayList;  
    public class Array4 extends ArrayList<Integer> {  
        @Override  
        public String toString() {  
            StringBuilder sb = new StringBuilder();  
            sb.append("{");  
            for (int i = 0; i < size(); i++) {  
                if (i % 4 == 0 && i > 0) sb.append("\n ");  
                else if (i > 0) sb.append(", ");  
                sb.append(get(i));  
            }  
            sb.append("}");  
            return sb.toString();  
        }
        public static void main(String[] args) {  
            ArrayList<Integer> a1 = new ArrayList<>();  
            ArrayList<Integer> a2 = new Array4();  
            for (int i = 0; i < 10; i++) {  
                a1.add(i); a2.add(i);  
            }  
            System.out.println(a1);  
            System.out.println(a2);  
        }
    }
  • Expected Output:

    • Standard ArrayList output vs formatted Array4 output.

Page 24: Expected Array Output

  • Example output:

    • Standard ArrayList: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

    • Custom Array4 format:

    {0, 1, 2, 3  
      4, 5, 6, 7  
      8, 9}  

Page 25: Class Implementation Example

  • Example Program - Accum:

    public class Accum {  
        private int value = 0;  // hidden field  
        public Accum() {}  
        public void incr() { value++; }  
        public void twice() { value *= 2; }  
        public int get() { return value; }  
        public String toString() { return "" + value; }  
        @Override  
        public boolean equals(Object o) {  
            if (o instanceof Accum) {  // Safe to cast  
                Accum a = (Accum) o;  // Cast
                return a.value == value;  
            }  
            return false;  
        }
        public static void main(String[] args) {  
            Accum m = new Accum();  
            m.incr(); m.incr(); m.twice();  
            System.out.println("m=" + m);  
            assert m.equals(new Accum()); // Assertion check
        }
    }

Page 26: Instanceof and Casting

  • Key Concepts:

    • instanceof checks safety for casting.

    • Interface allows upcasting (subclass to superclass) but not downcasting without checking.

Page 27: Extended Class Example

  • Example Program - Accum2:

    public class Accum2 extends Accum {  
        public Accum2() {}  
        public Accum2(Accum m) {  
            while (get() < m.get()) incr();  
        }  
        public static void main(String[] args) {  
            Accum m = new Accum2();  
            m.incr(); m.incr(); m.twice();  
            System.out.println("m=" + m);  
            assert m.equals(new Accum2(m)); // Assertion check
        }
    }

Page 28: Interface Example

  • Example Program - ArrayPrinterI:

    public interface ArrayPrinterI {  
        void println(int[] x); // No method body
    }  
  • Program Principles:

    • Separation of concerns is key.

    • Interfaces facilitate distinction between actions and their implementations.

Page 29: ArrayPrinterA Implementation

  • Example Program - ArrayPrinterA:

    public class ArrayPrinterA implements ArrayPrinterI {  
        @Override  
        public void println(int[] x) {  
            for (int n : x)
                System.out.println(n);  
        }
    }

Page 30: ArrayPrinterB Implementation

  • Example Program - ArrayPrinterB:

    public class ArrayPrinterB implements ArrayPrinterI {  
        @Override  
        public void println(int[] x) {  
            System.out.print("{ ");  
            for (int i = 0; i < x.length; i++) {  
                if (i > 0) System.out.print(", ");  
                System.out.print(x[i]);  
            }  
            System.out.println("}");  
        }
    }

Page 31: Putting It All Together

  • Example Program - ArrayPrinter

    public class ArrayPrinter {  
        public static void main(String[] args) {  
            int[] arr = new int[]{1, 1, 2, 3, 5, 8, 13};  
            ArrayPrinterI printer = new ArrayPrinterA();  
            printer.println(arr); // First implementation  
            printer = new ArrayPrinterB();  
            printer.println(arr); // Second implementation  
        }
    }

Page 32: Expected Output

  • Output results when running ArrayPrinter with implementations A and B:

    • First implementation:

      1
      1
      2
      3
      5
      8
      13
    • Second implementation:

      { 1, 1, 2, 3, 5, 8, 13 }

Page 33: Java.lang.Object Class

  • Characteristics of Universal Base Class:

    • Has an empty constructor.

    • Implements equals(), toString(), and hashCode().

Page 34: toString() vs. println()

  • Distinctions:

    • println() outputs to console; toString() returns a string representation.

    • Every object has a toString() method that can be overridden.

Page 35: Using StringBuilder in Object Representation

  • Example Program - Martian:

    public class Martian extends Object {  
        String name;  
        int age;  
        int[] coord_location;  
        public Martian(String n, int a, int[] cloc) {  
            name = n; age = a; coord_location = cloc;  
        }
        public String toString() {  
            StringBuilder sb = new StringBuilder();  
            sb.append("Martian(name=");  
            sb.append(name);  
            sb.append(", loc=");  
            sb.append(age);  
            sb.append(coord_location[0]);  
            sb.append(",");  
            sb.append(coord_location[1]);  
            sb.append(")");  
            return sb.toString();  
        }
        public static void main(String[] args) {  
            System.out.println(new Martian("Steve", 61, new int[]{55, 186}));  
        }
    }

Page 36: Lecture 2

  • Further exploration of Java programming concepts.

Page 37: Key Terminology

  • Accessor:

    • Retrieves object state without modifying it.

  • Mutator:

    • Modifies object state.

  • Polymorphism:

    • Treats different objects uniformly based on their shared interface.

Page 38: Packages in Java

  • Overview of Packages:

    • Acts as a namespace (similar to a zipcode) to categorize classes.

    • To define, use package myclass;.`

  • Importing Classes:

    • Import single class: import java.util.List;

    • Import all classes from a package: import java.util.*;

    • Classes in java.lang are imported by default.

Page 39: Using Packages Example

  • Example Program - Pack:

    package my.package;  // Implicit import of java.lang  
    import java.util.List;  
    import static java.lang.Math.PI;  
    public class Pack {  
        public static void main(String[] args) {  
            List<Integer> li = new java.util.ArrayList<>();  // Use fully qualified name as needed  
            double d = Math.cos(PI * 4);  // Usage of statically imported constant  
        }
    }

Page 40: Anatomy of a Function Call

  • Example Call:

    • System.out.println("Hello, world")

    • Explanation:

      • System is a class.

      • out is a static instance field.

      • println is a method called on out.

Page 41: Function Call with Static Method

  • Example Call:

    • java.lang.Math.sin(3)

    • Explanation:

      • java.lang is the package name.

      • Math is the class name.

      • sin is a static method called from the class.

Page 42: Variable Scope and Automatic Variables

  • Scope Rules:

    • Declarations inside {} only exist within that block.

    • Example Program:

    public class Foo {  
        static int x = 3;  // Static field  
        int y = 4;  // Instance field  
        Foo() {  
            int x = 2;  // Automatic variable  
            {  
                int x = 5;  // Another automatic variable  
            }  
            y = 9;  // Set instance field
        }
    }

Page 43: Privacy Levels

  • Access Modifiers:

    • Public: Accessible by anyone.

    • Private: Only accessible within the class.

    • Package private: Default level, accessible within the package.

    • Protected: Accessible within the class or subclasses.

Page 44: References and Values

  • Example Program - Ref:

    public class Ref {  
        public static void main(String[] args) {  
            {  
                int[] x = new int[]{3, 5};  
                int[] y = x;  // Reference copy  
                y[0]++;  
                System.out.println("" + x[0]);  // Outputs modified value
            }  
            {  
                int x = 3;  
                int y = x;  // Value copy  
                y++;  
                System.out.println("" + x); // Outputs original value
            }
        }
    }

Page 45: String Copy Example

  • Example Program - Ref2:

    public class Ref2 {  
        public static void main(String[] args) {  
            {  
                String x = "hello";  
                String y = x;  
                y += ", world";  
                System.out.println("" + x); // Original value unchanged
            }  
            {  
                String x = "hello";  
                String y = x;  
                StringBuilder sb = new StringBuilder();  
                sb.append(x);  
                sb.append(", world");  
                y = sb.toString();  
                System.out.println("" + x); // Original value unchanged
            }
        }
    }

Page 46: Final Keyword

  • Final Keyword Example Program:

    public class Fin {  
        final static int x = 3;  
        public static void main(String[] args) {  
            //x++; // Not allowed  
            if (x == 9) { do_a_thing(); }  // May be optimized out  
            final int y = 4;  
            // y = 2; // Not allowed  
            final int[] arr = new int[]{5};  
            arr[0]++; // Allowed
        }
    }

Page 47: Implementing String Class

  • Example Program:

    public class Str {  
        private char[] data;  
        public Str() { data = new char[0]; }  
        public Str(char[] in) {  
            data = new char[in.length];  
            for (int i = 0; i < in.length; i++)  
                data[i] = in[i];  
        }
        public Str(Str s) { data = s.data; }  
        public char charAt(int n) { return data[n]; }  
        public int length() { return data.length; }
    }

Page 48: Implementing String Class with Lists

  • Example Program - Str2:

    import java.util.*;  
    public class Str2 {  
        private List<Character> data;  
        public Str2() { data = new ArrayList<Character>(); }  
        public Str2(char[] in) {  
            data = new ArrayList<Character>();  
            for (int i = 0; i < in.length; i++)  
                data.add(in[i]);  
        }
        public Str2(Str2 s) { data = s.data; }  
        public char charAt(int n) { return data.get(n); }  
        public int length() { return data.size(); }
    }

Page 49: Missing Elements in Str

  • Elements Yet to Implement in Str:

    • toString() method.

    • boolean equals(Object o) method implementation.

Page 50: Lecture 3

  • Further course discussions and concepts.