0% found this document useful (0 votes)
0 views34 pages

Java Revision

The document provides comprehensive notes on Java programming, covering its introduction, history, features, and key components like JVM, JRE, and JDK. It details programming concepts such as classes, objects, methods, decision-making statements, loops, and exception handling, along with the differences between Java and C++. Additionally, it discusses advanced topics like generics, collections, and file handling, making it a thorough resource for understanding Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views34 pages

Java Revision

The document provides comprehensive notes on Java programming, covering its introduction, history, features, and key components like JVM, JRE, and JDK. It details programming concepts such as classes, objects, methods, decision-making statements, loops, and exception handling, along with the differences between Java and C++. Additionally, it discusses advanced topics like generics, collections, and file handling, making it a thorough resource for understanding Java.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

JAVA Micro Notes

UNIT – I
Introduction to Java
Programming
 Process of giving instructions to computer.
 Converts logic into machine actions.
 Uses programming languages.
 Used in apps, websites, systems.

History of Java
 Developed by James Gosling and team.
 Released in 1995.
 Initially for electronic devices.
 Later used for web & mobile apps.
 Platform independent.
 WORA = Write Once Run Anywhere.

Features of Java
 Platform Independent → runs on any OS.
 Object Oriented → based on classes & objects.
 Secure → JVM provides security.
 Robust → handles memory/errors.
 Multithreaded → multiple tasks together.
 Portable → easy to move between systems.

Java Technology & Platform


 Java Technology → tools + systems for developing apps.
 Java Platform → environment using JVM + libraries.
JVM, JRE, JDK
JVM (Java Virtual Machine)
Functions:
 Executes bytecode
 Converts bytecode to machine code
 Memory management
 Security
JRE (Java Runtime Environment)
 Provides runtime environment to execute Java programs.
JDK (Java Development Kit)
 Used to write + run Java programs.
Flow:
Java Program → JDK → JRE → JVM → OS

First Java Program


class Hello {
public static void main(String args[]) {
[Link]("Hello Java");
}
}
Output:
Hello Java

Difference Between C++ & Java


C++
 Compiled language
 Converts directly into machine code
 Platform dependent
 Faster execution
Java
 Compiles into bytecode
 Bytecode executed by JVM
 Platform independent
 Slightly slower
Flow:
C++ → Source → Compiler → Machine Code
Java → Source → Compiler → Bytecode → JVM → Machine Code

Classes & Objects


Class
 User-defined datatype.
 Blueprint for objects.
Features:
 Contains variables + methods
 Defines properties + behavior
 Memory allocated only after object creation
 Implements OOP concepts

Object
 Instance of class.
 Represents real-world entity.
Features:
 Occupies memory
 Access class members
 Represents actual data
 Multiple objects possible

Instantiation
 Creating object of class using new.
Example:
Student s = new Student();

Variables
 Named memory location.
Features:
 Stores data
 Value can change
 Must be declared before use
 Associated with datatype

Naming Rules
 Use camelCase
 Start with letter, _ or $
 No spaces
 Cannot start with number
 No keywords
 Case sensitive

Primitive Variables / Datatypes

Type Meaning

int Integer

float Decimal

double Large decimal

char Single character

boolean true/false

byte Small integer

short Medium integer

long Large integer

Features:
 Stores actual values
 Faster processing
 Less memory
 Built-in datatypes

Scope of Variables
Local Variable
 Declared inside method/block.
 Accessible only there.
 Destroyed after execution.
Instance Variable
 Declared inside class.
 Each object has copy.
 Accessed using object.
Static Variable
 Declared using static.
 Shared among all objects.
 Memory allocated once.

Garbage Collection
 Automatic destruction of unused objects.
Managed by JVM.
Advantages:
 Frees memory
 Improves performance
 Prevents memory leaks
Garbage created when:
 Reference = null
 Reference reassigned
 Anonymous object
Request GC:
[Link]();

Datatypes
Primitive
 int, float, char etc.
Non-Primitive
 Arrays
 Classes
 Objects
 Strings

Operators
Arithmetic
+-*/%
Relational
== != > < >= <=
Logical
&& || !
Assignment
= += -=
Unary
++ --

