Java Programming - Complete Guide (Basics to Advanced)
Java Programming - Complete Guide (Basics to Advanced)
I'll guide you step by step from Java Basics to Advanced, covering all concepts, definitions, examples, coding, and references.
Java Programming - Complete Guide (Basics to Advanced)
1. Introduction to Java
Concept & Definition:
- Java is a high-level, object-oriented programming language developed by Sun Microsystems (now owned by Oracle).
- It is platform-independent, meaning code written once can run on multiple platforms using the JVM (Java Virtual Machine).
- Java follows the Write Once, Run Anywhere (WORA) principle.
Example Code:
// First Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!"); // Prints output
}
}
Reference:
- JDK (Java Development Kit): Required for compiling and running Java programs.
- IDE (Integrated Development Environment): Use Eclipse, IntelliJ IDEA, or VS Code.
- Compiler:
javac
(Java Compiler) - Runtime Environment:
java
(JVM)
Introduction to Java – A Detailed Discussion
Java is one of the most popular programming languages, widely used for web development, mobile applications, enterprise software, and cloud computing. In this discussion, we'll cover everything about Java, including its features, advantages, history, and basic structure.
1. What is Java?
Definition:
Java is a high-level, object-oriented, and platform-independent programming language developed by Sun Microsystems (now owned by Oracle).
It follows the "Write Once, Run Anywhere" (WORA) principle, meaning Java code can run on different platforms without modification.
Key Features of Java:
✅ Object-Oriented: Uses concepts like Classes, Objects, Inheritance, and Polymorphism.
✅ Platform-Independent: Runs on multiple OS like Windows, Mac, and Linux using the Java Virtual Machine (JVM).
✅ Robust & Secure: Provides features like exception handling and memory management (Garbage Collection).
✅ Multithreaded: Supports concurrent programming for better performance.
✅ Distributed & Scalable: Used in web applications, cloud computing, and enterprise software.
2. History of Java
3. Java Editions
Java is divided into four main editions:
1️⃣ Java Standard Edition (Java SE) – Used for desktop applications and core Java concepts.
2️⃣ Java Enterprise Edition (Java EE) – Used for web and enterprise applications (Spring, Hibernate).
3️⃣ Java Micro Edition (Java ME) – Used for embedded systems and IoT devices.
4️⃣ JavaFX – Used for creating rich UI applications.
4. Java Architecture – How Java Works?
Java programs go through 5 stages from writing code to execution:
1️⃣ Writing Code (Source Code)
- Java programs are written in
.java
files using plain text.
2️⃣ Compilation (Java Compiler)
- The Java Compiler (javac) converts the source code into bytecode (.class files).
3️⃣ Bytecode (Intermediate Representation)
- Bytecode is not machine code; it is platform-independent and can run anywhere.
4️⃣ Java Virtual Machine (JVM)
- The JVM interprets and converts bytecode into machine code for execution.
5️⃣ Execution (Java Runtime Environment - JRE)
- The JRE (Java Runtime Environment) provides necessary libraries to run Java programs.
Diagram of Java Architecture:
Java Code (.java) → Compiler (javac) → Bytecode (.class) → JVM → Machine Code (Execution)
5. Java Development Kit (JDK) Components
To write and run Java programs, you need the Java Development Kit (JDK), which includes:
✅ JVM (Java Virtual Machine) – Runs Java programs.
✅ JRE (Java Runtime Environment) – Libraries + JVM for running Java applications.
✅ Compiler (javac) – Converts Java code into bytecode.
✅ Debugger (jdb) – Used for debugging Java programs.
Difference Between JDK, JRE, and JVM:
6. Writing Your First Java Program
Steps to Install Java
- Download and Install JDK: Get it from Oracle’s website.
- Set up Environment Variables:
- Add
JAVA_HOME
to system variables. - Add JDK
bin
path toPATH
.
- Add
- Verify Installation: Run
java -version
in Command Prompt (CMD).
Example Program (Hello World)
// Java program to print Hello World
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
Explanation:
public class HelloWorld
→ Defines a class namedHelloWorld
.public static void main(String[] args)
→ Main method (entry point).System.out.println("Hello, Java!");
→ Prints output to console.
How to Run This Program?
javac HelloWorld.java # Compiles Java file into bytecode
java HelloWorld # Runs the program
7. Advantages of Java
8. Where is Java Used?
✅ Web Applications – Spring Boot, JSP, Servlets
✅ Android Development – Kotlin & Java (Android Studio)
✅ Enterprise Applications – Banking, ERP Systems
✅ Game Development – Minecraft, LibGDX
✅ Cloud Computing & AI – AWS, Google Cloud, AI Libraries
✅ Big Data & IoT – Hadoop, Apache Spark
9. Java vs Other Languages
10. Summary & Next Steps
✅ Java is a platform-independent, object-oriented, secure, and robust programming language.
✅ It runs on the JVM, making it highly portable.
✅ The JDK provides tools to write, compile, and run Java programs.
✅ Java is widely used in web development, mobile apps, enterprise systems, and cloud computing.
Next Steps:
➡️ Learn Java Syntax – Variables, Data Types, Operators
➡️ Master OOP Concepts – Classes, Objects, Inheritance, Polymorphism
➡️ Explore Advanced Topics – Collections, Multithreading, JDBC
➡️ Build Real-World Projects – Web apps, APIs, JavaFX applications
Would you like hands-on exercises or a deeper dive into any topic?
2. Java Basics
Data Types & Variables
- Java has primitive data types:
int
(integer),double
(decimal),char
(character),boolean
(true/false),float
,long
,short
,byte
- Non-primitive data types:
String
,Array
,Class
,Interface
Example:
public class DataTypesExample {
public static void main(String[] args) {
int age = 25;
double price = 199.99;
char grade = 'A';
boolean isJavaFun = true;
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Grade: " + grade);
System.out.println("Java is fun: " + isJavaFun);
}
}
Java Basics – A Detailed Discussion
Java Basics form the foundation for writing and understanding Java programs. This discussion will cover data types, variables, operators, control statements, loops, methods, arrays, and strings in Java with concepts, examples, coding, and references.
1. Java Data Types
Concept:
Data types define the type of data a variable can store in Java. They are divided into:
1️⃣ Primitive Data Types – int
, float
, double
, char
, boolean
, etc.
2️⃣ Non-Primitive Data Types – String
, Array
, Class
, Interface
, etc.
Primitive Data Types (Memory & Example):
Example Code:
public class DataTypesExample {
public static void main(String[] args) {
int age = 25;
double price = 199.99;
char grade = 'A';
boolean isJavaFun = true;
System.out.println("Age: " + age);
System.out.println("Price: " + price);
System.out.println("Grade: " + grade);
System.out.println("Java is fun: " + isJavaFun);
}
}
2. Variables in Java
Concept:
- Variables are containers for storing data.
- Declared using a data type and a variable name.
- Naming rules: Must start with a letter,
_
, or $
, but cannot start with a number or Java keyword.
Types of Variables:
Example Code:
public class VariableExample {
static int count = 5; // Static variable
public static void main(String[] args) {
String name = "Alice"; // Local variable
System.out.println("Name: " + name);
System.out.println("Count: " + count);
}
}
3. Java Operators
Concept:
Operators perform operations on variables and values.
Types of Operators:
Example Code:
public class OperatorExample {
public static void main(String[] args) {
int a = 10, b = 5;
System.out.println("Sum: " + (a + b)); // Arithmetic
System.out.println("Is a greater? " + (a > b)); // Relational
System.out.println("Logical AND: " + (a > 0 && b > 0)); // Logical
}
}
4. Control Statements in Java
Concept:
Control statements are used to control the flow of a program based on conditions.
Types of Control Statements:
✅ Conditional Statements
if
, if-else
, if-else-if
, switch-case
✅ Looping Statements
for
, while
, do-while
✅ Jump Statements
break
, continue
, return
Conditional Statements Example:
public class IfElseExample {
public static void main(String[] args) {
int num = 10;
if (num > 0) {
System.out.println("Positive Number");
} else {
System.out.println("Negative Number");
}
}
}
Looping Statements Example:
public class LoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
}
}
5. Methods in Java
Concept:
Methods allow code reusability and modularity.
Types of Methods:
✅ Predefined Methods – Built-in Java methods like Math.sqrt()
, String.length()
.
✅ User-defined Methods – Custom methods created by the programmer.
✅ Static Methods – Called without creating an object.
Example Code:
public class MethodExample {
// User-defined method
static void greet() {
System.out.println("Hello, Welcome to Java!");
}
public static void main(String[] args) {
greet(); // Calling the method
}
}
6. Arrays in Java
Concept:
An array is a collection of elements of the same data type.
Example Code:
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println(num);
}
}
}
7. Strings in Java
Concept:
- Strings are immutable sequences of characters.
- Created using
String
class.
Example Code:
public class StringExample {
public static void main(String[] args) {
String name = "Java";
System.out.println("Length: " + name.length());
System.out.println("UpperCase: " + name.toUpperCase());
}
}
Summary & Next Steps
✅ Java Basics cover: Data Types, Variables, Operators, Control Flow, Loops, Methods, Arrays, and Strings.
✅ Key Takeaways:
- Java is statically typed, meaning variables must have a defined type.
- Control structures like
if-else
, loops, and methods help organize code.
- Arrays and Strings allow handling collections of data.
Next Steps:
➡️ Learn Object-Oriented Programming (OOP) in Java – Classes, Objects, Inheritance, Polymorphism
➡️ Explore Collections & Exception Handling
➡️ Start Building Mini Java Projects
Would you like detailed practice exercises or real-world examples next?
3. Control Statements
Conditional Statements
if-else
,switch-case
Looping Statements
for
,while
,do-while
Example (Loop & Condition):
public class LoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
System.out.println(i + " is Even");
} else {
System.out.println(i + " is Odd");
}
}
}
}
Control Statements in Java – A Detailed Discussion
Control statements in Java manage the flow of execution based on conditions, loops, or jumps. These statements allow decision-making, repeating tasks, and altering the normal flow of a program.
1. Types of Control Statements in Java
Java has three main categories of control statements:
2. Conditional Statements in Java
Conditional statements allow Java programs to execute different blocks of code based on conditions.
A) if Statement
- Used when there is one condition to check.
Syntax:
if (condition) {
// Code executes if the condition is true
}
Example:
public class IfExample {
public static void main(String[] args) {
int num = 10;
if (num > 0) {
System.out.println("Number is positive.");
}
}
}
B) if-else Statement
- Used when there are two possible outcomes (true or false).
Syntax:
if (condition) {
// Executes if condition is true
} else {
// Executes if condition is false
}
Example:
public class IfElseExample {
public static void main(String[] args) {
int num = -5;
if (num >= 0) {
System.out.println("Positive number.");
} else {
System.out.println("Negative number.");
}
}
}
C) if-else-if Ladder
- Used when there are multiple conditions to check.
Syntax:
if (condition1) {
// Executes if condition1 is true
} else if (condition2) {
// Executes if condition2 is true
} else {
// Executes if none of the conditions are true
}
Example:
public class IfElseIfExample {
public static void main(String[] args) {
int marks = 85;
if (marks >= 90) {
System.out.println("Grade: A+");
} else if (marks >= 80) {
System.out.println("Grade: A");
} else if (marks >= 70) {
System.out.println("Grade: B");
} else {
System.out.println("Grade: C");
}
}
}
D) switch-case Statement
- Used when we have multiple possible values for a variable.
- It is more efficient than multiple if-else statements when comparing the same variable with different values.
Syntax:
switch (variable) {
case value1:
// Code to execute if variable == value1
break;
case value2:
// Code to execute if variable == value2
break;
default:
// Code to execute if no case matches
}
Example:
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
}
}
3. Looping Statements in Java
Looping statements repeat a block of code multiple times based on a condition.
A) for Loop
- Used when we know how many times a loop should run.
Syntax:
for (initialization; condition; increment/decrement) {
// Code to be executed
}
Example:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
}
}
B) while Loop
- Used when the number of iterations is unknown but a condition is given.
Syntax:
while (condition) {
// Code executes while the condition is true
}
Example:
public class WhileLoopExample {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Iteration: " + i);
i++;
}
}
}
C) do-while Loop
- Similar to
while
, but executes at least once, even if the condition is false.
Syntax:
do {
// Code executes at least once
} while (condition);
Example:
public class DoWhileExample {
public static void main(String[] args) {
int i = 1;
do {
System.out.println("Iteration: " + i);
i++;
} while (i <= 5);
}
}
4. Jump Statements in Java
Jump statements alter the normal sequence of execution.
A) break Statement
- Stops the loop or switch case immediately.
Example:
public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Stops the loop when i = 3
}
System.out.println(i);
}
}
}
Output:
1
2
B) continue Statement
- Skips the current iteration and goes to the next loop iteration.
Example:
public class ContinueExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skips when i = 3
}
System.out.println(i);
}
}
}
Output:
1
2
4
5
C) return Statement
- Exits from a method and returns a value (if applicable).
Example:
public class ReturnExample {
static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = add(5, 10);
System.out.println("Sum: " + sum);
}
}
Summary & Next Steps
✅ Control Statements allow decision-making (if-else
), loops (for
, while
), and jumps (break
, continue
).
✅ Conditional statements control execution based on conditions.
✅ Loops help in repeating code efficiently.
✅ Jump statements modify the flow of execution.
Next Steps:
➡️ Learn Functions and Recursion in Java
➡️ Explore Object-Oriented Programming (OOP) in Java
➡️ Work on small projects using control statements
Would you like real-world examples or coding exercises on these topics?
4. Object-Oriented Programming (OOPs)
Concepts:
- Class & Object: Blueprint & instance
- Encapsulation: Data hiding
- Inheritance: Code reusability
- Polymorphism: Multiple forms
- Abstraction: Hiding details
Example (Class & Object)
class Car {
String brand;
Car(String brand) {
this.brand = brand;
}
void display() {
System.out.println("Car Brand: " + brand);
}
}
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Toyota");
myCar.display();
}
}
Object-Oriented Programming (OOP) in Java – A Detailed Discussion
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of objects and classes. It enables modular, reusable, and scalable code development in Java.
1. What is Object-Oriented Programming (OOP)?
Concept:
- OOP focuses on objects rather than functions and logic.
- An object represents a real-world entity with state (data/attributes) and behavior (methods/functions).
- Java follows four main principles of OOP:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
2. Key Concepts of OOP in Java
3. Classes and Objects in Java
A) What is a Class?
A class is a blueprint for creating objects. It contains fields (variables) and methods (functions) that define an object’s behavior.
Syntax of a Class:
class ClassName {
// Fields (variables)
// Methods (functions)
}
Example of a Class:
class Car {
String brand;
int speed;
void display() {
System.out.println("Brand: " + brand);
System.out.println("Speed: " + speed + " km/h");
}
}
B) What is an Object?
An object is an instance of a class. It contains real data and can use class methods.
Creating an Object:
public class CarDemo {
public static void main(String[] args) {
Car myCar = new Car(); // Creating an object
myCar.brand = "Toyota";
myCar.speed = 180;
myCar.display();
}
}
Output:
Brand: Toyota
Speed: 180 km/h
4. Encapsulation in Java
Concept:
- Encapsulation means hiding data from direct access.
- It is implemented using private fields and public getter/setter methods.
Example of Encapsulation:
class Person {
private String name; // Private variable
// Setter method
public void setName(String newName) {
name = newName;
}
// Getter method
public String getName() {
return name;
}
}
public class EncapsulationExample {
public static void main(String[] args) {
Person p = new Person();
p.setName("Alice");
System.out.println("Name: " + p.getName());
}
}
Output:
Name: Alice
5. Inheritance in Java
Concept:
- Inheritance allows a class (child) to inherit properties from another class (parent).
- It promotes code reusability and establishes relationships between classes.
Syntax:
class Parent {
// Parent class properties and methods
}
class Child extends Parent {
// Child class properties and methods
}
Example of Inheritance:
class Animal {
void sound() {
System.out.println("Animals make sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class InheritanceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.sound(); // Inherited method
myDog.bark(); // Child method
}
}
Output:
Animals make sound
Dog barks
6. Polymorphism in Java
Concept:
- Polymorphism allows a single interface to represent multiple implementations.
- It is of two types:
- Method Overloading (Compile-time polymorphism)
- Method Overriding (Runtime polymorphism)
A) Method Overloading (Compile-time Polymorphism)
- Same method name with different parameters (different number, type, or sequence of parameters).
Example of Method Overloading:
class MathOperations {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}
public class OverloadingExample {
public static void main(String[] args) {
MathOperations obj = new MathOperations();
System.out.println("Sum (2 args): " + obj.add(5, 10));
System.out.println("Sum (3 args): " + obj.add(5, 10, 15));
}
}
Output:
Sum (2 args): 15
Sum (3 args): 30
B) Method Overriding (Runtime Polymorphism)
- Child class provides a different implementation for a method already defined in the parent class.
Example of Method Overriding:
class Animal {
void makeSound() {
System.out.println("Animal makes a sound");
}
}
class Cat extends Animal {
@Override
void makeSound() {
System.out.println("Cat meows");
}
}
public class OverridingExample {
public static void main(String[] args) {
Animal myAnimal = new Cat(); // Runtime polymorphism
myAnimal.makeSound();
}
}
Output:
Cat meows
7. Abstraction in Java
Concept:
- Abstraction hides implementation details and shows only essential features.
- It is implemented using abstract classes and interfaces.
A) Abstract Class in Java
- An abstract class cannot be instantiated.
- It can have both abstract (without body) and concrete methods (with body).
Example of an Abstract Class:
abstract class Vehicle {
abstract void start(); // Abstract method (without body)
void stop() {
System.out.println("Vehicle stopped");
}
}
class Car extends Vehicle {
void start() {
System.out.println("Car starts with a key");
}
}
public class AbstractClassExample {
public static void main(String[] args) {
Car myCar = new Car();
myCar.start();
myCar.stop();
}
}
Output:
Car starts with a key
Vehicle stopped
B) Interface in Java
- An interface is a contract that classes must follow.
- All methods in an interface are abstract by default.
Example of an Interface:
interface Animal {
void makeSound(); // Abstract method
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Dog barks");
}
}
public class InterfaceExample {
public static void main(String[] args) {
Dog myDog = new Dog();
myDog.makeSound();
}
}
Output:
Dog barks
8. Summary & Next Steps
✅ OOP in Java includes: Classes, Objects, Encapsulation, Inheritance, Polymorphism, and Abstraction.
✅ Key Takeaways:
- Encapsulation protects data.
- Inheritance promotes code reusability.
- Polymorphism allows multiple behaviors using the same interface.
- Abstraction hides unnecessary details.
Next Steps:
➡️ Learn Exception Handling in Java
➡️ Explore Collections Framework
➡️ Work on small projects using OOP principles
Would you like practice exercises or real-world examples next?
5. Arrays & Collections
Array Example:
public class ArrayExample {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int num : numbers) {
System.out.println(num);
}
}
}
ArrayList Example:
import java.util.ArrayList;
public class ArrayListExample {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
for (String name : names) {
System.out.println(name);
}
}
}
6. Exception Handling
Definition:
- Handle runtime errors using
try-catch-finally
.
Example:
public class ExceptionExample {
public static void main(String[] args) {
try {
int num = 10 / 0; // Division by zero
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Execution completed.");
}
}
}
7. File Handling
Reading & Writing Files:
import java.io.FileWriter;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
try {
FileWriter writer = new FileWriter("file.txt");
writer.write("Hello, Java File Handling!");
writer.close();
System.out.println("File written successfully.");
} catch (IOException e) {
System.out.println("An error occurred.");
}
}
}
8. Multithreading
Thread Example:
class MyThread extends Thread {
public void run() {
System.out.println("Thread is running...");
}
}
public class ThreadExample {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
9. JDBC (Java Database Connectivity)
Connecting Java with MySQL
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class JDBCExample {
public static void main(String[] args) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
Statement stmt = con.createStatement();
stmt.executeUpdate("INSERT INTO users (name, email) VALUES ('Alice', 'alice@example.com')");
System.out.println("Data Inserted Successfully.");
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
10. Advanced Java (Frameworks & Web Development)
Spring Boot Example (REST API)
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello from Spring Boot!";
}
}
Conclusion & Next Steps
This guide covers all core Java concepts from basics to advanced. To continue learning:
- Practice coding daily.
- Work on real-world projects.
- Explore Java frameworks like Spring Boot & Hibernate.
- Learn about design patterns & system architecture.
Would you like hands-on exercises or real-world projects next?
Comments
Post a Comment