COS202: Advanced Object-Oriented Programming in Java Study Guide

COS202 Computer Programming II: Course Overview

  • Course Code: COS202
  • Course Title: Computer Programming II
  • Units: 3 Credits (LH 30; PH 45)
  • Course Content Coverage:
    • Advanced Object-Oriented Programming (OOP) including polymorphism, abstract classes, and interfaces.
    • Class hierarchies and program organization using packages and namespaces.
    • Use of API: Iterators/enumerators, List, Stack, and Queue.
    • Algorithms: Searching, sorting, and recursive algorithms.
    • Event-driven programming: Event-handling methods and event propagation.
    • Exception handling and Applications in Graphical User Interface (GUI) programming.
  • Lab Work Focus: Problem-solving and program development, static and dynamic data structures, searching and sorting (iterative and recursive), and GUI programming.
  • Learning Outcomes:
    • Demonstrate principles of good and structured programming.
    • Master string processing, internal searching, sorting, and recursion.
    • Utilize OOP concepts: classes, objects, inheritance, polymorphism, and data abstraction.
    • Apply tools for developing, compiling, interpreting, and debugging programs.
    • Utilize syntax, data objects, operators, flow constructs, Arrays, methods, Exceptions, Applets, and the Abstract Window Toolkit.
  • Reference Textbooks:
    1. Object Oriented Programming and Java by Danny Poo, Derek Kiong, and Swarnalatha Ashok.
    2. Java How To Program (9ed.) by Deitel.
  • Course Developer: Dr. Femi E. Ayo, Olabisi Onabanjo University.

Basic Object-Oriented Programming (OOP) Concepts

  • Definition: OOP is a programming paradigm based on objects (containing data and methods) aimed at incorporating modularity and reusability. It decomposes problems into entities called objects and builds data and methods around them.
  • Characteristics of OOP:
    • Bottom-up approach in program design.
    • Programs organized around objects grouped into classes.
    • Focus on data with methods operating on that data.
    • Interaction between objects through methods.
    • Enhanced abstraction (modeling data and methods together).
    • Better maintainability (less fragile, more comprehensible).
    • Better reusability via class inheritance.
  • OOP Languages: Examples include C++, Java, Smalltalk, Delphi, C#, Perl, Python, Ruby, and PHP.
  • Procedure-Oriented Programming (POP): Problem-solving is viewed as a sequence of tasks/functions. Heavy focus on functions with little attention to data. Examples: COBOL, FORTRAN, PASCAL, and C.

Comparison: POP vs. OOP

FeatureProcedure Oriented Programming (POP)Object-Oriented Programming (OOP)
DivisionProgram is divided into small parts called functions.Program is divided into parts called objects.
FocusFocuses on functions and sequence of actions.Focuses on data rather than procedures (models real world).
ApproachTop-Down approach.Bottom-Up approach.
Access SpecifiersNo access specifiers.Public, Private, Protected etc.
Data MovementData moves freely from function to function.Objects communicate via member functions.
ExpansionAdding new data/functions is difficult.Easy to add new data and functions.
Data AccessUses global data shared by functions.Data is controlled (public or private).
SecurityNo proper data hiding; less secure.Supports data hiding for high security.
OverloadingNot possible.Function and Operator overloading is possible.
ExamplesC, VB, FORTRAN, Pascal.C++, Java, VB.NET, C#.NET, Python.

Benefits of OOP

  • Reusability: Code written by one user can be reused by others without modification.
  • Inheritance: Eliminates redundant code and extends existing classes.
  • Data Hiding: Programmers can hide data and functions within a class to build secure programs.
  • Reduced Complexity: Problems are viewed as a collection of objects responsible for specific tasks.
  • Maintenance: Easy to upgrade and maintain; complexity is manageable.
  • Message Passing: Facilitates easier interfacing with external systems.
  • Modifiability: Changes inside a class do not affect other parts of the program due to public method interfaces.

Java Language Overview and Environment

  • History: Developed at Sun Microsystems in 1991 by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan. Designed to be platform-independent.
  • Paradigm: Based on OOP; derived from C syntax (curly braces {}, variables declared before use).
  • Structure: Java programs start with packages (namespaces), containing classes, which contain methods, variables, and constants.
  • Environment Setup:
    1. Download Java Development Kit (JDK).
    2. Install the JDK (.exe).
    3. Install an Integrated Development Environment (IDE) or text editor.
    4. Files are saved with the .java extension.
    5. The Java Compiler produces Java bytecodes (.class files).
    6. The Java Virtual Machine (JVM) interprets bytecodes into machine language.
  • Popular IDEs/Editors: Notepad, BlueJ, NetBeans (open-source), JCreator, Eclipse, IntelliJ IDEA, and JBuilder.

