Java Full Course: Beginner to Master with Practical Projects

Java programming course
Beginner to Master Core Java OOP + JDBC + Projects Interactive Quizzes

Complete Java Full Course Notes

This full Java course is designed for students who want to start from zero and become strong in Java programming. It covers installation, basic syntax, object-oriented programming, collections, exception handling, file handling, JDBC, multithreading, Java 8 features, and final projects.

Study Method: Read the explanation, type the code yourself, run it, change it, complete the practical task, and answer the quiz. Java becomes easy when you practice daily.

1. Java Installation and Setup

Programming setup
Beginner Level

What You Need

  • JDK: Java Development Kit
  • Code editor: IntelliJ IDEA, Eclipse, NetBeans, or VS Code
  • Command Prompt or Terminal

Install JDK on Windows

  1. Download and install the latest JDK from Oracle or OpenJDK distribution.
  2. Install it normally.
  3. Set environment variable if needed.
  4. Open Command Prompt and check:
java -version
javac -version

Important Tools

ToolPurpose
javaRuns compiled Java programs
javacCompiles Java source code
JDKDevelopment kit for creating Java programs
JRERuntime environment for running Java programs
JVMVirtual machine that executes bytecode

Compile and Run Java

javac Main.java
java Main

Practical Task

  1. Install JDK.
  2. Install any Java IDE.
  3. Create a file named Main.java.
  4. Compile and run your first program.

Quiz 1

Which command checks the Java compiler version?

2. Introduction to Java

Beginner Level

What is Java?

Java is a high-level, class-based, object-oriented programming language. It is used to create desktop applications, Android apps, enterprise systems, web applications, banking systems, and backend services.

Features of Java

Simple
Java syntax is clean and structured.
Object-Oriented
Java uses classes and objects.
Platform Independent
Write once, run anywhere.
Secure
Java has strong memory and security features.
Robust
Exception handling and garbage collection help build stable apps.
Multithreaded
Java supports running multiple tasks at the same time.

JDK, JRE, JVM

NameExplanation
JDKJava Development Kit. Used by developers to write and compile Java programs.
JREJava Runtime Environment. Used to run Java programs.
JVMJava Virtual Machine. Converts bytecode into machine-level execution.

Question and Answer

Q: Why is Java called platform independent?

A: Java source code is compiled into bytecode. This bytecode can run on any system that has a JVM.

Q: What is bytecode?

A: Bytecode is the intermediate code generated after compiling a Java program.

Quiz 2

Which component executes Java bytecode?

3. First Java Program

Beginner Level

Hello World Program

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello, Java!");
    }
}

Explanation

PartMeaning
public class MainDefines a class named Main
main methodStarting point of Java program
System.out.printlnPrints output and moves to next line
;Ends a statement
Important: If the class is public, the file name must match the class name. Example: public class Main should be saved as Main.java.

Practical Task

Print your personal details.

public class Main {
    public static void main(String[] args) {
        System.out.println("Name: Kumar");
        System.out.println("Age: 20");
        System.out.println("Course: Java");
    }
}

Quiz 3

Which method is the starting point of a Java program?

4. Variables, Data Types, and Input

Coding on laptop
Beginner Level

Variables

A variable is a named memory location used to store data.

int age = 20;
double price = 99.99;
char grade = 'A';
boolean isPassed = true;
String name = "Ravi";

Primitive Data Types

TypeExampleUse
bytebyte x = 10;Small integer
shortshort x = 100;Short integer
intint x = 1000;Whole number
longlong x = 100000L;Large whole number
floatfloat x = 10.5f;Decimal number
doubledouble x = 10.5;Large decimal number
charchar c = 'A';Single character
booleanboolean b = true;true or false

Taking Input Using Scanner

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = input.nextLine();

        System.out.print("Enter your age: ");
        int age = input.nextInt();

        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }
}

Type Casting

int a = 10;
double b = a; // automatic casting

double x = 10.75;
int y = (int) x; // manual casting

System.out.println(b);
System.out.println(y);

Practical Task

