[Go to site: main page, start]

0% found this document useful (0 votes)
3 views27 pages

Java Review Notes

The document provides a comprehensive review of Java programming concepts, covering topics such as arrays, classes, encapsulation, inheritance, polymorphism, exception handling, file I/O, and design patterns. It includes code examples and explanations of key principles like method overloading, overriding, and the use of access modifiers. Additionally, it discusses relationships between objects, UML, and resource management in Java.

Uploaded by

aekiveimar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views27 pages

Java Review Notes

The document provides a comprehensive review of Java programming concepts, covering topics such as arrays, classes, encapsulation, inheritance, polymorphism, exception handling, file I/O, and design patterns. It includes code examples and explanations of key principles like method overloading, overriding, and the use of access modifiers. Additionally, it discusses relationships between objects, UML, and resource management in Java.

Uploaded by

aekiveimar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Programming Review Notes

Table of Contents
1. Arrays and Multi-Dimensional Arrays
2. Classes and Objects

3. Encapsulation - Access Modifiers


4. Overriding/Overloading

5. Exception Handling
6. File I/O
7. Inheritance

8. Polymorphism
9. Abstraction

10. Packages
11. Varargs
12. Relationships between Objects

13. UML
14. Javadoc

15. Collections
16. Collections Generics <!-- Placeholder -->

17. Enum <!-- Placeholder -->


18. Testing
19. Git <!-- Placeholder -->

20. Design Patterns


Arrays and Multi-Dimensional Arrays

Multidimensional Arrays
Declaration:

java

int sizerow = 3;
int sizecolumn = 4;
String[][] student = new String[sizerow][sizecolumn];
String[][] student = {{a,b},{c,d},{e,f}};

Method declaration (2D array):

java

public void printName(String[][] name) {


for (int i = 0; i < [Link]; i++) {
for (int j = 0; j < name[i].length; j++) {
[Link](name[i][j] + " ");
}
[Link](); // Move to the next line after printing a row
}
}

[Link] = length of the array "name"

name[i].length = length of the row "i" in array "name"

Common Exceptions in Arrays


1. ArrayIndexOutOfBoundsException: Accessing indexes outside their valid range.
java

int[] array = new int[5]; // Indexes 0-4


int value = array[5]; // Error - index 5 doesn't exist

2. NullPointerException: Accessing arrays that are null.

java

int[] array = null; // Only reference created, no actual array


int value = array[0]; // Error - array doesn't exist

3. NegativeArraySizeException: Creating arrays with a negative size.

java

int[] array = new int[-1]; // Error - can't have negative size

4. ClassCastException: Invalid casting of array types.

java

Object obj = new int[5];


int[][] array = (int[][]) obj; // Error - incompatible casting

5. ArrayStoreException: Assigning incompatible types to an array.

java

Object[] objArray = new String[5]; // Array of strings


objArray[0] = new Integer(5); // Error - can't store Integer in String array

6. Index Out of Bounds for 2D Arrays: Accessing rows or columns outside the defined
boundaries.
java

int[][] twoDArray = new int[3][3];


int value = twoDArray[5][0]; // Error - row 5 doesn't exist

Classes and Objects

Classes
A class is a blueprint from which individual objects are created (a class is a data type of an object
type). In Java, everything is related to classes and objects.

A class does not take any memory.

A class is like a blueprint that specifies functionalities.

A class contains mainly two things: Methods and Data Members.

A class can also be a nested class.

Classes follow OOP principles: inheritance, encapsulation, abstraction, etc.

Types of Class Variables:

1. Local variables
Defined inside methods, constructors, or blocks

Destroyed when the method completes

2. Instance variables
Variables within a class but outside any method

Initialized when the class is instantiated

Accessible from any method, constructor, or block of that class

3. Class variables
Variables declared within a class, outside any method, with the static keyword
Objects
An object is a variable of the type class, a basic component of object-oriented programming.

Creating a Java Object involves three steps:

1. Declaration: Variable declaration with an object type

2. Instantiation: Using the 'new' keyword to create the object

3. Initialization: The 'new' keyword followed by a constructor call

Encapsulation - Access Modifiers


Encapsulation is a way to hide "sensitive" data from external users. It's achieved through:

Declaring class variables/attributes as private


Providing public get (accessors) and set (mutators) methods to access and update private
variables

Access Modifiers
1. Public (everyone has access)
Accessible within class, outside class, within package, outside package

2. Protected (class and subclass access)


Access within same package, and to subclasses even in different packages

3. Default (package access - no explicit modifier)


Accessible only within the same package

4. Private (class-only access)


Only accessible within the same class

Access level from most to least: Public > Protected > Default > Private
Overriding/Overloading

Method Overloading (Compile-time polymorphism)


Multiple methods with the same name but different signatures (parameters) in the same class
Return type can be different, but changing only return type isn't enough

