Java Programming Labs

Master Optional for null safety, the modern Date/Time API, and database connectivity with JDBC.

Optional, Date/Time API & JDBC - Module 7

Learn null-safe programming, modern date handling, and database operations.

Lab 19: Optional Class
Advanced
Coding Challenge
Your Task: Master Java's Optional class to write null-safe code and avoid NullPointerException.

Detailed Requirements:
1. Import Optional:
   import java.util.Optional;

2. Create Optional instances:
   • Optional.of(value) - value must not be null
   • Optional.ofNullable(value) - value can be null
   • Optional.empty() - empty Optional

3. Check and retrieve values:
   • isPresent() - returns true if value exists
   • isEmpty() - returns true if no value (Java 11+)
   • get() - gets value (throws if empty)
   • orElse(default) - gets value or default
   • orElseGet(supplier) - lazy default
   • orElseThrow() - throws if empty

4. Transform with functional methods:
   • map(function) - transform value
   • filter(predicate) - conditional check
   • ifPresent(consumer) - execute if present

Expected Output:
--- Optional Basics --- Has value: true Value: Hello Optional! With default: Hello Optional! Empty with default: Default Value --- Optional Methods --- Uppercase: HELLO OPTIONAL! Filtered (length > 5): Optional[Hello Optional!] Filtered (length > 100): Optional.empty --- Practical Example --- Found user: Alice User not found: Unknown User

Requirements Checklist

Import java.util.Optional
Use Optional.of() or Optional.ofNullable()
Use isPresent() to check value
Use orElse() for default value
Use map() to transform value
Use filter() or ifPresent()
Output
// Click "Run Code" to compile and execute
Hints & Tips
• Create: Optional.of(val) or Optional.ofNullable(val)
• Check: opt.isPresent() returns boolean
• Default: opt.orElse("default")
• Transform: opt.map(v -> v.toUpperCase())
• Execute: opt.ifPresent(v -> System.out.println(v))
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 20: Date/Time API (Java 8+)
Advanced
Coding Challenge
Your Task: Master Java's modern Date/Time API (java.time package) for handling dates, times, and durations.

Detailed Requirements:
1. Import java.time classes:
   import java.time.*;
   import java.time.format.*;

2. Core classes:
   • LocalDate - date only (year, month, day)
   • LocalTime - time only (hour, minute, second)
   • LocalDateTime - date and time combined
   • Period - date-based amount (days, months, years)
   • Duration - time-based amount (hours, minutes, seconds)

3. Create and manipulate:
   • LocalDate.now(), LocalDate.of(2024, 1, 15)
   • date.plusDays(10), date.minusMonths(1)
   • date.getDayOfWeek(), date.getMonth()

4. Format and parse:
   • DateTimeFormatter.ofPattern("yyyy-MM-dd")
   • date.format(formatter)
   • LocalDate.parse("2024-01-15", formatter)

Expected Output:
--- LocalDate --- Today: 2024-01-15 Specific date: 2024-12-25 Day of week: WEDNESDAY Plus 30 days: 2024-02-14 --- LocalTime --- Current time: 14:30:00 Specific time: 09:15:30 Plus 2 hours: 16:30:00 --- LocalDateTime --- Now: 2024-01-15T14:30:00 Formatted: 15/01/2024 14:30 --- Period & Duration --- Period between dates: P11M10D Days until Christmas: 345

Requirements Checklist

Import java.time.*
Use LocalDate.now() or LocalDate.of()
Use LocalTime or LocalDateTime
Use plusDays(), minusMonths() etc.
Use DateTimeFormatter for formatting
Use Period or Duration
Output
// Click "Run Code" to compile and execute
Hints & Tips
• Date: LocalDate.now() or LocalDate.of(2024, 1, 15)
• Time: LocalTime.of(14, 30, 0)
• Add: date.plusDays(10), time.plusHours(2)
• Format: DateTimeFormatter.ofPattern("dd/MM/yyyy")
• Period: Period.between(date1, date2)
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below

Lab 21: JDBC Database Connectivity
Expert
Coding Challenge
Your Task: Learn JDBC (Java Database Connectivity) to connect to databases, execute queries, and process results.

Detailed Requirements:
1. Import JDBC classes:
   import java.sql.*;

2. Establish connection:
   • Connection conn = DriverManager.getConnection(url, user, pass);
   • URL format: jdbc:mysql://localhost:3306/dbname

3. Execute queries:
   • Statement stmt = conn.createStatement();
   • ResultSet rs = stmt.executeQuery("SELECT...");
   • int rows = stmt.executeUpdate("INSERT...");

4. Process ResultSet:
   • while (rs.next()) { }
   • rs.getString("column"), rs.getInt("column")

5. Use PreparedStatement for safety:
   • PreparedStatement ps = conn.prepareStatement("SELECT * WHERE id=?");
   • ps.setInt(1, value);

6. Close resources with try-with-resources.

Expected Output:
--- Database Connection --- Connected to database successfully! --- Query Results --- ID: 1, Name: Alice, Email: alice@example.com ID: 2, Name: Bob, Email: bob@example.com ID: 3, Name: Charlie, Email: charlie@example.com --- Insert with PreparedStatement --- Inserted 1 row(s) successfully! --- Update Example --- Updated 1 row(s) Connection closed.

Requirements Checklist

Import java.sql.*
Use DriverManager.getConnection()
Create Statement and execute query
Process ResultSet with next()
Use PreparedStatement with parameters
Handle SQLException in try-catch
Output
// Click "Run Code" to compile and execute
Hints & Tips
• Connect: DriverManager.getConnection(url, user, pass)
• Query: stmt.executeQuery("SELECT...") returns ResultSet
• Update: stmt.executeUpdate("INSERT...") returns row count
• ResultSet: while(rs.next()) { rs.getString("col"); }
• Prepared: ps.setString(1, value) - index starts at 1
Progress: 0/6
Score: 0/100
0%

Lab Results

Review feedback below