Create a program that asks for student name and three marks, then calculates total and average.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Student name: ");
        String name = input.nextLine();

        System.out.print("Mark 1: ");
        int m1 = input.nextInt();

        System.out.print("Mark 2: ");
        int m2 = input.nextInt();

        System.out.print("Mark 3: ");
        int m3 = input.nextInt();

        int total = m1 + m2 + m3;
        double average = total / 3.0;

        System.out.println("Name: " + name);
        System.out.println("Total: " + total);
        System.out.println("Average: " + average);
    }
}

Quiz 4

Which Java type stores true or false?

5. Operators

Beginner Level

Arithmetic Operators

OperatorMeaningExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Remaindera % b

Comparison Operators

int a = 10;
int b = 5;

System.out.println(a == b);
System.out.println(a != b);
System.out.println(a > b);
System.out.println(a <= b);

Logical Operators

int age = 20;
boolean hasId = true;

if (age >= 18 && hasId) {
    System.out.println("Allowed");
}

Assignment Operators

int x = 10;
x += 5;
x -= 2;
x *= 3;
System.out.println(x);

Practical Task

Build a basic calculator.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter number 1: ");
        double a = input.nextDouble();

        System.out.print("Enter number 2: ");
        double b = input.nextDouble();

        System.out.println("Addition: " + (a + b));
        System.out.println("Subtraction: " + (a - b));
        System.out.println("Multiplication: " + (a * b));
        System.out.println("Division: " + (a / b));
    }
}

Quiz 5

Which operator gives remainder?

6. Conditions and Loops

Beginner Level

if Statement

int age = 18;

if (age >= 18) {
    System.out.println("Adult");
}

if else

int marks = 45;

if (marks >= 50) {
    System.out.println("Pass");
} else {
    System.out.println("Fail");
}

else if Ladder

int marks = 78;

if (marks >= 75) {
    System.out.println("A Grade");
} else if (marks >= 65) {
    System.out.println("B Grade");
} else if (marks >= 50) {
    System.out.println("C Grade");
} else {
    System.out.println("Fail");
}

switch

int day = 2;

switch (day) {
    case 1:
        System.out.println("Monday");
        break;
    case 2:
        System.out.println("Tuesday");
        break;
    default:
        System.out.println("Invalid day");
}

for Loop

for (int i = 1; i <= 5; i++) {
    System.out.println(i);
}

while Loop

int i = 1;

while (i <= 5) {
    System.out.println(i);
    i++;
}

do while Loop

int i = 1;

do {
    System.out.println(i);
    i++;
} while (i <= 5);

Practical Task

Create multiplication table.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter number: ");
        int number = input.nextInt();

        for (int i = 1; i <= 12; i++) {
            System.out.println(number + " x " + i + " = " + (number * i));
        }
    }
}

Quiz 6

Which loop runs at least once?

7. Arrays and Strings

Learning programming online
Beginner to Intermediate

Array

An array stores multiple values of the same type.

int[] numbers = {10, 20, 30, 40};

System.out.println(numbers[0]);
System.out.println(numbers.length);

Loop Through Array

int[] marks = {75, 80, 65};

for (int i = 0; i < marks.length; i++) {
    System.out.println(marks[i]);
}

Enhanced for Loop

String[] names = {"Ravi", "Kavi", "Meena"};

for (String name : names) {
    System.out.println(name);
}

Two-Dimensional Array

int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6}
};

System.out.println(matrix[0][1]);

String Basics

String text = "Java Programming";

System.out.println(text.length());
System.out.println(text.toUpperCase());
System.out.println(text.toLowerCase());
System.out.println(text.charAt(0));
System.out.println(text.substring(0, 4));
System.out.println(text.contains("Java"));

StringBuilder

StringBuilder is useful when you need to modify text many times.

StringBuilder sb = new StringBuilder("Java");
sb.append(" Course");
System.out.println(sb);

Practical Task

Find total and average marks using array.

public class Main {
    public static void main(String[] args) {
        int[] marks = {80, 75, 90, 65, 70};
        int total = 0;

        for (int mark : marks) {
            total += mark;
        }

        double average = total / (double) marks.length;

        System.out.println("Total: " + total);
        System.out.println("Average: " + average);
    }
}

Quiz 7

Array index starts from:

8. Methods

Intermediate Level

A method is a block of code that performs a specific task.

Simple Method

public class Main {
    static void greet() {
        System.out.println("Hello Student");
    }

