| theme | seriph | |
|---|---|---|
| background | https://source.unsplash.com/1920x1080/?java,programming | |
| class | text-center | |
| highlighter | shiki | |
| lineNumbers | false | |
| info | ## Introduction to Java By Kenneth Kousen Learn more at [KouseniT](https://kousenit.com) | |
| drawings |
|
|
| transition | slide-left | |
| title | Introduction to Java | |
| mdc | true |
Ken Kousen
Kousen IT, Inc.
- Java Basics (90 min)
- Values, Variables, Methods
- String Handling & Math
- Flow Control
- Introduction to OO (60 min)
- Classes & Objects
- Wrapper Types & Arrays
- Object-oriented programming language
- Platform independent ("Write Once, Run Anywhere")
- Strongly typed
- Automatic memory management
- Rich standard library
- Used for enterprise, Android, web backends, and more
graph TD
A[Java Source Code .java] --> B[javac Compiler]
B --> C[Bytecode .class]
C --> D[JVM - Java Virtual Machine]
- Java source code is compiled to bytecode
- Bytecode is platform-independent
- JVM executes bytecode on specific platforms
graph TD
C[Bytecode .class] --> D[JVM - Java Virtual Machine]
D --> E[Operating System]
E --> F[Hardware]
- JVM provides abstraction layer
- Same bytecode runs on different platforms
- "Write Once, Run Anywhere" (WORA)
Starting JShell:
$ jshell
| Welcome to JShell -- Version 17
| For an introduction type: /help intro
jshell>- REPL (Read-Eval-Print Loop)
- Great for learning and experimentation
- No need for class or main method
- Built into Java since version 9
jshell> int x = 10
x ==> 10
jshell> double pi = 3.14159
pi ==> 3.14159
jshell> String message = "Hello, Java!"
message ==> "Hello, Java!"
jshell> boolean isReady = true
isReady ==> true- Type declaration required
- Assignment with
= - Semicolons optional in JShell
| Type | Size | Range |
|---|---|---|
byte |
8 bits | -128 to 127 |
short |
16 bits | -32K to 32K |
int |
32 bits | -2³¹ to 2³¹-1 |
long |
64 bits | -2⁶³ to 2⁶³-1 |
| Type | Size | Range |
|---|---|---|
float |
32 bits | ±3.4×10³⁸ |
double |
64 bits | ±1.7×10³⁰⁸ |
char |
16 bits | Unicode |
boolean |
1 bit* | true/false |
*Size is JVM-dependent
jshell> int add(int a, int b) {
...> return a + b;
...> }
| created method add(int,int)
jshell> add(5, 3)
$2 ==> 8
jshell> double calculateArea(double radius) {
...> return Math.PI * radius * radius;
...> }
| created method calculateArea(double)
jshell> calculateArea(5.0)
$4 ==> 78.53981633974483Try these in JShell:
- Write a function
multiplythat takes two integers and returns their product - Write a function
isEventhat returns true if a number is even - Write a function
celsiusToFahrenheitthat converts temperatures
Time: 10 minutes
jshell> String name = "Java"
name ==> "Java"
jshell> name.length()
$2 ==> 4
jshell> name.toUpperCase()
$3 ==> "JAVA"
jshell> name.toLowerCase()
$4 ==> "java"
jshell> name.charAt(0)
$5 ==> 'J'Strings are immutable - methods return new strings
jshell> String first = "Hello"
first ==> "Hello"
jshell> String second = "World"
second ==> "World"
jshell> first + " " + second
$3 ==> "Hello World"
jshell> String result = first.concat(" ").concat(second)
result ==> "Hello World"
jshell> "Number: " + 42
$5 ==> "Number: 42"jshell> String text = " Hello Java "
jshell> text.trim()
$2 ==> "Hello Java"
jshell> text.contains("Java")
$3 ==> true
jshell> text.replace("Java", "World")
$4 ==> " Hello World "
jshell> "apple,banana,orange".split(",")
$5 ==> String[3] { "apple", "banana", "orange" }jshell> Math.sqrt(16)
$1 ==> 4.0
jshell> Math.pow(2, 8)
$2 ==> 256.0
jshell> Math.max(10, 20)
$3 ==> 20
jshell> Math.random()
$4 ==> 0.7264896551724027
jshell> Math.round(3.7)
$5 ==> 4In JShell, try:
- Create a full name from first and last name variables
- Check if an email contains "@" symbol
- Extract the domain from an email address
- Count the number of words in a sentence
Time: 10 minutes
int age = 18;
if (age >= 18) {
System.out.println("You can vote!");
} else {
System.out.println("Too young to vote.");
}
// Multiple conditions
if (age < 13) {
System.out.println("Child");
} else if (age < 20) {
System.out.println("Teenager");
} else {
System.out.println("Adult");
}| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal to |
> |
Greater than |
< |
Less than |
>= |
Greater than or equal |
<= |
Less than or equal |
Logical operators: && (AND), || (OR), ! (NOT)
// Traditional for loop
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}
// Enhanced for loop (for-each)
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
// Loop with step
for (int i = 0; i <= 10; i += 2) {
System.out.println(i); // 0, 2, 4, 6, 8, 10
}// while loop
int count = 0;
while (count < 5) {
System.out.println("Count: " + count);
count++;
}
// do-while loop
int num = 0;
do {
System.out.println("Number: " + num);
num++;
} while (num < 3);whilechecks condition firstdo-whileexecutes at least once
// break - exit the loop
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
System.out.println(i); // 0, 1, 2, 3, 4
}
// continue - skip to next iteration
for (int i = 0; i < 5; i++) {
if (i == 2) {
continue;
}
System.out.println(i); // 0, 1, 3, 4
}Classic programming exercise:
- Print numbers 1 to 100
- For multiples of 3, print "Fizz"
- For multiples of 5, print "Buzz"
- For multiples of both, print "FizzBuzz"
for (int i = 1; i <= 100; i++) {
// Your code here
}- Objects represent real-world entities
- Classes are blueprints for objects
- Encapsulation: bundling data and methods
- Key concepts:
- State (fields/attributes)
- Behavior (methods)
- Identity (unique instance)
graph TD
A[Database Table: Person] --> B[Column: name VARCHAR]
A --> C[Column: age INTEGER]
A --> D[Column: email VARCHAR]
E[Row 1: 'Alice', 25, 'alice@ex.com']
F[Row 2: 'Bob', 30, 'bob@ex.com']
G[Row 3: 'Charlie', 28, 'charlie@ex.com']
A --> E
A --> F
A --> G
graph TD
H[Java Class: Person] --> I[Field: String name]
H --> J[Field: int age]
H --> K[Field: String email]
H --> L[Method: introduce#40;#41;]
M[Object: Alice, 25, alice@ex.com]
N[Object: Bob, 30, bob@ex.com]
O[Object: Charlie, 28, charlie@ex.com]
H --> M
H --> N
H --> O
- Class = Table Definition: Defines structure and data types
- Object = Table Row: Individual instance with specific values
- Fields = Columns: Data attributes
- Methods = Stored Procedures (analogy breaks here, but adds behavior)
public class Person {
// Fields (state)
String name;
int age;
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method (behavior)
public void introduce() {
System.out.println("Hi, I'm " + name +
" and I'm " + age + " years old.");
}
}jshell> class Car {
...> String make;
...> String model;
...> int year;
...> }
| created class Car
jshell> Car myCar = new Car()
myCar ==> Car@1a2b3c4d
jshell> myCar.make = "Toyota"
$3 ==> "Toyota"
jshell> myCar.model = "Camry"
$4 ==> "Camry"
jshell> myCar.year = 2022
$5 ==> 2022Person person1 = new Person("Alice", 25);
Person person2 = new Person("Bob", 30);
Person person3 = person1; // Reference copy
person3.age = 26;
System.out.println(person1.age); // 26- Variables hold references to objects
- Multiple references can point to same object
- Assignment copies the reference, not the object
String text = null; // No object
// Checking for null
if (text != null) {
System.out.println(text.length());
} else {
System.out.println("text is null");
}
// NullPointerException
String s = null;
s.length(); // Error!Always check for null before using an object
Create these classes in JShell:
BankAccountwith balance and deposit/withdraw methodsRectanglewith width, height, and area calculationStudentwith name, grades array, and average grade method
Time: 15 minutes
| Primitive | Wrapper Class |
|---|---|
int |
Integer |
double |
Double |
boolean |
Boolean |
char |
Character |
| Primitive | Wrapper Class |
|---|---|
long |
Long |
float |
Float |
byte |
Byte |
short |
Short |
Objects that contain primitive values
// Autoboxing - primitive to wrapper
Integer num = 42; // int -> Integer
// Unboxing - wrapper to primitive
int value = num; // Integer -> int
// In collections
List<Integer> numbers = new ArrayList<>();
numbers.add(10); // autoboxing
int first = numbers.get(0); // unboxingAutomatic conversion between primitives and wrappers
// Parsing strings
int num = Integer.parseInt("123");
double d = Double.parseDouble("3.14");
// Converting to strings
String s1 = Integer.toString(42);
String s2 = Double.toString(3.14);
// Min/Max values
System.out.println(Integer.MAX_VALUE); // 2147483647
System.out.println(Integer.MIN_VALUE); // -2147483648
// Comparing
Integer.compare(10, 20); // -1// Declaration and initialization
int[] numbers = new int[5]; // [0, 0, 0, 0, 0]
String[] names = {"Alice", "Bob", "Charlie"};
// Accessing elements
numbers[0] = 10;
System.out.println(names[1]); // "Bob"
// Array length
System.out.println(numbers.length); // 5
// Iterating
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}// Enhanced for loop
int[] scores = {85, 90, 78, 92, 88};
for (int score : scores) {
System.out.println(score);
}
// Finding sum
int sum = 0;
for (int score : scores) {
sum += score;
}
double average = (double) sum / scores.length;
// Array of objects
Person[] people = new Person[3];
people[0] = new Person("Alice", 25);// 2D array (matrix)
int[][] matrix = new int[3][3];
matrix[0][0] = 1;
matrix[0][1] = 2;
// Initialize with values
int[][] grid = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
// Iterate through 2D array
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
System.out.print(grid[i][j] + " ");
}
System.out.println();
}-
Create a
GradeBookclass that:- Stores student names and their grades
- Calculates class average
- Finds highest and lowest grades
-
Create a method that reverses an array
-
Create a tic-tac-toe board using 2D array
Time: 15 minutes
- VS Code for Java development
- Java compilation process
- JVM architecture
- Command-line tools
- Lightweight, fast editor
- Java Extension Pack
- IntelliSense code completion
- Integrated debugging
- Git integration
- Built-in terminal
- Cross-platform & free
- Install VS Code
- Install Extension Pack for Java
- Open folder for your project
- Create project structure:
MyProject/ ├── src/ # Source files ├── bin/ # Compiled classes └── .vscode/ # VS Code settings
Extension Pack includes: Language Support, Debugger, Test Runner, Maven/Gradle
// IntelliSense (Ctrl+Space)
String name = "Java";
name. // Shows all String methods
// Code Actions (Ctrl+.)
// - Generate constructors
// - Generate getters/setters
// - Generate toString(), equals(), hashCode()
// Refactoring (F2 to rename)
// - Rename symbols
// - Extract method/variable/constant
// - Inline variableEditing:
| Shortcut | Action |
|---|---|
Ctrl+Space |
IntelliSense |
Ctrl+. |
Quick fix |
Ctrl+/ |
Toggle comment |
Alt+Shift+Down |
Copy line down |
Ctrl+Shift+K |
Delete line |
F2 |
Rename symbol |
Running & Debugging:
| Shortcut | Action |
|---|---|
F5 |
Start debugging |
Ctrl+F5 |
Run without debug |
Shift+F5 |
Stop debugging |
F9 |
Toggle breakpoint |
Create a new Java project:
- Open VS Code and create a new folder
- Create
Main.javawith main method - Add a
Calculatorclass with basic operations - Use Code Actions (Ctrl+.) to generate constructor
- Set breakpoints (F9) and debug (F5)
Time: 15 minutes
graph LR
A[HelloWorld.java] -->|javac| B[HelloWorld.class]
B -->|java| C[JVM]
C --> D[Execution]
# Compile
javac HelloWorld.java
# Run
java HelloWorldgraph TD
A[Class Loader] --> B[Runtime Data Areas]
B --> C[Method Area]
B --> D[Heap]
B --> E[Stack]
B --> F[PC Registers]
B --> G[Native Method Stack]
H[Execution Engine] --> I[Interpreter]
H --> J[JIT Compiler]
H --> K[Garbage Collector]
- Class Loader: Loads .class files
- Heap: Objects live here
- Stack: Method calls and local variables
- Method Area: Class metadata, constants
- Execution Engine: Runs bytecode
- Garbage Collector: Automatic memory management
# Compile
javac MyClass.java
# Run
java MyClass
# Compile with classpath
javac -cp lib/dependency.jar MyClass.java
# Run with classpath
java -cp .:lib/dependency.jar MyClass
# View bytecode
javap -c MyClass
# JShell
jshell# Memory settings
java -Xms512m -Xmx2g MyApp
# Enable assertions
java -ea MyApp
# System properties
java -Dfile.encoding=UTF-8 MyApp
# Verbose output
java -verbose:gc MyAppCommon options you'll encounter
Using terminal/command prompt:
- Compile and run a simple Java program
- Use
javapto examine bytecode - Run with different heap sizes
- Create a multi-file program and compile
Time: 10 minutes
public class Animal {
protected String name;
public Animal(String name) {
this.name = name;
}
public void eat() {
System.out.println(name + " is eating");
}
}
public class Dog extends Animal {
public Dog(String name) {
super(name); // Call parent constructor
}
public void bark() {
System.out.println(name + " says woof!");
}
}Dog myDog = new Dog("Buddy");
myDog.eat(); // Inherited method
myDog.bark(); // Dog-specific method
// Polymorphism
Animal animal = new Dog("Max");
animal.eat(); // Works
// animal.bark(); // Compile error - not in Animal- Child class inherits parent's members
- Can add new methods/fields
- Can override parent methods
public class Cat extends Animal {
public Cat(String name) {
super(name);
}
@Override
public void eat() {
System.out.println(name + " is eating delicately");
}
public void meow() {
System.out.println(name + " says meow!");
}
}@Override annotation helps catch errors
| Modifier | Class | Package | Subclass | All |
|---|---|---|---|---|
public |
✓ | ✓ | ✓ | ✓ |
protected |
✓ | ✓ | ✓ | ✗ |
| (default) | ✓ | ✓ | ✗ | ✗ |
private |
✓ | ✗ | ✗ | ✗ |
Key Points:
public- Accessible everywhereprotected- Package + subclasses- Default - Package only
private- Class only
Control visibility of classes, methods, and fields
public class BankAccount {
private double balance; // Private field
public BankAccount(double initialBalance) {
this.balance = initialBalance;
}
// Public getter
public double getBalance() {
return balance;
}
// Public method with validation
public void deposit(double amount) {
if (amount > 0) {
balance += amount;
}
}
}public interface Drawable {
void draw(); // Abstract method
// Default method (Java 8+)
default void print() {
System.out.println("Printing...");
}
}
public class Circle implements Drawable {
@Override
public void draw() {
System.out.println("Drawing a circle");
}
}Define contracts that classes must follow
public interface Movable {
void move(int x, int y);
}
public interface Resizable {
void resize(double factor);
}
public class Shape implements Drawable, Movable, Resizable {
@Override
public void draw() { /* implementation */ }
@Override
public void move(int x, int y) { /* implementation */ }
@Override
public void resize(double factor) { /* implementation */ }
}public abstract class Vehicle {
protected String brand;
public Vehicle(String brand) {
this.brand = brand;
}
// Abstract method - must be implemented
public abstract void start();
// Concrete method - can be used as-is
public void stop() {
System.out.println("Vehicle stopped");
}
}Partial implementation + contract
Create a hierarchy:
- Base class
Employeewith name and salary - Subclass
Managerwith team size - Subclass
Developerwith programming language - Interface
PayablewithcalculateBonus()method
Time: 15 minutes
graph TD
A[Collection] --> B[List]
A --> C[Set]
A --> D[Queue]
E[Map]
B --> F[ArrayList]
B --> G[LinkedList]
C --> H[HashSet]
C --> I[TreeSet]
E --> J[HashMap]
E --> K[TreeMap]
// ArrayList - dynamic array
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add(0, "Charlie"); // Insert at index
// Access elements
String first = names.get(0);
names.set(1, "Robert"); // Replace
// Remove
names.remove("Alice");
names.remove(0); // By index
// Iterate
for (String name : names) {
System.out.println(name);
}Lists:
- Ordered collection
- Allow duplicates
- Access by index
- Common:
ArrayList
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Alice"); // Allowed
// [Alice, Bob, Alice]Sets:
- No duplicates
- May or may not be ordered
- No index access
- Common:
HashSet,TreeSet
Set<String> names = new HashSet<>();
names.add("Alice");
names.add("Bob");
names.add("Alice"); // Ignored
// [Alice, Bob] (order not guaranteed)// HashSet - no duplicates, no order
Set<Integer> numbers = new HashSet<>();
numbers.add(5);
numbers.add(3);
numbers.add(5); // Ignored - duplicate
// TreeSet - sorted
Set<String> sortedWords = new TreeSet<>();
sortedWords.add("banana");
sortedWords.add("apple");
sortedWords.add("cherry");
// Stored as: [apple, banana, cherry]
// Check membership
if (numbers.contains(3)) {
System.out.println("Found 3");
}// HashMap - key-value pairs
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);
ages.put("Charlie", 35);
// Access values
Integer aliceAge = ages.get("Alice"); // 25
Integer unknown = ages.get("David"); // null
// Iterate
for (Map.Entry<String, Integer> entry : ages.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
// Check existence
if (ages.containsKey("Bob")) {
System.out.println("Bob's age: " + ages.get("Bob"));
}// List operations
List<Integer> nums = Arrays.asList(3, 1, 4, 1, 5);
Collections.sort(nums); // [1, 1, 3, 4, 5]
Collections.reverse(nums); // [5, 4, 3, 1, 1]
int max = Collections.max(nums); // 5
// Convert array to list
String[] array = {"a", "b", "c"};
List<String> list = Arrays.asList(array);
// List to array
String[] newArray = list.toArray(new String[0]);
// Unmodifiable collections
List<String> immutable = Collections.unmodifiableList(list);Basic Collections:
| Need | Use |
|---|---|
| Ordered, duplicates | ArrayList |
| Fast insert/delete | LinkedList |
| No duplicates | HashSet |
| Sorted, no duplicates | TreeSet |
Advanced Collections:
| Need | Use |
|---|---|
| Key-value pairs | HashMap |
| Sorted key-value | TreeMap |
| Thread-safe list | CopyOnWriteArrayList |
| Thread-safe map | ConcurrentHashMap |
- Create a phone book using HashMap
- Remove duplicates from a list using Set
- Count word frequency in a sentence
- Implement a simple shopping cart
Time: 15 minutes
// Safe map access
Map<String, String> map = new HashMap<>();
String value = map.getOrDefault("key", "default");
// Iterate and remove
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String item = it.next();
if (item.startsWith("remove")) {
it.remove();
}
}
// Collection to stream (Java 8+)
list.stream()
.filter(s -> s.length() > 5)
.forEach(System.out::println);✓ Java syntax and basics
✓ Object-oriented programming
✓ JVM and development tools
✓ Collections framework