Java Basic Syntax and Coding Conventions

  • Standard Printing Program:java public class Welcome1 { public static void main(String[] args) { System.out.println("Welcome to Java Programming!"); } }     
  • Comments:
    • Single-line: Starts with // and ends at the line terminal.
    • Multi-line: Starts with /* and ends with */.
    • Javadoc: Starts with /** and ends with */; used for generating HTML documentation (supports tags like @author and @version).
  • Class Declaration: Introduced by the keyword class. By convention, class names use PascalCase (starts with uppercase, e.g., SampleClassName).
  • Identifiers: Series of characters (letters, digits, _, $). Significant rules:
    • Cannot begin with a digit.
    • Cannot contain spaces.
    • Case-sensitive (Value and value are different).
    • Keywords cannot be used as identifiers.
  • Main Method: The entry point for JVM. Signature: public static void main(String[] args). Keyword void denotes no return value.
  • Output: System.out is the standard output object. System.out.println() prints a line and moves the cursor to the next line.
  • Case Sensitivity: Java is strictly case-sensitive.
  • Naming Conventions:
    • Class Names: UpperCase (e.g., MyFirstJavaClass).
    • Method Names: CamelCase starting with lowercase (e.g., myMethodName()).
    • File Name: Must exactly match the class name (including case) with a .java extension.

Java Modifiers and Keywords

  • Access Modifiers: default, public, protected, private.
  • Non-access Modifiers: final, abstract, strictfp.
  • Reserved Keywords: Constants or identifiers cannot use these. Examples include: abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while.

Data Types and Variables

  • Variable Declaration: Named storage with size, layout, and operations determined by type. Syntax: int a = 10, b = 10;, double pi = 3.14159;.
  • Primitive Data Types (8):
    1. Byte: 8-bit signed two’s complement integer.
    2. Short: 16-bit signed two’s complement integer.
    3. Int: 32-bit signed two’s complement integer.
    4. Long: 64-bit signed two’s complement integer.
    5. Float: Single-precision 32-bit IEEE 754.
    6. Double: Double-precision 64-bit IEEE 754.
    7. Boolean: Represents one bit of information.
    8. Char: Single 16-bit Unicode character.
  • Reference/Object Data Types: Created using constructors (e.g., Animal animal = new Animal("giraffe");).
    • Default value is null.
    • Includes class objects and arrays.
  • Kinds of Variables:
    1. Local Variables: Declared in methods/blocks. Created on entry, destroyed on exit. No access modifiers. No default values (must be initialized).
    2. Instance Variables: Declared inside a class but outside methods. Created with new, destroyed with object. Accessible by all class methods. Recommended to be private. Default values: 0 for numbers, false for boolean, null for references.
    3. Class/Static Variables: Declared with static keyword. Only one copy per class. Created at program start, destroyed at program stop. Accessed via ClassName.VariableName.

Operators

  • Arithmetic: +, -, *, /, %, ++, --.
  • Relational: ==, !=, >, <, >=, <=.
  • Logical: &&, ||, !.
  • Bitwise: Operates on bits (&, |, ^, ~).
  • Assignment: =, +=, -=, *=, /=, %=.
  • Misc Operators:
    • Conditional (Ternary): variable x = (expression) ? value if true : value if false;.
    • instanceof: Checks if an object is of a specific type. Example: name instanceof String.

Control Structures

  • Transfer of Control: Non-sequential execution.
  • Sequence Structure: Statements executed in order.
  • Selection Structures:
    • if: Single-selection.
    • if…else: Double-selection.
    • switch: Multiple-selection. Requires break to exit the structure after a case is processed. The default case is optional.
  • Repetition Structures (Loops):
    • while: Tests condition at the start (0 or more executions).
    • do…while: Tests condition at the end (executes at least once).
    • for: Counter-controlled. Format: for(initialization; condition; increment) { body }.
    • Enhanced for: Iterates through arrays without counters. Syntax: for (parameter : arrayName) { ... }.
  • Flow Keywords:
    • break: Immediate exit from a loop or switch.
    • continue: Skips the rest of the loop body and proceeds to the next iteration.

Core Principles of OOP

  1. Encapsulation: Making fields private and providing access through public getters and setters. Acts as a protective barrier/Data Hiding.
  2. Abstraction: Hiding complexity. Uses abstract classes and methods.
    • Abstract Class: Cannot be instantiated; used as a superclass.
    • Abstract Method: Method signature without a body (public abstract void draw();).
  3. Polymorphism: Ability of an object to take many forms (e.g., a Deer is an Animal, and a Vegetarian, and a Deer).
  4. Method Overloading: Multiple methods in a class with the same name but different parameters (number or type).
  5. Inheritance: One object acquires properties of another. Keywords: extends (for classes) and implements (for interfaces).
    • IS-A Relationship: Parent-child relationship.
    • HAS-A Relationship (Aggregation): A class having an entity reference to another class (e.g., an Employee has an Address).
  6. Packages: Grouping of similar classes and interfaces. Removes naming collisions and provides access protection.
    • Compilation: javac -d . FileName.java.
    • Running: java packagename.ClassName.
    • Importing: import pack.* (all classes) or import pack.A (specific class).
  7. Interfaces: A blueprint of a class containing static constants and abstract methods. Achieves full abstraction and multiple inheritance. Fields are public static final by default; methods are public abstract. Marker/Tagged interfaces (e.g., Serializable) have no members.