    public static void main(String[] args) {
        greet();
    }
}

Method with Parameters

public class Main {
    static void greet(String name) {
        System.out.println("Hello " + name);
    }

    public static void main(String[] args) {
        greet("Ravi");
    }
}

Method with Return Value

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

    public static void main(String[] args) {
        int result = add(10, 20);
        System.out.println(result);
    }
}

Method Overloading

Method overloading means using the same method name with different parameters.

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

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

    public static void main(String[] args) {
        System.out.println(add(5, 10));
        System.out.println(add(5.5, 10.5));
    }
}

Practical Task

Create methods for add, subtract, multiply, and divide.

public class Main {
    static double add(double a, double b) {
        return a + b;
    }

    static double subtract(double a, double b) {
        return a - b;
    }

    static double multiply(double a, double b) {
        return a * b;
    }

    static double divide(double a, double b) {
        return a / b;
    }

    public static void main(String[] args) {
        System.out.println(add(10, 5));
        System.out.println(subtract(10, 5));
        System.out.println(multiply(10, 5));
        System.out.println(divide(10, 5));
    }
}

Quiz 8

Using same method name with different parameters is called:

9. Object-Oriented Programming

Intermediate Level

OOP Concepts

ConceptMeaning
ClassBlueprint for objects
ObjectReal instance of a class
EncapsulationBinding data and methods together
InheritanceOne class acquiring properties of another class
PolymorphismOne thing behaving in many forms
AbstractionShowing essential details and hiding internal details

Class and Object

class Student {
    String name;
    int age;

    void display() {
        System.out.println(name);
        System.out.println(age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        s1.name = "Ravi";
        s1.age = 20;
        s1.display();
    }
}

Constructor

class Student {
    String name;
    int age;

    Student(String n, int a) {
        name = n;
        age = a;
    }

    void display() {
        System.out.println(name + " " + age);
    }
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student("Kavi", 21);
        s1.display();
    }
}

this Keyword

class Student {
    String name;

    Student(String name) {
        this.name = name;
    }
}

Encapsulation

class BankAccount {
    private double balance;

    public void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
        }
    }

    public double getBalance() {
        return balance;
    }
}

Practical Task

Create a class called Book with title, author, and price.

class Book {
    String title;
    String author;
    double price;

    Book(String title, String author, double price) {
        this.title = title;
        this.author = author;
        this.price = price;
    }

    void display() {
        System.out.println("Title: " + title);
        System.out.println("Author: " + author);
        System.out.println("Price: " + price);
    }
}

public class Main {
    public static void main(String[] args) {
        Book b1 = new Book("Java Basics", "Ravi", 1500);
        b1.display();
    }
}

Quiz 9

Which OOP concept protects data using private variables and public methods?

10. Inheritance, Polymorphism, Abstraction, Interface

Advanced coding
Intermediate to Advanced

Inheritance

class Animal {
    void eat() {
        System.out.println("Animal is eating");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println("Dog is barking");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.eat();
        d.bark();
    }
}

Method Overriding

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

Polymorphism

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Cat extends Animal {
    void sound() {
        System.out.println("Meow");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Bark");
    }
}

public class Main {
    public static void main(String[] args) {
        Animal a;

        a = new Cat();
        a.sound();

        a = new Dog();
        a.sound();
    }
}

Abstract Class

abstract class Shape {
    abstract void draw();

    void message() {
        System.out.println("Drawing shape");
    }
}

class Circle extends Shape {
    void draw() {
        System.out.println("Drawing circle");
    }
}

Interface

interface Payment {
    void pay();
}

class CardPayment implements Payment {
    public void pay() {
        System.out.println("Paid by card");
    }
}

Abstract Class vs Interface

Abstract ClassInterface
Uses extendsUses implements
Can have constructorsCannot be instantiated directly
Can contain abstract and non-abstract methodsUsed to define contracts

Practical Task

Create an interface Vehicle and implement it using Car and Bike.

interface Vehicle {
    void start();
}

class Car implements Vehicle {
    public void start() {
        System.out.println("Car started");
    }
}

class Bike implements Vehicle {
    public void start() {
        System.out.println("Bike started");
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle v1 = new Car();
        Vehicle v2 = new Bike();

        v1.start();
        v2.start();
    }
}

Quiz 10

