Java Fundamentals
Java Fundamentals
Introduction
- IntelliJ Community Edition
- Java 17 or later
- IntellJ > Download JDK
- GitHub repo
Conditions and Loops
Java Basic Exercise
Gross Pay Calculator
1 | public class GrossPayCalculator { |
If Statement
Salary Calculator
1 | /** |
If-Else Statement
Quota Calculator
1 | /** |
Nested If Statement
Test Results
1 | public class TestResults { |
Switch Expression
Switch Expression
1 | public class GradeMessage { |
Operators
- Relational Operators
Operator | Description | Example |
---|---|---|
> | Greater than | 2 > 1 -> true |
>= | Greater than or equal to | 2 >= 2 -> true |
< | Less than | 1 < 2 -> true |
<= | Less than or equal to | 1 <= 1 -> true |
== | Equal to | 1 == 1 -> true |
!= | Not equal to | 1 != 2 -> true |
- Logical Operators
Symbol | Operator | Example |
---|---|---|
&& | AND | true && true -> true |
|| | OR | true || false -> true |
! | NOT | !true -> false |
While Loops
While Loop
1 | public class InputValidation { |
Do-While Loops
Do-While Loop
1 | public class AddNumbers { |
For Loops
For Loop
1 | public class Cashier { |
Methods, Objects and Data Types
Methods
Methods
1 | public class GreetUser { |
Method Overloading
Method Overloading
1 | public class AreaCalculator { |
Variable Scope
Variable Scope
1 | public class InstantCreditCheck { |
Objects and Encapsulation
- Encapsulation
- All data and behaviors is contained within the object itself.
- Expose behavior and restrict direct access to data.
Encapsulation
1 | public class Rectangle { |
Constructors
Constructors
1 | public class Rectangle { |
Instantiating Objects
Instantiating Objects
1 | public class HomeAreaCalculator { |
Sending and Receiving Objects
Sending and Receiving Objects
1 | public class HomeAreaCalculatorRedo { |
Records and Wrapper Classes
Records and Wrapper Classes
1 | public record Person(String name, int age) { |
1 | public class WrapperClasses { |
Primitive Type | Wrapper Class |
---|---|
byte | Byte |
int | Integer |
double | Double |
float | Float |
char | Character |
boolean | Boolean |
long | Long |
short | Short |
Arrays and Text Processing
Arrays
1 | int[] numbers = new int[5]; |
Random Number Array
Random Number Array
1 | public class LotteryTicket { |
Strings
Strings
1 | public class WordCount { |
StringBuilder
StringBuilder
1 | public class BackwardsString { |
Jumbled String
Jumbled String
1 | public class JumbledString { |
Text Blocks
1 | public class TextBlocks { |
Inheritance
Inheritance
Inheritance
1 | public class Person { |
Overriding Parameters
Overriding Parameters
1 | public class Square extends Rectangle { |
Overloading Methods
Overloading Methods
1 | public class Parent { |
Chain of Inheritance
Chain of Inheritance
1 | public class Human { |
Limited Access and Access Modifier
- Limited Access in Inheritance. > 继承中的有限访问。
- constructors are not inherited. > 构造函数不会被继承。
- public and protected members are inherited. > 公共和受保护的成员被继承。
- private members are not inherited. > 私有成员不会被继承。
- final members are inherited but cannot be overridden. > 继承最终成员,但不能被覆盖。
Sealed Classes
- classes that restrict inheritance to specific classes. > 限制继承到特定类的类。
1 | public sealed class Shape permits Rectangle, Circle { } |
- Sealed classes
- sealed classes grant inheritance permission. > 密封类授予继承权限。
- permitted subclass must extend sealed class. > 允许的子类必须扩展密封类。
- permitted subclass must be sealed/non-sealed or final. > 允许的子类必须是密封/非密封或最终的。
Polymorphism & Abstraction
Polymorphism
Polymorphism
1 | public class Animal { |
Type Casting
1 | Animal animal = new Dog(); |
instanceof Operator
1 | Animal animal = new Dog(); |
instanceof Pattern Matching
1 | Animal animal = new Dog(); |
Abstraction
Abstraction
1 | public abstract class Animal { |
- Abstraction
- abstract classes and methods are templates. > 抽象类和方法是模板。
- declare using abstract reserved word. > 使用 abstract 保留字声明。
- subclasses must implement abstract methods. > 子类必须实现抽象方法。
- abstract classes cannot be instantiated. > 抽象类不能被实例化。
Interfaces
- a stateless construct with abstract behaviors. > 一个没有状态的结构,具有抽象的行为。
Interfaces
1 | public interface Animal { |
Multiple Inheritance
- classes can implement multiple interfaces to achieve multiple inheritance. > 类可以实现多个接口以实现多重继承。
1 | public interface Animal { |
Default Methods
1 | public interface Animal { |
Static methods
- interface methods that contain implementation but are not inherited by implementing classes. > 接口方法包含实现但不被实现类继承。
Interfaces
- cannot be instantiated. > 不能被实例化。
- implemented by classes, extended by other interfaces. > 由类实现,由其他接口扩展。
- implementing non-abstract class must implement all abstract methods. > 实现非抽象类必须实现所有抽象方法。
- methods are public and abstract by default. > 方法默认为 public 和 abstract。
- default and static methods allowed. > 允许默认和静态方法。
Data Structures
Set
Collections Framework
- unified architecture that provides data structures and algorithms to manipulate them. > 统一的架构,提供数据结构和算法来操作它们。
Common Collections
- Set
- List
- Queue
- Map
Set
- unordered collections of unique objects
1 | Set<String> set = new HashSet<>(); |
List
- List
- ordered elements allowing duplicates
- accessible by position
1 | List<String> list = new ArrayList<>(); |
Queue
- Queue
- ordered elements allowing duplicates
- accessible by position
- FIFO
1 | Queue<String> queue = new LinkedList<String>(); |
Map
- Map
- unique key-value pairs
- unordered
1 | Map<String, String> map = new HashMap<String, String>(); |
Collection Iterators
- Iterators
- allow looping over collections
- hasNext() and next() methods
1 | List<String> list = new ArrayList<>(); |
Access to Iterator
- Set
- List
- Queue
EntrySet
- Map
1 | Map<String, String> map = new HashMap<String, String>(); |
Iterating with Enhanced For Loop
1 | for(Map.Entry<String, String> entry : map.entrySet()) { |
Iterating with forEach()
1 | map.forEach((k, v) -> System.out.println(k + " : " + v)); |
Functional Interfaces and Streams
Functional Interfaces
- Functional Interfaces
- single abstract method
- used as assignment targets for lambda expressions or method references
- java.util.function
1 | List countries = List.of("USA", "China"); |
1 | Consumer<String> print = c -> System.out.println(c); |
Interface | Description | Abstract Method |
---|---|---|
Consumer | accepts single argument, returns no result | void accept(T t) |
Supplier | no argument, returns a result | T get() |
Predicate | single argument, returns boolean | boolean test(T t) |
Function | single argument, returns a result | R apply(T t) |
UnaryOperator | single argument, returns a result | R apply(T t) |
BinaryOperator | two arguments, returns a result | R apply(T t, U u) |
1 |
|
1 | Function<Integer, Integer> add = x -> x + 1; |
1 |
|
Streams
- Streams
- sequence of elements supporting sequential and parallel aggregate operations
- java.util.stream
- lazy evaluation
1 | int[] numbers = {1, 2, 3, 4, 5, 6}; |
1 | int[] numbers = {1, 2, 3, 4, 5, 6}; |
- Stream operations
- Intermediate
- Performs operation and return result stream
- Terminal
- return a result and close the stream
- Intermediate
anyMatch, allMatch and filter
1 | List<String> countries = List.of("USA", "China", "France", "Germany", "Japan"); |
1 | Map<String, String> map = new HashMap<String, String>(); |
map and reduce
1 | List<String> countries = List.of("USA", "China", "France", "Germany", "Japan"); |
1 | List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6); |
1 | List<Integer> numbers = List.of(1, 2, 3, 4, 5, 6); |
collect
1 | List<String> countries = List.of("USA", "China", "France", "Germany", "Japan"); |
Exceptions
Handling Exceptions
1 | // ArrayIndexOutOfBoundsException |
Create a file
1 | public class CreateFile { |
Checked and Unchecked Exceptions
- Checked Exceptions
- Exceptions that are checked at compile time
1 | public boolean createNewFile() throws IOException { |
- Unchecked Exceptions
- Exceptions that are checked at runtime
1 | public double nextDouble() { |
- Checked vs Unchecked Exceptions
- Checked Exceptions
- used when there’s a possibility of recovery
- Unchecked Exceptions
- used when there’s not anything that can be done in the event of the error
- Checked Exceptions
Handling Multiple Exceptions
Polymorphism
Multiple catch blocks
Catch multiple in single block
Polymorphism
1 | // Class ArrayIndexOutOfBoundsException |
- Multiple catch blocks
1 | public class MultipleCatchBlocks { |
- Catch multiple in single block
1 | public class CatchMultipleErrorInSingleBlock { |
Closing the File Reader in Finally Block
1 | public class ClosingFileReader { |
1 | public class ClosingFileReaderAutomatically { |
Print to File
1 | public class PrintToFile { |
Throwing Exceptions
1 | public class ThrowingExceptions { |
1 | public class NegativeInputException extends Exception { |
Re-throwing Exceptions
1 | public class RethrowingExceptions { |