Exception Handling

  • Definition: Mechanism to handle runtime errors and maintain normal application flow. Errors spawn a "stack trace".
  • Keywords: try, catch, finally, throw, throws.
  • The try-catch-finally Block:
    • try: Encloses code that might throw an exception.
    • catch: Handles specific exceptions.
    • finally: Executes code regardless of whether an exception occurred (used for resource cleanup like closing files).
  • Checked vs. Unchecked Exceptions:
    • Checked: Verified at compile-time (e.g., IOException). Inherit from Exception but not RuntimeException.
    • Unchecked: Verified at runtime (e.g., ArithmeticException, NullPointerException). Inherit from RuntimeException.
    • Errors: Irrecoverable JVM conditions (e.g., OutOfMemoryError).
  • Scenarios:
    • ArithmeticException: Division by zero in integer arithmetic.
    • InputMismatchException: Scanner receiving non-matching data type.
    • NullPointerException: Operation on a null variable.
    • NumberFormatException: Invalid string-to-number conversion.
    • ArrayIndexOutOfBoundsException: Invalid array index access.
  • Throw vs. Throws:
    • throw: Used to explicitly throw an instance of an exception within a method.
    • throws: Declared in a method signature to indicate which exceptions the method might throw.

Arrays

  • Definition: A group of variables (elements) of the same type. Arrays are objects/reference types.
  • Indexing: Zero-indexed (00 to length−1length - 1).
  • Declaration: int[] array = new int[10]; or using an initializer list {32, 27, 64}.
  • Multidimensional Arrays: Represented as arrays of arrays.
    • Creation: int[][] b = new int[3][4];.
    • Ragged Arrays (different row lengths): int[][] b = new int[2][]; b[0] = new int[5]; b[1] = new int[3];.

Input and Output (I/O) Methods

  1. Scanner Class: Part of java.util. Uses nextInt(), nextDouble(). Requires System.in.
  2. BufferedReader Class: Part of java.io. Requires InputStreamReader. Uses readLine() (must be inside try-catch for IOException).
  3. JOptionPane: Part of javax.swing. Uses dialog boxes:
    • showInputDialog("Prompt")
    • showMessageDialog(null, "Message")

Laboratory Exercises and Programming Tasks

  1. Matrix Operations: Accept two matrices and perform addition, subtraction, or multiplication via a switch menu.
  2. Array Statistics: Calculate min, max, range, mode, median, mean, variance, and standard deviation for an input array.
  3. Square Class: Side length variable, constructor, enlargement methods, and area computation.
  4. Random Squares: Sum of areas of 10 randomly sized squares using Math.random().
  5. ASCII Drawing: Functionality for a Square to draw itself using characters (e.g., * or X).
  6. Divisibility Puzzle: Find a 9-digit number d1d2...d9d_1d_2...d_9 where the prefix of length nn is divisible by nn.
  7. Calculator: Design a simple calculator using OOP features.
  8. Min/Max: Read 5 integers and output the largest and smallest.
  9. Multiples: Read 2 integers and check if the first is a multiple of the second via %.
  10. Getters/Setters Logic: Explanation of why access control is important for instance variables.
  11. Employee Class: Name and monthly salary (validated positive). Calculate yearly salary and apply a 10%10\% raise.
  12. Date Class: Month, day, year variables; displayDate method formatted as m/d/y.
  13. Invoice Class: Part number, description, quantity, price. Method getInvoiceAmount. Validate quantity/price (set to 0 if negative).
  14. Integer Division: Explain the loss of fractional parts and how to avoid it (using float/double).
  15. Gross Pay Calculator: Straight time for first 40 hours, then time-and-a-half for excess hours.
  16. Hollow Square: Printing a hollow asterisk square of user-defined size (1−201-20).
  17. Palindrome: Check if a 5-digit integer reads the same forward and backward.
  18. Graphics Drawing: Utilize drawRect and drawOval based on user menu choice.
  19. Pythagorean Triples: Triple-nested loop to find triples for sides up to 500 (a2+b2=c2a^2 + b^2 = c^2).
  20. isMultiple Method: Return true if the second integer is a multiple of the first.
  21. isEven Method: Boolean check for even integers using remainder operator.
  22. Unique Value Array: Read 5 numbers (10−10010-100) and display only non-duplicates.
  23. Quadrilateral Hierarchy: Inheritance chain: Quadrilateral -> Trapezoid -> Parallelogram -> Rectangle -> Square. Using a Point class for coordinates and area computation.