Which keyword is used to inherit a class?

11. Packages and Access Modifiers

Intermediate Level

Package

A package groups related classes together.

package mypackage;

public class Student {
    public void display() {
        System.out.println("Student class");
    }
}

Import Package

import java.util.Scanner;
import java.util.ArrayList;

Access Modifiers

ModifierAccess Level
publicAccessible from everywhere
privateAccessible only inside the same class
protectedAccessible in same package and subclasses
defaultAccessible only inside same package

Question and Answer

Q: Why use packages?

A: Packages help organize code, avoid class name conflicts, and make projects easier to maintain.

Q: Which modifier is most restrictive?

A: private

Quiz 11

Which modifier allows access only inside the same class?

12. Exception Handling

Intermediate Level

An exception is an error that occurs during program execution. Java uses exception handling to keep programs safe and stable.

try catch

public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }
    }
}

finally

try {
    int[] numbers = {1, 2, 3};
    System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Invalid array index");
} finally {
    System.out.println("Program completed");
}

throw

public class Main {
    static void checkAge(int age) {
        if (age < 18) {
            throw new ArithmeticException("Not eligible");
        } else {
            System.out.println("Eligible");
        }
    }

    public static void main(String[] args) {
        checkAge(16);
    }
}

throws

import java.io.FileReader;
import java.io.IOException;

public class Main {
    static void readFile() throws IOException {
        FileReader file = new FileReader("data.txt");
    }
}

Practical Task

Create safe division program.

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        try {
            System.out.print("Enter first number: ");
            int a = input.nextInt();

            System.out.print("Enter second number: ");
            int b = input.nextInt();

            System.out.println("Answer: " + (a / b));
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero.");
        } catch (Exception e) {
            System.out.println("Invalid input.");
        }
    }
}

Quiz 12

Which block catches exceptions?

13. Collections Framework

Technology board
Advanced Level

The Java Collections Framework provides ready-made data structures like ArrayList, LinkedList, HashSet, HashMap, and Queue.

ArrayList

import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> names = new ArrayList<>();

        names.add("Ravi");
        names.add("Kavi");
        names.add("Meena");

        System.out.println(names.get(0));
        System.out.println(names.size());
    }
}

LinkedList

import java.util.LinkedList;

LinkedList<String> list = new LinkedList<>();
list.add("A");
list.addFirst("Start");
list.addLast("End");

HashSet

import java.util.HashSet;

HashSet<Integer> numbers = new HashSet<>();
numbers.add(10);
numbers.add(20);
numbers.add(10);

System.out.println(numbers);

HashMap

import java.util.HashMap;

HashMap<String, Integer> marks = new HashMap<>();
marks.put("Ravi", 80);
marks.put("Kavi", 90);

System.out.println(marks.get("Ravi"));

Collection Comparison

CollectionUse
ArrayListDynamic list, fast access
LinkedListGood for frequent insert/delete
HashSetStores unique values
HashMapStores key-value pairs

Practical Task

Create a student marks system using HashMap.

import java.util.HashMap;

public class Main {
    public static void main(String[] args) {
        HashMap<String, Integer> students = new HashMap<>();

        students.put("Ravi", 85);
        students.put("Meena", 92);
        students.put("Kavi", 78);

        for (String name : students.keySet()) {
            System.out.println(name + " : " + students.get(name));
        }
    }
}

Quiz 13

Which collection stores key-value pairs?

14. File Handling

Advanced Level

Write File

import java.io.FileWriter;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        try {
            FileWriter writer = new FileWriter("notes.txt");
            writer.write("Java file handling example.");
            writer.close();
            System.out.println("File written successfully.");
        } catch (IOException e) {
            System.out.println("Error occurred.");
        }
    }
}

Read File

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        try {
            File file = new File("notes.txt");
            Scanner reader = new Scanner(file);

            while (reader.hasNextLine()) {
                String line = reader.nextLine();
                System.out.println(line);
            }

            reader.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
    }
}

Practical Task

Save five names into a text file.