Used to increase code readability

java

static int add(int a, int b) { return a + b; }


static int add(int a, int b, int c) { return a + b + c; }

Method Overriding (Runtime polymorphism)


Method in a derived class has the same name, return type, and parameters as a method in
parent class

The derived class provides specific implementation for method already defined in parent class
java

class Animal {
void eat() {
[Link]("Animal is eating.");
}
}

class Dog extends Animal {


@Override
void eat() {
[Link]("Dog is eating.");
}
}

Key Differences Between Overloading and Overriding


Method Overloading Method Overriding

Compile-time polymorphism Run-time polymorphism

Increases code readability Provides specific implementation of existing method

Occurs within the same class Performed in two classes with inheritance relationship

May not require inheritance Always needs inheritance

Same name, different signatures Same name, same signature

Return type can differ Return type must be same or covariant

Uses static binding Uses dynamic binding

Private/final methods can be overloaded Private/final methods can't be overridden

Argument list must differ Argument list must be same


 

Exception Handling
An exception is an event that disrupts normal program flow, representing conditions or errors that
need handling to prevent crashes.

Types of Exceptions

Checked Exceptions

Compiler forces you to handle these


Typically caused by conditions not under program control

Must handle with try-catch or declare with "throws"


Designed to be handled at runtime

Examples: IOException, SQLException

Unchecked Exceptions

Not forced by compiler to be handled explicitly

Subclasses of RuntimeException

Usually represent programming errors


Examples: NullPointerException, ArithmeticException, IndexOutOfBoundsException

Try-Catch-Finally Block
Try:

Encloses code that might throw an exception


If exception occurs, normal flow interrupts and program searches for matching catch

Catch:

Can have multiple catch blocks for different exception types

JVM matches exception type with catch block


Only first matching catch executes
Best practices:
Catch as close to problem as possible
Place from specific to general

Can rethrow exceptions

Finally (Optional):

Executes whether exception is thrown or not

Executes even if try block exits with return, break, or continue


Typically used to release resources

Won't execute if [Link]() is called

"throw" vs "throws"
throw keyword:

Used to explicitly throw an exception from within a method

Creates and throws an exception object at a specific point


Cannot throw multiple exceptions

Uses syntax like: throw new ArithmeticException("message")

throws keyword:

Used in method signature to declare potential checked exceptions

Doesn't actually throw the exception


Can declare multiple exceptions

Uses syntax like: public void method() throws IOException, SQLException


Java Exceptions Hierarchy
Throwable: Root of exception hierarchy
Error: System errors (not typically caught)

Exception: Base for all exceptions


RuntimeException: Unchecked exceptions

File I/O
A file is a persistent storage location, unlike variables and arrays which are temporary (in-memory).

Types of Files
Text files (.txt): Human-readable characters with delimiters
Binary files: Non-human-readable binary format for complex data

Files and Streams


Java views files as streams of bytes

Operating system provides end-of-file marker

Stream Types:
Byte-based streams: Input/output in byte format (binary files)
Character-based streams: Input/output in character format (text files, Unicode)

I/O Packages
[Link]: Basic input/output classes
[Link]: More advanced classes for files and directories
Path interface: Represents file/directory

DirectoryStream interface: Iterates over directories


Paths class: Static methods to create Path objects
Files class: Static methods for file manipulation

Working with Text Files


Scanner class:

Reads data from text files sequentially

Methods: hasNext(), nextInt(), next(), nextDouble()

Handles: FileNotFoundException, NoSuchElementException

Formatter class:

Writes formatted data to text files


Creates file if doesn't exist, truncates if exists

Handles: SecurityException, NoSuchElementException, FileNotFoundException,


FormatterClosedException

Working with CSV Files


Reading CSV Files:

Use BufferedReader with string manipulation


Alternative: Apache Commons CSV or OpenCSV libraries

Writing CSV Files:

Use FileWriter or BufferedWriter

Ensure proper CSV formatting

Working with Binary Files


Writing to Binary Files:

java

try (FileOutputStream fos = new FileOutputStream(filename)) {


// Writing integer data
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
[Link]([Link](4).putInt(num).array());
}
}

Reading from Binary Files:

java

try (FileInputStream fis = new FileInputStream(filename)) {


byte[] buffer = new byte[4];
while ([Link](buffer) != -1) {
int number = [Link](buffer).getInt();
[Link]("Read number: " + number);
}
}

Resource Management
[Link](int status):

Terminates Java program immediately


Status 0 indicates success, non-zero indicates error

Shuts down entire JVM


May bypass resource closing in try-with-resources
Try-with-resources (Modern):

java

try (Resource resource = new Resource()) {


// Code using resource
} catch (Exception e) {
// Exception handling
}

Automatically closes resources

Resources must implement AutoCloseable

Try-finally (Older):

java

Resource resource = new Resource();