Source File Declaration Rules


 File name = public class name
 .java extension compulsory
 Multiple classes allowed
 Only one public class allowed
 main() required in execution class

Class Naming Rules


 Start with capital letter
 Use CamelCase
 No spaces
 No keywords
 Meaningful names
Examples:
 StudentName
 BankAccount

Method Naming Rules


 Start with lowercase
 camelCase
 Represent action
Example:
calculateMarks()

UNIT – II
Decision Making Statements
if Statement
 Executes code when condition TRUE.
Syntax:
if(condition){
statements;
}
if-else Statement
 Executes one block when TRUE and another when FALSE.
if(condition){
}
else{
}

if-else-if Ladder
 Multiple conditions checked sequentially.
if(cond1){
}
else if(cond2){
}
else{
}

Nested if
 if inside another if.
Used for multiple dependent conditions.

Ternary Operator ?:
Short form of if-else.
int max = (a>b) ? a : b;
Features:
 Uses 3 operands
 Returns one value
 Compact code

switch Case
switch(variable){
case value:
statements;
break;

default:
statements;
}
Features:
 Multiple conditions
 Uses break
 Alternative to ladder

Loops
for Loop
Used when iterations known.
for(initialization; condition; increment){
}

while Loop
Condition checked before execution.
while(condition){
}

do-while Loop
Executes at least once.
do{
}
while(condition);
Jump Statements
break
 Terminates loop immediately.
continue
 Skips current iteration.

UNIT – III
Methods
 Block of code performing task.
Features:
 Reusable
 Improves modularity
Types:
 With return type
 Without return type

Constructors
 Special method initializing objects.
Characteristics:
 Same name as class
 No return type
 Called automatically
Types:
 Default constructor
 Parameterized constructor

Method Overloading
 Same method name with different parameters.
Features:
 Compile-time polymorphism

Constructor Overloading
 Multiple constructors with different parameters.

Method Overriding
 Subclass redefines superclass method.
Features:
 Runtime polymorphism

Static Members
 Belong to class.
 Shared among objects.

final Keyword
Used with:
 Variables
 Methods
 Classes
Cannot be modified/overridden.

super Keyword
 Refers parent class object.
 Access parent variables/methods/constructors.

Inheritance
 One class acquires properties of another.
Types mentioned:
 Single inheritance
UNIT – IV
Wrapper Classes
Convert primitive datatype into objects.

Primitive Wrapper

int Integer

float Float

double Double

boolean Boolean

char Character

byte Byte

short Short

long Long

Features:
 Autoboxing
 Used in collections
 Utility methods

Datatypes Classification
Primitive
 byte
 short
 int
 long
 float
 double
 char
 boolean
Non-Primitive
 String
 Array
 Class
 Object
 Interface

Conversion & Utility Methods


String → Primitive
[Link]()
[Link]()
[Link]()
Primitive → String
[Link]()
[Link]()
Wrapper → Primitive
intValue()
doubleValue()
floatValue()

Utility Methods
 valueOf()
 compareTo()
 max()
 min()
 toString()

Typecasting
Implicit (Widening)
 Automatic
 Small → large
Example:
int → long
Explicit (Narrowing)
 Manual
 Large → small
Example:
double → int

String Class
Features:
 Non-primitive
 Immutable
 Stored in String Pool
 Package: [Link]
Methods:
 length()
 isEmpty()
 toLowerCase()
 toUpperCase()
 charAt()
 equals()
 substring()

Arrays
Array
Stores multiple values of same datatype.
Characteristics:
 Same datatype
 Fixed size
 Indexed
 Contiguous memory

Types
1D Array
Linear collection.
2D Array
Rows & columns.

Array Declaration
int arr[];
Array Creation
arr = new int[5];
Array Initialization
arr[0] = 10;

Array of Objects
 Array storing objects.

UNIT – V
String Class
String
Sequence of characters.
Created using:
String s = "Hello";
or
String s = new String("Hello");
SCP (String Constant Pool)
 Special heap area storing string literals.

String Methods
 length()
 charAt()
 concat()
 equals()
 substring()
 toUpperCase()
 toLowerCase()

String Handling
Operations:
 Creation
 Manipulation
 Comparison
 Modification