import java.io.FileWriter;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        try {
            FileWriter writer = new FileWriter("students.txt");

            for (int i = 1; i <= 5; i++) {
                System.out.print("Enter name " + i + ": ");
                String name = input.nextLine();
                writer.write(name + "\n");
            }

            writer.close();
            System.out.println("Names saved.");
        } catch (Exception e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

Quiz 14

Which class can write text to a file?

15. Generics, Wrapper Classes, Enum

Advanced Level

Wrapper Classes

Wrapper classes convert primitive types into objects.

PrimitiveWrapper
intInteger
doubleDouble
charCharacter
booleanBoolean

Generics

Generics allow classes and methods to work with different data types safely.

class Box<T> {
    T value;

    void setValue(T value) {
        this.value = value;
    }

    T getValue() {
        return value;
    }
}

public class Main {
    public static void main(String[] args) {
        Box<String> box = new Box<>();
        box.setValue("Java");
        System.out.println(box.getValue());
    }
}

Enum

enum Day {
    MONDAY, TUESDAY, WEDNESDAY
}

public class Main {
    public static void main(String[] args) {
        Day today = Day.MONDAY;
        System.out.println(today);
    }
}

Practical Task

Create an enum for order status.

enum OrderStatus {
    PENDING, PROCESSING, COMPLETED, CANCELLED
}

public class Main {
    public static void main(String[] args) {
        OrderStatus status = OrderStatus.PROCESSING;

        switch (status) {
            case PENDING:
                System.out.println("Order pending");
                break;
            case PROCESSING:
                System.out.println("Order processing");
                break;
            case COMPLETED:
                System.out.println("Order completed");
                break;
            case CANCELLED:
                System.out.println("Order cancelled");
                break;
        }
    }
}

Quiz 15

What is the wrapper class for int?

16. Java 8 Features: Lambda and Stream API

Master Level

Lambda Expression

Lambda expressions make code shorter when working with functional interfaces.

interface Greeting {
    void sayHello();
}

public class Main {
    public static void main(String[] args) {
        Greeting g = () -> System.out.println("Hello Java");
        g.sayHello();
    }
}

Lambda with Parameters

interface Add {
    int sum(int a, int b);
}

public class Main {
    public static void main(String[] args) {
        Add add = (a, b) -> a + b;
        System.out.println(add.sum(10, 20));
    }
}

Stream API

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);

        numbers.stream()
               .filter(n -> n % 2 == 0)
               .forEach(n -> System.out.println(n));
    }
}

map and collect

import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> names = Arrays.asList("ravi", "kavi", "meena");

        List<String> upperNames = names.stream()
            .map(name -> name.toUpperCase())
            .collect(Collectors.toList());

        System.out.println(upperNames);
    }
}

Practical Task

Filter marks greater than 75 using Stream API.

import java.util.Arrays;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> marks = Arrays.asList(45, 78, 90, 66, 82);

        marks.stream()
             .filter(mark -> mark > 75)
             .forEach(mark -> System.out.println(mark));
    }
}

Quiz 16

Which symbol is used in lambda expressions?

17. Multithreading

Master Level

Multithreading means running multiple parts of a program at the same time.

Thread Using Thread Class

class MyThread extends Thread {
    public void run() {
        System.out.println("Thread is running");
    }
}

public class Main {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        t1.start();
    }
}

Thread Using Runnable Interface

class MyTask implements Runnable {
    public void run() {
        System.out.println("Task running");
    }
}

public class Main {
    public static void main(String[] args) {
        Thread t1 = new Thread(new MyTask());
        t1.start();
    }
}

sleep

public class Main {
    public static void main(String[] args) {
        try {
            Thread.sleep(1000);
            System.out.println("After 1 second");
        } catch (InterruptedException e) {
            System.out.println(e);
        }
    }
}

synchronized

synchronized helps control access when multiple threads use the same resource.

class Counter {
    int count = 0;

    synchronized void increment() {
        count++;
    }
}

Question and Answer

Q: What is the difference between start() and run()?

A: start() creates a new thread and then calls run(). Calling run() directly executes like a normal method.

Q: Why use multithreading?

A: To improve performance and run tasks concurrently, such as downloading, processing, and UI work.

Quiz 17

Which method starts a new thread?

18. JDBC Database Basics

Database and server
Master Level

JDBC means Java Database Connectivity. It allows Java programs to connect with databases like MySQL, PostgreSQL, Oracle, and SQLite.