try {
// Code using resource
} finally {
if (resource != null) {
[Link]();
}
}

Requires manual closing

More verbose and error-prone

Object Serialization
Converting an object to a byte sequence (writing) and reconstructing the object (reading).
Serialization: Converting object to bytes (also called marshalling)

Deserialization: Converting bytes back to object (unmarshalling)

Uses ObjectInputStream and ObjectOutputStream classes

Implements ObjectInput and ObjectOutput interfaces

Inheritance
Inheritance allows one class to acquire properties (methods and attributes) of another, organizing
information hierarchically.

Benefits of Inheritance
Code Reusability: Reuse features across classes

Extensibility: Extend functionality easily

Method Overriding: Implement polymorphism

Abstraction: Support for OOP abstraction concept

Implementation

java

class Super {
// Superclass members
}

class Sub extends Super {


// Subclass members + inherited members
}

Reference and Object Types


1. Super var = new Sub:
Reference is Super, object is Sub
Can access only Super members

If Sub overrides methods, Sub versions are called

2. Super var = new Super:


Reference and object both Super

Only Super members accessible

3. Sub var = new Sub:


Reference and object both Sub
All Sub members (including inherited) accessible

If Sub overrides methods, Sub versions are used

4. Sub var = new Super:


INVALID: Cannot assign Super to Sub reference without explicit casting

Superclass doesn't have subclass properties

The super Keyword


Used to differentiate superclass members from subclass members with same names

Used to invoke superclass constructor from subclass


java

class Superclass {
Superclass(int param) { /* Constructor code */ }
}

class Subclass extends Superclass {


Subclass(int param) {
super(param); // Call superclass constructor
}
}

Types of Relationships
IS-A Relationship: Inheritance hierarchy (Dog IS-A Animal)
HAS-A Relationship: Composition (Car HAS-A Engine)

Types of Inheritance
Single: Class extends one class
Multilevel: Class extends a class which extends another class
Hierarchical: Multiple classes extend one class

Java doesn't support Multiple and Hybrid inheritance directly

Polymorphism
Two types of polymorphism in Java:

1. Compile-Time Polymorphism (Static)


Implemented by method overloading
Resolved during compilation
2. Run-Time Polymorphism (Dynamic)
Implemented by method overriding

Resolved during execution

Abstraction
Hiding implementation details from the user, providing only functionality. Achieved through
Abstract classes and Interfaces.

Abstract Classes
A class that cannot be instantiated directly and is intended to be subclassed.

java

abstract class Animal {


// Abstract method - no body
abstract void makeSound();

// Concrete method
void breathe() {
[Link]("Breathing...");
}
}

Declared with abstract keyword

May contain abstract methods (must be implemented by subclasses)

If a class has at least one abstract method, it must be abstract


Cannot be instantiated, must be inherited

Subclasses must implement all abstract methods


Interfaces

A completely abstract class containing only abstract methods.

java

interface Animal {
void eat();
void travel();
}

Characteristics:

Implicitly abstract (no need for abstract keyword)


Methods implicitly public and abstract

Fields are implicitly public, static, and final


Cannot be instantiated

No constructors

Classes implement interfaces (using implements keyword)

An interface can extend multiple interfaces

Rules for implementing interfaces:

Must declare same exceptions as interface method (or subclasses)


Must maintain same signature and return type (or subtype)

Implementation class can be abstract


A class can implement multiple interfaces

A class can extend only one class but implement many interfaces

Packages
Packages group related types (classes, interfaces, enumerations, and annotations) to prevent
naming conflicts and control access.

Types of Packages:

Built-in: [Link], [Link], [Link], etc.

User-defined: Custom packages to group related classes

Package statement should be the first line in source file. Creates a new namespace to prevent
conflicts.

Varargs
Varargs (variable arguments) allows a method to accept variable number of arguments.

java

public void myMethod(int... numbers) {


for(int num : numbers) {
[Link](num);
}
}

Key points:

Uses ... syntax in method parameters

Can be treated as an array inside method


Simplifies creation of methods needing variable arguments

Can be used only in the final argument position


Without varargs, would need to use overloaded methods or arrays
Relationships between Objects

Association
General connection between classes
Independent lifetimes

Deleting one object doesn't affect others

Symbol: Arrow

Example: Teacher associated with multiple students

Aggregation (has-a)
Part-whole relationship with weaker coupling

Parts can exist independently

Symbol: Empty diamond at one end


Example: Car has a wheel, wheel can exist independently

Composition (part-of)
Stronger form of aggregation
Parts tightly coupled to whole
Parts cannot exist independently

Symbol: Filled diamond at one end

Example: File in folder, deleting folder removes files


Relationship Lifetime Dependency Example

Association Independent Teacher and Student

Aggregation Parts can exist independently Library and Books

Composition Parts cannot exist independently House and Rooms


 