String Classes
String
 Immutable
StringBuffer
 Mutable
 Thread safe
StringBuilder
 Mutable
 Faster
 Not thread safe
Exception Handling
Exception
Unexpected event disrupting normal flow.
Causes:
 Divide by zero
 Null access
 Array index out of bounds
 Invalid input

Exception Handling
Mechanism to detect & handle runtime errors.
Keywords:
 try
 catch
 finally
 throw
 throws

Exception vs Error
Exception
 Runtime problem
 Can be handled
Error
 Serious system issue
 Cannot be handled easily

UNIT – VI
Packages
Package
Collection of related classes/interfaces.
Advantages:
 Organized code
 Avoid naming conflicts
 Reusability

Import Statements
import package.*;
import [Link];
Types:
 Single class import
 Entire package import
 Static import

Creating Package
package mypack;

JAR Files
JAR
Compressed file containing classes/resources.
Advantages:
 Small size
 Easy deployment

Abstract Class
 Declared using abstract.
 Cannot instantiate.
Abstract Method
 No body/implementation.
Rules:
 Must override in subclass.
 Subclass implements abstract methods.

Interface
Features:
 Achieves abstraction
 Supports multiple inheritance

Multiple Interface Implementation


Class can implement multiple interfaces.
Benefits:
 Flexibility
 Loose coupling
 Code reusability

UNIT – VII
File Class
Package:
[Link]
Methods:
 createNewFile()
 exists()
 delete()
 getName()
 length()
 mkdir()
Reading & Writing Files
Used for storing/retrieving data.
Importance:
 Data persistence

BufferedReader & BufferedWriter


 Improves file handling efficiency.
Advantages:
 Faster than FileReader/FileWriter
 Good for large files

Object Serialization
Converting object into byte stream.
Purpose:
 Save/transmit objects

Scanner Class
Package:
[Link]
Methods:
 nextInt()
 nextDouble()
 next()
 nextLine()
 hasNext()
Advantages:
 Easy input handling
 Reads different datatypes
Threads
Thread
Lightweight process.
Advantages:
 Multitasking
 Better CPU utilization

Creating Threads
1. Extending Thread class
2. Implementing Runnable interface

Thread Class Methods


 start()
 run()
 sleep()
 setPriority()

Runnable Interface
Preferred because Java supports single inheritance.

Thread States
1. New
2. Runnable
3. Running
4. Blocked/Waiting
5. Terminated

Thread Priorities
Range:
 MIN_PRIORITY = 1
 NORM_PRIORITY = 5
 MAX_PRIORITY = 10

Generics
Allows datatype safety.
Advantages:
 Reusable code
 Compile-time checking

Generic Methods
Works with multiple datatypes.
Example:
<T> void display(T data)

Synchronization
Controls shared resource access in multithreading.
Prevents:
 Data inconsistency

Collections Framework
Stores/manipulates groups of objects.
Interfaces:
 List
 Set
 Queue
 Map
Classes:
 ArrayList
 LinkedList
 Vector
 HashSet
 HashMap
 PriorityQueue

Collection API
Framework in [Link] package.

Array vs Collection

Array Collection

Fixed size Dynamic size

Faster Flexible

Less overhead More features

List
ArrayList
 Dynamic array
 Fast random access
 Not synchronized
LinkedList
 Doubly linked list
 Faster insertion/deletion
Vector
 Synchronized
 Slower than ArrayList

Queue
FIFO structure.
PriorityQueue
 Elements ordered by priority.

Map
Stores key-value pairs.

SortedMap
 Maintains sorted keys.

HashMap vs SortedMap

HashMap SortedMap

No ordering Sorted keys

Implemented using hashing Implemented using tree

UNIT – I
1. Java Program Execution Flow
Java Source Code (.java)

Compiler
(javac)

Bytecode (.class)

JVM

Machine Code

Output

2. JDK – JRE – JVM Relationship


JDK
----------------
| |
| JRE |
| ---------- |
| | JVM | |
| ---------- |
----------------
Remember:
 JDK → Development
 JRE → Running programs
 JVM → Executes bytecode

3. Difference Flow: C++ vs Java


C++
Source Code

Compiler

