Introduction
What is Java?
Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995. It is known for its portability, robustness, and security.
> Motto: "Write Once, Run Anywhere" (WORA)
This means Java code can run on any device with a Java Virtual Machine (JVM), regardless of the underlying hardware or operating system.
---
Key Features of Java
1 - Object-Oriented Everything is treated as an object.
Platform Independent Java code runs on any platform via the JVM.
2 - Simple & Familiar Syntax is similar to C/C++.
3 - Secure Built-in security features like 3bytecode verification.
4 - Multithreaded Supports concurrent programming.
5 -Robust Strong memory management, exception handling.
6 - High Performance Just-In-Time (JIT) compiler optimizes performance.
7 - Distributed Supports networking and remote objects (RMI).
---
🔹 Java Architecture Overview
1. Source Code (.java) → Compiled by javac →
2. Bytecode (.class) → Executed by JVM
Diagram:
Java Source Code (.java)
↓ javac
Bytecode (.class)
↓ JVM
Machine-Specific Code
---
Basic Structure of a Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
class HelloWorld: Every Java program must have at least one class.
main(String[] args): Entry point of any Java application.
System.out.println: Prints text to the console.
---
Java Development Tools
JDK (Java Development Kit) – For developing Java programs.
JRE (Java Runtime Environment) – For running Java programs.
JVM (Java Virtual Machine) – Interprets and executes bytecode.
---
Common Java Applications
Desktop GUI Applications (e.g., Swing, JavaFX)
Web Applications (e.g., JSP, Servlets)
Mobile Applications (Android uses Java)
Enterprise Applications (Spring, Hibernate)
Embedded Systems
Scientific Applications
---
Java Output
1. Basic Console Program
This is the most common "Hello, World!" program.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
How to run:
1. Save as HelloWorld.java
2. Compile: javac HelloWorld.java
3. Run: java HelloWorld
---
2. Using a Method
A bit more structure:
public class HelloWorld {
public static void main(String[] args) {
printMessage();
}
public static void printMessage() {
System.out.println("Hello, World!");
}
}
---
3. Using a Constructor
More object-oriented:
public class HelloWorld {
public HelloWorld() {
System.out.println("Hello, World!");
}
public static void main(String[] args) {
new HelloWorld();
}
}
---
4. GUI Version (Swing)
A pop-up window instead of console output:
import javax.swing.JOptionPane;
public class HelloWorld {
public static void main(String[] args) {
JOptionPane.showMessageDialog(null, "Hello, World!");
}
}
---
5. JavaFX Version
Requires JavaFX SDK (Java 11+ doesn't bundle JavaFX by default):
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.stage.Stage;
public class HelloWorld extends Application {
public void start(Stage stage) {
Label label = new Label("Hello, World!");
Scene scene = new Scene(label, 200, 100);
stage.setScene(scene);
stage.setTitle("Hello");
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
---
Data Type
In Java, data types specify the size and type of values that can be stored in variables. Java has two main categories of data types:
---
🔹 1. Primitive Data Types
These are the most basic data types built into the Java language.
Data Type Size Description Example
byte 1 byte Stores whole numbers from -128 to 127 byte b = 100;
short 2 bytes Whole numbers from -32,768 to 32,767 short s = 10000;
int 4 bytes Whole numbers from -2^31 to 2^31-1 int i = 50000;
long 8 bytes Larger whole numbers long l = 15000000000L;
float 4 bytes Decimal numbers (less precision) float f = 5.75f;
double 8 bytes Decimal numbers (more precision) double d = 19.99;
char 2 bytes A single Unicode character char c = 'A';
boolean 1 bit True or false boolean b = true;
---
🔹 2. Non-Primitive Data Types (Reference Types)
These are more complex types that refer to objects.
Type Description Example
String A sequence of characters (text) String name = "Java";
Arrays A collection of values of same type int[] numbers = {1,2,3};
Classes User-defined types MyClass obj = new MyClass();
Interfaces Abstract types for polymorphism Runnable r = new MyRunnable();
---
🔸 Type Conversion
Java supports automatic (implicit) and manual (explicit) type conversion between compatible types:
Implicit (Widening): int → long → float → double
Explicit (Narrowing): double → float → long → int → short → byte
Example:
int x = 10;
double y = x; // implicit
double a = 9.78;
int b = (int) a; // explicit
Variables
🔹 Java Variables – Overview
In Java, a variable is a container that holds data that can be changed during the execution of a program. Each variable has a type, a name, and optionally an initial value.
---
Basic Syntax
<type> <variableName> = <value>;
Example:
int age = 25;
String name = "Alice";
boolean isJavaFun = true;
---
🔸 Types of Variables in Java
Java variables are classified based on where they are declared and how they are used:
Type Declared Inside Accessible From Memory Location
Local Variable Method or block Only within that method/block Stack
Instance Variable Inside a class (outside methods) Specific object (non-static) Heap
Static Variable Inside a class with static All instances of the class Method Area
---
🔹 1. Local Variable
Defined inside a method or block. Must be initialized before use.
void greet() {
String message = "Hello!";
System.out.println(message);
}
---
🔹 2. Instance Variable
Declared in a class but outside any method. Belongs to each object.
public class Person {
String name; // instance variable
void display() {
System.out.println("Name: " + name);
}
}
---
🔹 3. Static Variable
Declared with static. Shared by all objects of the class.
public class Counter {
static int count = 0; // static variable
Counter() {
count++;
}
}
---
🔸 Variable Naming Rules
✅ Valid:
Must begin with a letter, $, or _
Can contain letters, digits, $, and _
Case-sensitive
❌ Invalid:
Can't use reserved keywords (e.g., int, class)
Can't start with a digit
Examples:
int _score = 100;
String $name = "Java";
double price2 = 99.99;
---
Comments
Java Comments – Explained
Comments in Java are used to explain code, make it more readable, or temporarily disable code during debugging. Comments are ignored by the compiler, so they don’t affect the program execution.
---
🔸 Types of Comments in Java
Java supports three types of comments:
---
1. Single-line Comments
Use // for short, one-line comments.
// This is a single-line comment
int age = 25; // age of the person
---
2. Multi-line Comments
Use /* ... */ for longer comments that span multiple lines.
/*
This is a multi-line comment.
It can span multiple lines.
Useful for explaining code blocks.
*/
int sum = a + b;
---
3. Documentation Comments (JavaDoc)
Use /** ... */ for generating API documentation. These are usually placed before classes, methods, or fields.
/**
* This class represents a simple calculator.
* It can perform addition and subtraction.
*/
public class Calculator {
/**
* Adds two numbers.
* @param a First number
* @param b Second number
* @return Sum of a and b
*/
public int add(int a, int b) {
return a + b;
}
}
You can generate HTML documentation using the javadoc tool:
javadoc Calculator.java
---
Keywords
Java Keywords – Complete Guide
Java keywords are reserved words that have a specific meaning in the language. You cannot use them as variable names, method names, class names, or identifiers.
---
What Are Keywords?
They are part of the Java syntax and define the structure and flow of a program (like class, if, while, return, etc.).
Java has 50 reserved keywords (as of Java 17+), including some that are not currently used but are reserved for future use.
---
🔹 Commonly Used Java Keywords (Grouped by Purpose)
1. Class & Object Related
Keyword Description
class Declares a class
interface Declares an interface
extends Inherits a class
implements Implements an interface
new Creates new objects
this Refers to the current object
super Refers to the superclass
---
2. Control Flow
Keyword Description
if Conditional statement
else Alternate branch
switch Multi-way decision
case Defines a branch in switch
default Fallback in switch
while Loop
do Loop (executes at least once)
for Loop
break Exits loop or switch
continue Skips to next loop iteration
return Exits from method and returns value
---
3. Access Modifiers
Keyword Description
public Accessible from anywhere
private Accessible only within the class
protected Accessible within package and subclass
static Belongs to the class, not instance
final Constant or cannot be overridden
abstract Class or method without implementation
---
4. Memory Management & Class Loading
Keyword Description
null No object reference
new Allocates memory
instanceof Checks object type
try, catch, finally, throw, throws Exception handling
---
5. Other Useful Keywords
Keyword Description
import Imports packages
package Defines package name
synchronized Thread-safe block or method
volatile Variable is thread-safe
transient Prevents serialization
assert For debugging/testing
enum Defines constants set
native Links to non-Java (native) code
---
Example Program Using Keywords
public class Example {
final int number = 10;
public static void main(String[] args) {
Example obj = new Example();
if (obj instanceof Example) {
System.out.println("This is an instance of Example.");
}
}
}
---
Operators
In Java, operators are special symbols or keywords used to perform operations on variables and values. They are essential to building logic in Java programs.
Here's a categorized overview of Java operators:
---
🔹 1. Arithmetic Operators
Used for basic mathematical operations.
Operator Meaning Example
+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
% Modulus (Remainder) a % b
---
🔹 2. Assignment Operators
Used to assign values to variables.
Operator Meaning Example
= Assign value a = b
+= Add and assign a += b (same as a = a + b)
-= Subtract and assign a -= b
*= Multiply and assign a *= b
/= Divide and assign a /= b
%= Modulus and assign a %= b
---
🔹 3. Relational (Comparison) Operators
Used to compare two values.
Operator Meaning Example
== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater or equal a >= b
<= Less or equal a <= b
---
🔹 4. Logical Operators
Used to combine multiple boolean expressions.
Operator Meaning Example
&& Logical AND a > 10 && b < 5
` `
! Logical NOT !(a == b)
---
🔹 5. Unary Operators
Operate on a single operand.
Operator Meaning Example
+ Unary plus (positive) +a
- Unary minus (negative) -a
++ Increment a++ or ++a
-- Decrement a-- or --a
! Logical NOT !true
---
🔹 6. Bitwise Operators
Work on bits and perform bit-by-bit operations.
Operator Meaning Example
& Bitwise AND a & b
` ` Bitwise OR
^ Bitwise XOR a ^ b
~ Bitwise Complement ~a
<< Left shift a << 2
>> Right shift a >> 2
>>> Unsigned right shift a >>> 2
---
🔹 7. Ternary Operator
A shorthand for if-else.
condition ? value_if_true : value_if_false;
Example:
int max = (a > b) ? a : b;
---
🔹 8. Instanceof Operator
Checks whether an object is an instance of a specific class or subclass.
object instanceof ClassName
Example:
if (obj instanceof String) {
// do something
}
---
if else
In Java, the if-else statement is used to perform conditional logic — it lets you execute certain blocks of code depending on whether a condition is true or false.
---
🔹 Basic Syntax of if, else if, and else
if (condition) {
// Executes if condition is true
} else if (anotherCondition) {
// Executes if previous condition is false and this one is true
} else {
// Executes if all above conditions are false
}
---
Examples
1. Simple if statement
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
2. if-else statement
int number = -5;
if (number > 0) {
System.out.println("Positive number");
} else {
System.out.println("Negative number");
}
3. if-else if-else ladder
int number = 0;
if (number > 0) {
System.out.println("Positive");
} else if (number < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
---
🔹 Nested if statement
You can also nest if statements inside each other.
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
if (hasLicense) {
System.out.println("You can drive.");
} else {
System.out.println("Get a license first.");
}
} else {
System.out.println("You're too young to drive.");
}
---
Switch Case
In Java, the switch statement is used to execute one block of code among many options, based on the value of a variable or expression. It's a cleaner alternative to multiple if-else statements when you're checking the same variable for different values.
---
🔹 Basic Syntax
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
// ...
default:
// code block
}
---
Example 1: switch with int
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");
}
Output:
Wednesday
---
🔹 break Statement
break is used to exit the switch block after a case is matched.
If omitted, Java will "fall through" to the next case — which is sometimes intentional but often causes bugs if forgotten.
---
Example 2: switch with String
String fruit = "Apple";
switch (fruit) {
case "Apple":
System.out.println("Red fruit");
break;
case "Banana":
System.out.println("Yellow fruit");
break;
default:
System.out.println("Unknown fruit");
}
---
Example 3: Grouping Cases
int month = 4;
switch (month) {
case 3: case 4: case 5:
System.out.println("Spring");
break;
case 6: case 7: case 8:
System.out.println("Summer");
break;
default:
System.out.println("Another season");
}
---
🔹 New Feature: Switch Expressions (Java 14+)
Java 14 introduced switch expressions, allowing you to assign values more cleanly:
String result = switch (day) {
case 1 -> "Monday";
case 2 -> "Tuesday";
case 3 -> "Wednesday";
default -> "Unknown day";
};
System.out.println(result);
> ✅ No need for break when using -> syntax!
Loops
In Java, loops are used to execute a block of code multiple times. Java supports several types of loops to handle different looping needs.
---
🔹 Types of Loops in Java
1. for loop – Use when the number of iterations is known.
2. while loop – Use when the number of iterations is unknown but the condition must be checked before the loop runs.
3. do-while loop – Like while, but runs at least once.
4. Enhanced for loop – For iterating through arrays or collections.
---
1. for Loop
for (initialization; condition; update) {
// code to be executed
}
Example:
for (int i = 1; i <= 5; i++) {
System.out.println("i = " + i);
}
---
2. while Loop
while (condition) {
// code to be executed
}
Example:
int i = 1;
while (i <= 5) {
System.out.println("i = " + i);
i++;
}
---
3. do-while Loop
do {
// code to be executed
} while (condition);
Example:
int i = 1;
do {
System.out.println("i = " + i);
i++;
} while (i <= 5);
> ✅ Runs at least once, even if the condition is false.
---
4. Enhanced for Loop (for-each)
Best for iterating through arrays or collections.
for (type variable : array) {
// code to be executed
}
Example:
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}
---
🔹 Loop Control Statements
Keyword Description
break Exits the loop immediately
continue Skips the current iteration and goes to the next
Example with continue:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i); // Skips printing 3
}
---
🔹 Loop Comparison Table
Feature for while do-while
Condition check Before loop Before loop After loop
Guaranteed to run once? No No ✅ Yes
Use case Known loop count Unknown loop count Run once, then check
---
Array
In Java, an array is a data structure that stores multiple values of the same type in a single variable. It's useful when you want to work with a group of related data elements using a single name.
---
🔹 Array Basics
✅ Declaration:
int[] numbers; // preferred
// OR
int numbers[]; // also valid
✅ Initialization:
numbers = new int[5]; // creates an array of size 5
✅ Declaration + Initialization:
int[] numbers = new int[5]; // default values (0)
String[] names = new String[3]; // default null values
✅ With Values:
int[] numbers = {10, 20, 30, 40, 50};
---
🔹 Accessing Array Elements
System.out.println(numbers[0]); // prints first element
numbers[2] = 100; // sets third element to 100
> ✅ Array indices start at 0 and go to length - 1
---
🔹 Length of an Array
System.out.println(numbers.length); // prints size of array
---
✅ Example: Simple Array
public class ArrayExample {
public static void main(String[] args) {
int[] marks = {90, 85, 70, 95};
for (int i = 0; i < marks.length; i++) {
System.out.println("Mark " + i + ": " + marks[i]);
}
}
}
---
🔹 Enhanced for Loop with Arrays
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.println(num);
}
---
🔹 Types of Arrays
1. Single-dimensional Array
int[] a = new int[5];
2. Multi-dimensional Array (2D example)
int[][] matrix = {
{1, 2, 3},
{4, 5, 6}
};
System.out.println(matrix[1][2]); // prints 6
---
Methods
Sure! Java methods are blocks of code that perform a specific task and can be called (invoked) when needed. They help in organizing and reusing code.
Here's a breakdown of Java methods:
---
🔹 Basic Syntax of a Method
modifier returnType methodName(parameters) {
// method body
// code to execute
return value; // if returnType is not void
}
---
🔹 Example 1: A Simple Method
public class MyClass {
// Method that returns the sum of two numbers
public int add(int a, int b) {
return a + b;
}
}
---
🔹 Calling a Method
You need an object to call a non-static method:
MyClass obj = new MyClass();
int result = obj.add(5, 3);
System.out.println(result); // Output: 8
---
🔹 Types of Methods
1. Instance Methods – Require an object to be called.
2. Static Methods – Belong to the class, called without creating an object.
public static void greet() {
System.out.println("Hello!");
}
// Call:
MyClass.greet();
---
🔹 Void Methods
Methods that don’t return a value:
public void printHello() {
System.out.println("Hello!");
}
---
🔹 Return Type
int, String, boolean, etc. → return a value.
void → returns nothing.
---
🔹 Method Overloading
You can define multiple methods with the same name but different parameters:
public int add(int a, int b) { return a + b; }
public double add(double a, double b) { return a + b; }
---
Class and Object
🔹 What is a Class?
A class is like a blueprint or template for creating objects. It defines the properties (variables) and behaviors (methods) that the objects created from the class will have.
Think of it like:
Class = Blueprint for a house
Object = A specific house built from that blueprint
---
🔹 What is an Object?
An object is an instance of a class. When you create an object, you’re making a specific thing based on the class blueprint. Each object has its own set of values for the properties defined by the class.
---
🔹 Basic Class Example
// Define a class
public class Car {
// Properties (fields)
String color;
String model;
int year;
// Method (behavior)
public void drive() {
System.out.println("The " + model + " is driving.");
}
}
---
🔹 Creating and Using Objects
public class Main {
public static void main(String[] args) {
// Create an object of Car class
Car myCar = new Car();
// Set properties
myCar.color = "Red";
myCar.model = "Toyota";
myCar.year = 2020;
// Call a method
myCar.drive(); // Output: The Toyota is driving.
}
}
---
🔹 Key Points
Class defines what an object is (properties and behaviors).
Object is an instance of a class with specific values.
You create objects using the new keyword.
Each object has its own copy of the class’s variables.
---
🔹 Constructors
Classes often have constructors — special methods to initialize new objects.
Example:
public class Car {
String model;
int year;
// Constructor
public Car(String model, int year) {
this.model = model;
this.year = year;
}
}
Create an object with the constructor:
Car myCar = new Car("Honda", 2021);
Comments
Post a Comment