UML
Unified Modeling Language (UML) is a standard visualization tool for system design.

Use of UML:

As a sketch: Communicate aspects of system (whiteboard/paper)


As a blueprint: Complete design for implementation
As a programming language: Auto-generate code structure

Class Diagram Structure


Top compartment: Class name (centered, bold)
Middle compartment: Attributes, properties, variables

Bottom compartment: Methods

Access Level Modifiers:

public: +

protected: #
package protected: ~

private: -

Multiplicity:

0..1: No instances or one instance (optional)


1 or 1..1: One and only one

1..n: One to specific limit

1..*: One or more


0..*: Zero or more

*: Zero or more

0..n: Zero to specific limit

Javadoc
[Placeholder for Javadoc information]

Collections
Java Collections Framework provides classes and interfaces to store and manipulate groups of
objects.

List Interface
Represents an ordered collection that can contain duplicates
Maintains element order
Allows duplicates

Elements accessed by index

ArrayList
A resizable array implementation of the List interface.

Characteristics:

Dynamic resizing (grows/shrinks automatically)

Ordered collection (maintains insertion order)


Allows duplicates
Fast random access by index

Implements List interface

Basic Methods:

Adding: add(E e) , add(int index, E element)

Removing: remove(Object o) , remove(int index)

Accessing: get(int index) , size()

Iterating through ArrayList:

java

// Using for loop


for (int i = 0; i < [Link](); i++) {
[Link]([Link](i));
}

// Using enhanced for-loop


for (String item : list) {
[Link](item);
}

// Using while loop


int index = 0;
while (index < [Link]()) {
[Link]([Link](index));
index++;
}

Collections Generics
[Placeholder for Collections Generics information]

Enum
[Placeholder for Enum information]

Testing

JUnit Test Cases


[More information needed]

Git
[Placeholder for Git information]

Design Patterns
设计模式是解决软件设计中常见问题的可重用解决方案。参见PPT第3-7页的基本定义和概念。

设计模式的关键特性(PPT第3-4页)
它们是与编程语言无关的策略
使代码更灵活、可重用和可维护

提供通过集体经验建立的最佳实践解决方案
帮助开发人员避免重复他人犯过的错误

设计模式的四个基本要素(PPT第5页)
1. 模式名称 - 标识模式
2. 问题 - 描述何时应用该模式(解释问题和上下文)
3. 解决方案 - 构成设计的元素、关系、责任和协作
4. 后果 - 使用模式的结果和权衡(空间/时间权衡、重用、灵活性、可扩展性、可移植性)

设计模式类型(PPT第7页)
1. 创建型模式:专注于对象创建机制
例如:单例、工厂方法、抽象工厂、建造者、原型

2. 结构型模式:处理类和对象的组成/结构
例如:适配器、桥接、组合、装饰器、外观、享元、代理

3. 行为型模式:描述类或对象交互和分配责任的方式
例如:观察者、策略、命令、模板方法、迭代器、中介者、状态

常见设计模式(五种重要模式)

1. 单例模式(创建型)- PPT第15-19页

目的:确保类只有一个实例,并提供对该实例的全局访问点。

使用场景:

当需要确保系统中只存在类的一个实例时
需要一个全局访问点时

例子:

Web应用中的会话控制器
数据库连接管理器

分配IP地址的应用程序

2. 工厂模式(创建型)- PPT第13-14页

目的:创建对象而不暴露创建逻辑,通过公共接口引用新创建的对象。
使用场景:

当类无法预期它必须创建的对象类型时

当类希望其子类指定它创建的对象时

3. 装饰器模式(结构型)- PPT第20-21页

也称为:包装器

目的:动态地向对象添加额外的职责,为扩展功能提供了比子类化更灵活的替代方案。

使用场景:

希望在不影响其他对象的情况下动态地向对象添加职责

通过子类化扩展功能不切实际时

4. 外观模式(结构型)- PPT第22页

目的:为子系统中的一组接口提供统一的接口,外观定义了更高级别的接口,使子系统更易于使
用。

使用场景:

希望为复杂子系统提供简单接口时

客户端和实现类之间存在许多依赖关系时

5. 观察者模式(行为型)- PPT第23页

目的:定义对象之间的一对多依赖关系,使得当一个对象改变状态时,所有依赖它的对象都会得到
通知并自动更新。

使用场景:

当一个对象的改变需要改变其他对象,且不知道有多少对象需要改变时
当一个对象应该能够通知其他对象而不知道这些对象是谁时

6. MVC模式(架构模式)- PPT第24-32页

目的:将应用程序分为三个主要组件:模型、视图和控制器。

组件:

模型:处理应用程序的数据和业务逻辑

视图:处理用户将看到的信息的显示
控制器:处理应用程序逻辑和行为的控制,定义用户界面如何响应用户输入

You might also like