JDBC Steps

  1. Import JDBC package.
  2. Load database driver if needed.
  3. Create connection.
  4. Create statement or prepared statement.
  5. Execute query.
  6. Process result.
  7. Close connection.

Basic MySQL Connection Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

public class Main {
    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/school";
        String user = "root";
        String password = "";

        try {
            Connection con = DriverManager.getConnection(url, user, password);
            Statement stmt = con.createStatement();

            String sql = "CREATE TABLE students (id INT, name VARCHAR(100))";
            stmt.executeUpdate(sql);

            System.out.println("Table created successfully");

            con.close();
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Insert Data

String sql = "INSERT INTO students VALUES (1, 'Ravi')";
stmt.executeUpdate(sql);

Read Data

import java.sql.ResultSet;

ResultSet rs = stmt.executeQuery("SELECT * FROM students");

while (rs.next()) {
    System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}

PreparedStatement

import java.sql.PreparedStatement;

String sql = "INSERT INTO students VALUES (?, ?)";
PreparedStatement ps = con.prepareStatement(sql);

ps.setInt(1, 2);
ps.setString(2, "Meena");

ps.executeUpdate();
Note: To run JDBC with MySQL, add MySQL Connector/J library to your project.

Practical Task

Create a database table for students and insert records using Java.

  1. Create database named school.
  2. Create table students.
  3. Insert three students.
  4. Print all students.

Quiz 18

What does JDBC stand for?

19. Final Practical Projects

Project 1

Student Grade Management System

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Student name: ");
        String name = input.nextLine();

        System.out.print("Marks: ");
        int marks = input.nextInt();

        String grade;

        if (marks >= 75) {
            grade = "A";
        } else if (marks >= 65) {
            grade = "B";
        } else if (marks >= 50) {
            grade = "C";
        } else {
            grade = "Fail";
        }

        System.out.println("Name: " + name);
        System.out.println("Grade: " + grade);
    }
}
Project 2

Bank Account System Using OOP

class BankAccount {
    private String owner;
    private double balance;

    BankAccount(String owner, double balance) {
        this.owner = owner;
        this.balance = balance;
    }

    void deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("Deposited: " + amount);
        }
    }

    void withdraw(double amount) {
        if (amount <= balance) {
            balance -= amount;
            System.out.println("Withdrawn: " + amount);
        } else {
            System.out.println("Insufficient balance");
        }
    }

    void showBalance() {
        System.out.println(owner + " Balance: " + balance);
    }
}

public class Main {
    public static void main(String[] args) {
        BankAccount acc = new BankAccount("Ravi", 5000);

        acc.deposit(1000);
        acc.withdraw(2000);
        acc.showBalance();
    }
}
Project 3

Console To-Do List Using ArrayList

import java.util.ArrayList;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        ArrayList<String> tasks = new ArrayList<>();
        Scanner input = new Scanner(System.in);

        while (true) {
            System.out.println("\n1. Add Task");
            System.out.println("2. View Tasks");
            System.out.println("3. Remove Task");
            System.out.println("4. Exit");
            System.out.print("Choose: ");

            int choice = input.nextInt();
            input.nextLine();

            if (choice == 1) {
                System.out.print("Enter task: ");
                tasks.add(input.nextLine());
            } else if (choice == 2) {
                for (int i = 0; i < tasks.size(); i++) {
                    System.out.println((i + 1) + ". " + tasks.get(i));
                }
            } else if (choice == 3) {
                System.out.print("Enter task number: ");
                int index = input.nextInt() - 1;
                if (index >= 0 && index < tasks.size()) {
                    tasks.remove(index);
                }
            } else if (choice == 4) {
                break;
            } else {
                System.out.println("Invalid choice");
            }
        }
    }
}
Project 4

Contact Book Using HashMap