Machine Code

Output
Java
Source Code

Compiler

Bytecode

JVM

Machine Code

Output

4. Class & Object Diagram


CLASS
-----------------
| variables |
| methods |
-----------------

Object Creation

OBJECT
Example:
Class → Student
Object → s1, s2

5. Memory Allocation of Variables


LOCAL VARIABLE
→ Inside method
→ Temporary memory

INSTANCE VARIABLE
→ Separate copy for each object

STATIC VARIABLE
→ Shared among all objects

6. Garbage Collection
Object Created

Object Unused

No Reference Exists

Garbage Collector

Memory Freed

UNIT – II
Decision Making & Loops

7. if Statement Flowchart
Condition
/ \
True False
| |
Statements End

8. if-else Flowchart
Condition
/ \
True False
| |
if block else block
\ /
End

9. if-else-if Ladder
Condition1 ?
/ \
T F
| ↓
Block1 Condition2 ?
/ \
T F
| |
Block2 Else Block

10. switch Case Diagram


Variable

-----------------
| case 1 |
| case 2 |
| case 3 |
| default |
-----------------

11. for Loop Flowchart


Initialization

Condition
/ \
True False
| |
Statements End

Increment

Condition again

12. while Loop


Condition
/ \
True False
| |
Statements End
|
Condition Again

13. do-while Loop


Statements

Condition
/ \
True False
| |
Repeat End

14. break vs continue


break
Loop

Condition Met

Exit Loop
continue
Loop

Condition Met

Skip Current Iteration

Next Iteration

UNIT – III
15. Constructor Working
Object Creation

Constructor Called

Variables Initialized

16. Method Overloading


Same Method Name

Different Parameters

Compile-Time Polymorphism
Example:
add(int a, int b)

add(int a, int b, int c)

17. Method Overriding


Superclass Method

Subclass Redefines Method

Runtime Polymorphism

18. Inheritance Diagram


Parent Class

|
Child Class
Example:
Animal

Dog

UNIT – IV
19. Primitive vs Non-Primitive Datatypes
DATATYPES
/ \
Primitive Non-Primitive
/| \ / | \
int char ... Array String Object

20. Typecasting
Widening
small datatype → large datatype
int → long
Narrowing
large datatype → small datatype
double → int

21. Array Memory Representation


1D Array
Index → 0 1 2 3
Array → [10][20][30][40]

2D Array
Column
0 1
----------
0| 1 2
1| 3 4

UNIT – V
22. String Constant Pool (SCP)
HEAP MEMORY
-------------------
| String Pool |
| "Java" |
| "Hello" |
-------------------

23. Exception Handling Flow


try Block

Exception Occurs?
/ \
Yes No
| |
catch Block Normal Flow

finally Block

24. Exception Hierarchy


Throwable
/ \
Error Exception

UNIT – VI
25. Package Structure
Package

Classes

Methods
Example:
[Link]
[Link]

26. Abstract Class & Interface


Abstract Class
Abstract Class

Can Have:
✔ Abstract methods
✔ Normal methods
Interface
Interface

Only abstract methods
(Traditionally)

27. Multiple Interface Implementation


Interface A Interface B
\ /
\ /
\ /
Child Class

UNIT – VII
28. File Handling Flow
Program

File Open

Read / Write

Close File

29. Object Serialization


Object

Byte Stream

Stored in File
Deserialization:
Byte Stream

Object Restored

30. Thread Lifecycle Diagram


NEW

RUNNABLE

RUNNING

BLOCKED/WAITING

TERMINATED

31. Thread Creation Methods


THREAD
/ \
Extending Implementing
Thread Runnable

32. Collection Framework Hierarchy


Collection
/ | \
List Set Queue
|
------------------------
| | |
ArrayList LinkedList Vector

33. Map Hierarchy


Map
|
HashMap
|
SortedMap
34. Queue (FIFO)
INSERT → [10][20][30] → DELETE

First In → First Out

35. Stack (LIFO) (Helpful extra)


30 ← TOP
20
10

Last In → First Out

36. Array vs Collection


ARRAY
- Fixed size
- Faster
- Less flexible

COLLECTION
- Dynamic size
- Flexible
- More features

You might also like