Introduction to Java.
1. What is Java?
Java is a high-level, object-oriented, platform-independent programming
language.
Developed by James Gosling at Sun Microsystems in 1995 (now owned by Oracle).
Famous for its principle: “Write Once, Run Anywhere (WORA)” – meaning Java
programs can run on any system that has the Java Virtual Machine (JVM).
2. Key Features of Java
1. Simple & Easy to Learn – Syntax is similar to C/C++ but with fewer complexities
(like no pointers).
2. Object-Oriented – Everything in Java is based on classes and objects (Encapsulation,
Inheritance, Polymorphism).
3. Platform Independent – “Write Once, Run Anywhere (WORA).” Java code runs
on the Java Virtual Machine (JVM), not directly on the OS.
4. Secure – Provides runtime security, no explicit memory access.
5. Robust – Strong memory management and exception handling.
6. Multithreaded – Supports concurrent execution (multiple tasks at once).
7. Portable – Java bytecode can run on any system with JVM.
8. Distributed – Supports distributed applications via RMI and networking.
3. Applications of Java
Desktop Applications → IDEs like Eclipse, IntelliJ.
Mobile Applications → Android apps are built on Java.
Web Applications → Backend systems using Spring, Hibernate.
Enterprise Applications → Banking, e-commerce systems.
Big Data & Cloud → Hadoop, Spark.
Game Development → 2D/3D games with Java frameworks.
4. Basic Structure of a Java Program
Components of Java Program Structure:
1. Comments → For documentation and
code readability.
2. Package Declaration (optional) →
Organizes classes, Groups classes
(optional)
3. Import Statements (optional) →
Access libraries.
4. Class Declaration → Defines the
program’s class.
5. Main Method → Starting point of
execution.
6. Statements → Instructions that run inside main()
5. MY FIRST JAVA PROGRAM :
Example:
class HelloWorld
{
public static void main(String[] args) {
[Link]("Hello, Java!");
}
}
Explanation:
class → Defines a class in Java.
public static void main(String[] args) → Entry point of any Java program.
[Link] → Prints output to the console.
Output:
Hello, Java!
Steps to Create & Run a Java Program
Step 1: Open a Text Editor or IDE
You can use:
o Notepad (Windows)
o TextEdit (Mac) (in plain text mode)
o VS Code, Brackets, Sublime Text
o Eclipse/IntelliJ IDEA (for IDE users)
Step 2: Create a new file (NotePad)
Write this code in the editor:
// [Link]
// A simple Java program
public class Hello {
public static void main(String[] args) {
[Link]("Hello, Java!"); // Print message
}
}
⚠️ Important: File name must match the class name (Hello). So save it as:
👉 [Link] (ie .is [Link])
Step 3: Open Terminal/Command Prompt.
Windows: Press Win + R, type cmd, hit Enter
Mac/Linux: Open Terminal
Step 4: Go to the folder where you saved the program
Example (Windows):
cd C:\Users\YourName\Documents\JavaPrograms
Step 5: Compile the program
Run: javac [Link]
javac [Link]
👉This creates a [Link] file (Java bytecode).
If there are no errors, move to next step.
Step 6: Run the program.
Run: java Classname
java Hello
Output:
Hello, Java!
6. Java Architecture (Environment ) and Components:
Java Architecture
Source Code (.java) → compiled by Java Compiler (javac)
Output: Bytecode (.class) → executed by JVM (Java Virtual Machine)
JVM runs inside the JRE (Java Runtime Environment).
JDK (Java Development Kit) = JRE + Compiler + Development tools.
A Java Architecture or Environment is the complete setup required to write, compile, and
run Java programs.
Components of Java Architecture
Java architecture comprises three main components:
Java Development Kit (JDK) = Development (Compiler + JRE).
Java Runtime Environment (JRE) = Running programs (JVM + Libraries).
Java Virtual Machine (JVM) = Executes bytecode on any platform.
1. Java Development Kit (JDK)
The JDK is used by developers to write Java programs.
It contains:
o Compiler (javac) → Converts Java source code into bytecode.
o Java Runtime Environment (JRE) → For running Java applications.
o Java API (libraries) → Predefined classes and methods.
o Tools like debugger (jdb), documentation tool (javadoc), etc.
👉 Example: You install JDK 17 to start programming in Java.
2. Java Runtime Environment (JRE)
JRE is the part of JDK that allows you to run Java programs.
It contains:
o Java Virtual Machine (JVM)
o Class Libraries (core packages like [Link], [Link])
o Other runtime components.
👉 If you only want to run Java applications (not develop), you just need the JRE.
3. Java Virtual Machine (JVM)
JVM is the heart of the Java environment.
Provides platform independence → “Write Once, Run Anywhere”.
It executes Java bytecode (.class files).
How JVM Works
Diagram of JVM Working
JVM
Steps:
Java Source Code (.java) → The programmer writes code in a .java file
( for example: [Link]).
Compiler → The javac compiler converts source code into bytecode (.class file).
Java Compiler (javac) translates your human-readable code into bytecode, stored in
a .class file.
Bytecode (.class) → Platform-independent instructions
This bytecode is special because it’s platform-independent : “Write Once, Run
Anywhere”. – it can run on any system that has a JVM.
JVM Execution (main components work together):
JVM runs Java programs by converting bytecode into machine code and managing
resources automatically.
Class Loader → Loads classes dynamically.
Memory Areas → Store code, objects, and variables.
Divide memory into method area, heap, stack, PC register, etc., for program
execution.
Execution Engine → Runs the program (Interpreter + JIT).
Runs the bytecode using Interpreter (line by line) or JIT compiler (compiles hot
code to machine code).
Native Interface (JNI) → Connects Java with non-Java code.
Allows Java to interact with native (C/C++) code and system-level resources.
Garbage Collector → Manages memory cleanup.
Automatically removes unused objects from memory.
Operating System → JVM finally relies on the OS to execute the translated machine code
on hardware.
Responsibilities of JVM.
o Loads class files.
o Verifies bytecode security.
o Converts bytecode into machine code (using JIT compiler).
o Manages memory (Garbage Collection).
Difference Between JDK, JRE and JVM
JDK JRE JVM
The full form of JRE is Java Runtime
The full form of JDK is Java The full form of JVM is
Environment.
Development Kit Java Virtual Machine.
JVM
JVM executes Java byte
JDK is a software it is a software bundle which provides
code and provides an
development kit to develop Java class libraries with necessary
environment for executing
applications in Java. components to run Java code.
it.
JVM is platform-
JDR is platform dependent. JRE is also platform dependent.
independent.
It contain tools for developing It contains class libraries and other
Software development tools
debugging and monitoring supporting files that JVM requires to
are not included in JVM.
java code. execute the program.
It is the superset of JRE It is the subset of JDK. JVM is a subset of JRE
The JDK enables developers
It is the Java platform
to create Java programs that The JRE is the part of Java that
component that executes
can be executed and run by creates the JVM.
source code.
the JRE and JVM.
JRE only contain environment to JVM bundled in both
JDK comes with the installer
execute source code. software JDK and JRE
Difference Between C and Java
C = Low-level, fast, procedural, system-level programming.
Java = High-level, portable, object-oriented, application-level programming.
Feature C Java
Procedural/Structured programming Object-Oriented programming language
Language Type
language. (OOP).
Platform dependent → compiled C code Platform independent → "Write Once,
Platform
runs only on the system where it’s Run Anywhere" because Java programs
Dependency
compiled. run on JVM (Java Virtual Machine).
Compilation & Compiled directly into machine code Compiled into bytecode, then executed
Execution by a C compiler → runs fast. by JVM → slightly slower than C.
Memory Programmer manages memory Automatic Garbage Collection (no
Management manually using malloc() / free(). manual memory management).
Supports pointers (direct memory Does not support pointers explicitly (for
Pointers
access). security and simplicity).
Simple and close to hardware (low- More strict and verbose, with emphasis
Syntax Style
level features available). on OOP principles.
Programming Procedural (focuses on functions and Object-Oriented (focuses on classes and
Paradigm procedures). objects).
Fully supports inheritance,
Not supported directly (can be done
Inheritance polymorphism, encapsulation,
through function calls, but not natural).
abstraction.
Uses standard library (stdio.h, stdlib.h, Rich standard library (collections,
Libraries
etc.). networking, multithreading, GUI, etc.).
Application development (web apps,
System programming (OS, drivers,
Use Cases mobile apps, enterprise software, cloud,
embedded systems, compilers).
games).
Speed Faster (closer to hardware). Slower (JVM overhead).
Low portability → recompiled for each High portability → runs anywhere with
Portability
platform. JVM.
Basics Of Java
Data Types:
Data types specify the type of data a variable can store. Java is strongly typed, meaning
every variable must be declared with a type.
Types of Data Types
Java data types are divided into two main categories:
1. Primitive Data Types (Built-in, 8 types): → 8 basic data types (byte, short, int, long,
float, double, char, boolean)
2. Non-Primitive Data Types (Reference types) → Objects, Strings, Arrays, Classes,
Interfaces, Enums
Primitive store value, Non-primitive store reference
1. Primitive Data Types (Built-in, 8 types): → 8 basic data types (byte, short, int, long, float,
double, char, boolean)
Primitive data types are the most basic, predefined data types in Java. They directly hold
values.
Types of Primitive Data Types
Data Type Size Definition Example
byte 8-bit Stores small integers (used in arrays, memory saving). byte b = 100;
short 16-bit Stores medium integers. short s = 1000;
int 32-bit Default integer type for whole numbers. int x = 50000;
long 64-bit Stores large integers (use with L). long l = 100000L;
float 32-bit Stores decimal numbers with 7-digit precision (use with f). float f = 12.45f;
Stores decimal numbers with 15-digit precision (default decimal double d =
double 64-bit
type). 123.456;
char 16-bit Stores a single Unicode character. char c = 'A';
boolean 1-bit* Stores only true or false. boolean flag = true;
2. Non-Primitive Data Types( Reference types) → Objects, Strings, Arrays, Classes,
Interfaces, Enums
Non-primitive (reference) data types do not store the value directly but instead refer to an
object in memory.
Non-Primitive Data Types are:
String → String name = "Java";
Arrays → int[] arr = {1, 2, 3};
Classes & Objects → User-defined types
Interfaces, Enums
These are stored as objects and reference memory locations.
ASIGNEMENT:
Difference between Primitive Data type and Non- Primitive Data type
Type Casting
Type casting in Java is the process of converting a variable of one data type into another.
It is used when you want to store a value of one type in a variable of another type.
Types of Type Casting
There are two main types of type casting in Java:
1. Widening Type Casting (Implicit Casting / Upcasting)
👉 Definition: Converting a smaller data type into a larger data type automatically.
If the conversion is from smaller type → larger type, it is called Widening
(implicit) casting.
Done by the compiler (no data loss).
Also called type promotion.
👉 Order of widening (from smaller → larger):
byte → short → int → long → float → double
Example:
public class WideningExample {
public static void main(String[] args) {
int a = 10; // int value
double b = a; // automatic conversion (int → double)
[Link]("Int value: " + a);
[Link]("Double value: " + b);
}
}
Output:
Int value: 10
Double value: 10.0
2. Narrowing Type Casting (Explicit Casting / Downcasting)
👉 Definition: Converting a larger data type into a smaller data type.
If the conversion is from larger type → smaller type, it is called Narrowing (explicit)
casting.
Done manually by the programmer.
May lead to data loss or precision loss.
Requires explicit cast (type).
👉 Order of narrowing (reverse of widening):
double → float → long → int → short → byte
Example:
public class NarrowingExample {
public static void main(String[] args) {
double x = 10.75; // double value
int y = (int) x; // manual conversion (double → int)
[Link]("Double value: " + x);
[Link]("Int value after casting: " + y);
}
}
Output:
Double value: 10.75
Int value after casting: 10
Note:
Type Definition Casting Style Example Data Loss?
Widening Smaller → Larger Automatic int a = 10; double b = a; No
Narrowing Larger → Smaller Manual (type) double d = 10.5; int x = (int) d; Yes (possible)
ASIGNEMENT:
Why there is no loss in Widening Casting, but there is loss in Narrowing Casting
Widening (Safe):
byte 100 → int 100 → double 100.0 ✅ (No loss)
Narrowing (Risky):
double 123.456 → int 123 ❌ (Loss of .456)
Variable in Java
A variable is a named memory location used to store data.
Think of it as a container that holds values that can be used and modified during program
execution.
Declaring Variables
Prefer camelCase for variables (e.g.,
Syatax: studentAge).
dataType variableName = value;
7. A variable must have a unique name
📌 Rules for Declaring Variables in Java within its scope.
1. A variable must be declared before it is
used. Cannot declare two variables with the
Data type is mandatory. same name in the same block.
2. Variable name must begin with a letter, Examples:
underscore _, or dollar sign $. int age = 25;
Cannot start with a digit. double salary = 55000.50;
char grade = 'A';
3. Variable name can contain letters, digits, String name = "John";
underscores, and dollar signs. boolean isJavaFun = true;
No spaces or special characters allowed. Valid Variable Examples
int age;
4. Variable names are case-sensitive. int _value;
int $price;
Age and age are different. double studentMarks;
String firstName;
5. Reserved keywords cannot be used as int roll_no1;
variable names.
❌ Invalid Variable Examples
Example: int class; is invalid. int 1age; // ❌ starts with a number
int roll-no; // ❌ hyphen not allowed
6. A variable name should be meaningful and int first name; // ❌ space not allowed
follow Java naming conventions. int class; // ❌ 'class' is a keyword
int @data; // ❌ special symbol not allowed
Types of Variables in Java or Variable Scope
1. Local Variables
2. Instance Variables(Non-static fields)
3. Static Variables(Class variables)
1. Local Scope:
- Variables Declared inside a method, constructor, or block.
- Accessible only within the block where they are declared.
- No default value; must be initialized before use.
Examples
void method()
{
int localVar = 10;
[Link](localVar);
}
2. Instance Variables:
- Declared inside a class but outside any method or block.
- Each instance of the class has its own copy.
- Can have default values (e.g., int defaults to 0, boolean defaults to false).
Examples
class Student
{
String name; // instance variable
}
3. Static Variables:
- Declared with the static keyword.
- Shared by all instances of the class.
- Loaded into memory only once at the time of class loading.
- Can have default values.
Examples
class Student {
static String school = "ABC High School"; // static variable
}
🔹 Operators in Java
Operators are special symbols that perform operations on variables and values.
For example: +, -, *, /, ==, &&, etc.
Operators in Java
1. Arithmetic
2. Unary
3. Assignment
4. Relational
5. Logical
6. Bitwise
7. Conditional (Ternary)
8. Type Cast
9. Instanceof
10. Special Operators
1. Arithmetic Operators
Definition: Operators used for performing basic mathematical operations.
Use: Addition, subtraction, multiplication, division, remainder.
Operator Name Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 3 3
% Modulus 10 % 3 1
EXAMPLE:
class ArithmeticDemo {
public static void main(String[] args) {
int a = 10, b = 3;
[Link]("Addition: " + (a + b));
[Link]("Subtraction: " + (a - b));
[Link]("Multiplication: " + (a * b));
[Link]("Division: " + (a / b));
[Link]("Modulus: " + (a % b));
}
}
2. Unary Operators
Definition: Operators that work on a single operand.
Use: To increase, decrease, negate, invert values.
Operator Name Example Result
+ Unary plus +5 5
- Unary minus -5 -5
++ Increment ++a (if a=5) 6
-- Decrement --a (if a=5) 4
Operator Name Example Result
! Logical NOT !(true) false
~ Bitwise NOT ~5 -6
class UnaryDemo {
public static void main(String[] args) {
int x = 5;
[Link]("Pre-Increment (++x): " + (++x));
[Link]("Post-Increment (x++): " + (x++));
[Link]("After Post-Increment: " + x);
[Link]("Pre-Decrement (--x): " + (--x));
[Link]("Post-Decrement (x--): " + (x--));
[Link]("After Post-Decrement: " + x);
[Link]("Logical NOT (!true): " + (!true));
[Link]("Bitwise Complement (~5): " + (~5));
}
}
3. Assignment Operators
Definition: Operators used to assign values to variables.
Use: Store or update values in variables.
Operator Name Example Equivalent
= Assignment a=5 a=5
+= Add & assign a += 3 a = a + 3
-= Subtract & assign a -= 2 a=a-2
*= Multiply & assign a *= 4 a=a*4
/= Divide & assign a /= 2 a=a/2
%= Modulus & assign a %= 3 a = a % 3
class AssignmentDemo {
public static void main(String[] args) {
int y = 20;
y += 5; [Link]("y += 5 → " + y);
y -= 3; [Link]("y -= 3 → " + y);
y *= 2; [Link]("y *= 2 → " + y);
y /= 4; [Link]("y /= 4 → " + y);
y %= 3; [Link]("y %= 3 → " + y);
}
}
4. Relational Operators
Definition: Operators used for comparison between two values.
Use: Return true or false depending on relation.
Operator Name Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
> Greater than 5>3 true
< Less than 5<3 false
>= Greater or equal 5 >= 5 true
<= Less or equal 3 <= 5 true
class RelationalDemo {
public static void main(String[] args) {
int a = 10, b = 3;
[Link]("a == b: " + (a == b));
[Link]("a != b: " + (a != b));
[Link]("a > b: " + (a > b));
[Link]("a < b: " + (a < b));
[Link]("a >= b: " + (a >= b));
[Link]("a <= b: " + (a <= b));
}
}
5. Logical Operators
Definition: Operators that work on boolean values (true/false).
Use: Combine multiple conditions.
Operator Name Example Result
&& Logical AND (5 > 3 && 2 < 4) true
` ` Logical OR
! Logical NOT !(5 > 3) false
class LogicalDemo {
public static void main(String[] args) {
int a = 10, b = 3;
[Link]("(a > 5 && b < 5): " + (a > 5 && b < 5));
[Link]("(a > 5 || b > 5): " + (a > 5 || b > 5));
[Link]("!(a > b): " + !(a > b));
}
}
6. Bitwise Operators
Definition: Operators that perform operations at the bit level.
Use: Manipulate bits (0s and 1s).
Operator Name Example (a=5, b=3) Result
& Bitwise AND a&b 1
` ` Bitwise OR `a
Operator Name Example (a=5, b=3) Result
^ Bitwise XOR a^b 6
~ Bitwise NOT ~a -6
<< Left shift a << 1 10
>> Right shift a >> 1 2
>>> Unsigned right shift -5 >>> 1 large positive number
class BitwiseDemo {
public static void main(String[] args) {
int a = 10, b = 3;
[Link]("a & b: " + (a & b));
[Link]("a | b: " + (a | b));
[Link]("a ^ b: " + (a ^ b));
[Link]("~a: " + (~a));
[Link]("a << 1: " + (a << 1));
[Link]("a >> 1: " + (a >> 1));
[Link]("-5 >>> 1: " + (-5 >>> 1));
}
}
7. Conditional (Ternary) Operator
Definition: A shorthand way of writing if-else.
Use: Returns one value if condition is true, another if false.
Operator Name Example Result
?: Ternary Operator (age >= 18) ? "Adult" : "Minor" "Adult"
class TernaryDemo {
public static void main(String[] args) {
int age = 18;
String result = (age >= 18) ? "Adult" : "Minor";
[Link]("Age check: " + result);
}
}
8. Type Cast Operator
Definition: Converts one data type into another.
Use: Data type conversion.
Operator Name Example Result
(type) Type casting (int)9.8 9
class TypeCastingDemo {
public static void main(String[] args) {
double d = 9.78;
int castInt = (int) d;
[Link]("Original double: " + d);
[Link]("After casting to int: " + castInt);
}
}
9. Instanceof Operator
Definition: Checks whether an object belongs to a particular class.
Use: Type checking at runtime.
Operator Name Example Result
instanceof Instance check s instanceof String true
class InstanceofDemo {
public static void main(String[] args) {
String str = "Hello";
[Link]("str instanceof String: " + (str instanceof String));
}
}
10. Special Operators
Definition: Operators used for special purposes in Java.
Use: Access objects, methods, parent class, etc.
Operator Name Example Use
. Dot operator [Link]() Access members
new Object creation new Student() Creates object
this Current object [Link] Refers to current instance
super Parent class reference [Link]() Calls parent method
-> Lambda operator (a,b)->a+b Defines lambda
:: Method reference [Link]::println Refers to a method
class SpecialDemo {
public static void main(String[] args) {
Student s = new Student("Raj"); // new operator
[Link](); // dot operator
}
}
class Student {
String name;
Student(String name) {
[Link] = name; // this operator
}
void show() {
[Link]("Student name: " + [Link]);
}
}
🔹 Control Structures in Java
Control structures determine the flow of execution in a Java program. They are mainly of
two types:
1. Selection (Decision-making) or Conditional Statements → choosing among
alternatives.
2. Looping (Iteration) → repeating tasks.
3. Jump Statements (inside loops)
1️⃣ Selection (Decision-Making) Statements
Used to decide which block of code should run based on conditions.
(a) if statement
Executes a block only if condition is true.
int age = 20;
if(age >= 18) {
[Link]("You can vote");
}
(b) if-else statement
Chooses between two alternatives.
int number = 5;
if(number % 2 == 0) {
[Link]("Even");
} else {
[Link]("Odd");
}
(c) if-else-if ladder
Checks multiple conditions in sequence.
int marks = 75;
if(marks >= 90) {
[Link]("Grade A");
} else if(marks >= 75) {
[Link]("Grade B");
} else if(marks >= 50) {
[Link]("Grade C");
} else {
[Link]("Fail");
}
(d) Nested if
An if inside another if.
int a = 10, b = 20, c = 30;
if(a < b) {
if(b < c) {
[Link]("a < b < c");
}
}
(e) switch-case
Selects one block from multiple choices.
Works with int, char, String, enum.
Uses break to exit case.
int day = 3;
switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
case 3: [Link]("Wednesday"); break;
default: [Link]("Invalid day");
}
2️⃣ Looping (Iteration) Statements
Used to repeat execution of a block of code.
(a) for loop
Runs block for a fixed number of times.
for(int i=1; i<=5; i++) {
[Link]("Hello " + i);
}
(b) while loop
Runs while condition is true (condition checked before execution).
int i = 1;
while(i <= 5) {
[Link](i);
i++;
}
(c) do-while loop
Runs at least once (condition checked after execution).
int i = 1;
do {
[Link](i);
i++;
} while(i <= 5);
(d) Enhanced for loop (for-each)
Used to iterate through arrays/collections.
int[] numbers = {10, 20, 30, 40};
for(int num : numbers) {
[Link](num);
}
3️⃣ Jump Statements (inside loops)
break → exits loop/switch.
continue → skips current iteration, goes to next.
for(int i=1; i<=5; i++) {
if(i == 3) continue; // skips 3
if(i == 5) break; // exits loop
[Link](i);
}
✅ Summary Table
Category Statement Purpose
Selection if, if-else, if-else-if, nested if Decision making
Selection switch-case Multi-way branching
Looping for, while, do-while Repetition
Looping for-each Easy array/collection iteration
Control break, continue Alter loop flow