import java.util.HashMap;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        HashMap<String, String> contacts = new HashMap<>();
        Scanner input = new Scanner(System.in);

        while (true) {
            System.out.println("\n1. Add Contact");
            System.out.println("2. Search Contact");
            System.out.println("3. View All Contacts");
            System.out.println("4. Exit");
            System.out.print("Choose: ");

            int choice = input.nextInt();
            input.nextLine();

            if (choice == 1) {
                System.out.print("Name: ");
                String name = input.nextLine();

                System.out.print("Phone: ");
                String phone = input.nextLine();

                contacts.put(name, phone);
            } else if (choice == 2) {
                System.out.print("Search name: ");
                String name = input.nextLine();

                if (contacts.containsKey(name)) {
                    System.out.println("Phone: " + contacts.get(name));
                } else {
                    System.out.println("Contact not found");
                }
            } else if (choice == 3) {
                for (String name : contacts.keySet()) {
                    System.out.println(name + " : " + contacts.get(name));
                }
            } else if (choice == 4) {
                break;
            }
        }
    }
}
Project 5

Mini Library Management System

import java.util.ArrayList;
import java.util.Scanner;

class Book {
    int id;
    String title;
    boolean isIssued;

    Book(int id, String title) {
        this.id = id;
        this.title = title;
        this.isIssued = false;
    }
}

public class Main {
    public static void main(String[] args) {
        ArrayList<Book> books = new ArrayList<>();
        Scanner input = new Scanner(System.in);

        books.add(new Book(1, "Java Basics"));
        books.add(new Book(2, "OOP Concepts"));
        books.add(new Book(3, "Data Structures"));

        while (true) {
            System.out.println("\n1. View Books");
            System.out.println("2. Issue Book");
            System.out.println("3. Return Book");
            System.out.println("4. Exit");
            System.out.print("Choose: ");

            int choice = input.nextInt();

            if (choice == 1) {
                for (Book book : books) {
                    System.out.println(book.id + " - " + book.title + " - " + 
                        (book.isIssued ? "Issued" : "Available"));
                }
            } else if (choice == 2) {
                System.out.print("Enter book id: ");
                int id = input.nextInt();

                for (Book book : books) {
                    if (book.id == id && !book.isIssued) {
                        book.isIssued = true;
                        System.out.println("Book issued");
                    }
                }
            } else if (choice == 3) {
                System.out.print("Enter book id: ");
                int id = input.nextInt();

                for (Book book : books) {
                    if (book.id == id && book.isIssued) {
                        book.isIssued = false;
                        System.out.println("Book returned");
                    }
                }
            } else if (choice == 4) {
                break;
            }
        }
    }
}

Final Project Quiz

Which collection is best for storing contact name and phone number pairs?

20. Exam Questions and Answers

Short Questions

Q1: What is Java?

A: Java is a high-level, object-oriented programming language used to build desktop, mobile, web, and enterprise applications.

Q2: What is JVM?

A: JVM means Java Virtual Machine. It executes Java bytecode.

Q3: What is JDK?

A: JDK means Java Development Kit. It contains tools required to develop Java programs.

Q4: What is a class?

A: A class is a blueprint for creating objects.

Q5: What is an object?

A: An object is an instance of a class.

Q6: What is constructor?

A: A constructor is a special method used to initialize objects. It has the same name as the class.

Q7: What is inheritance?

A: Inheritance allows one class to acquire properties and methods from another class.

Q8: What is polymorphism?

A: Polymorphism means one object or method can behave in different forms.

Q9: What is method overloading?

A: Method overloading means same method name with different parameter lists.

Q10: What is method overriding?

A: Method overriding means a subclass provides its own implementation of a parent class method.

Q11: Difference between abstract class and interface?

A: Abstract class can have abstract and non-abstract methods. Interface defines a contract and is implemented by classes.

Q12: What is exception handling?

A: Exception handling manages runtime errors using try, catch, finally, throw, and throws.

Q13: Difference between ArrayList and array?

A: Array has fixed size. ArrayList has dynamic size.

Q14: What is HashMap?

A: HashMap stores data as key-value pairs.

Q15: What is JDBC?

A: JDBC is Java Database Connectivity. It connects Java programs with databases.

Important Coding Questions for Practice

  1. Write a Java program to check odd or even number.
  2. Write a Java program to find largest of three numbers.
  3. Write a Java program to print multiplication table.
  4. Write a Java program to reverse a string.
  5. Write a Java program to find factorial of a number.
  6. Write a Java program to check prime number.
  7. Write a Java program to sort an array.
  8. Create a Student class and display student details.
  9. Create a BankAccount class using encapsulation.
  10. Create a To-Do app using ArrayList.

Final Exam Quiz

Which concept means hiding internal implementation and showing only essential details?