Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
6 views162 pages

Java

The document provides a comprehensive overview of Java, including its features, components like JVM, JRE, and JDK, and fundamental concepts such as syntax, data types, variables, operators, and control structures. It also covers object-oriented programming principles, including classes, inheritance, polymorphism, abstraction, encapsulation, and access modifiers. Additionally, it includes practical examples like a mini calculator program and discusses advanced topics such as garbage collection and string manipulation.

Uploaded by

rameswari489
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views162 pages

Java

The document provides a comprehensive overview of Java, including its features, components like JVM, JRE, and JDK, and fundamental concepts such as syntax, data types, variables, operators, and control structures. It also covers object-oriented programming principles, including classes, inheritance, polymorphism, abstraction, encapsulation, and access modifiers. Additionally, it includes practical examples like a mini calculator program and discusses advanced topics such as garbage collection and string manipulation.

Uploaded by

rameswari489
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 162

Java Full Portion

Basic - Advanced

Subbiah Pillai P
1. What is Java?

Java is a programming language used to build:

• Mobile apps (like Android apps),

• Websites (like Amazon, IRCTC),

• Desktop software (like Calculator),

• Games,

• ATM software, etc.

Features of Java:

• Simple – Easy to learn and use

• Object-Oriented – Based on real-world objects (we will learn soon)

• Platform-Independent – You write code once, it can run on Windows, Linux, Mac, etc.

• Secure – It has many built-in security features

• Robust – Java can handle errors well and avoids crashing

Real World Example:


Imagine you're writing a book. If you write it in English, any English reader can read it. Same way,
Java code (bytecode) can be read by any computer using JVM.

2. What is JVM (Java Virtual Machine)?

JVM is the engine that runs Java programs.

• It takes the .class file (bytecode)

• Converts it into machine code

• Runs the program on your system (Windows, Mac, Linux)

Why JVM is Special:

• JVM is different for Windows, Linux, etc.

• But it understands the same bytecode

• That’s why Java is platform-independent

Example:
Like a translator who reads one language (bytecode) and speaks in your local language (machine
code).
3. What is Bytecode?

Bytecode is a special code created by Java compiler.

How is it created?

1. You write a Java file → MyProgram.java

2. You compile it → creates MyProgram.class (this is bytecode)

• .java → is your code

• .class → is the bytecode

JVM reads .class file and runs it

Think like this:

• You write a recipe in English (.java)

• You translate it into a cooking script (.class)

• The kitchen (JVM) reads that cooking script and makes food (runs your code)

4. What is JIT (Just-In-Time Compiler)?

JIT is a small part inside JVM. It helps your program run faster.

• While JVM is running the program,

• JIT converts bytecode into machine code quickly

• It stores it in memory so the code doesn't need to be translated again

Think like this:


If you repeat a task many times, JIT helps JVM to remember it and reuse, which saves time.

5.What is JRE (Java Runtime Environment)?

JRE is needed to run Java programs.

JRE Contains:

• JVM (Java Virtual Machine)

• Library Files (pre-written Java code)

Example:
If your friend made a Java game, and you just want to play it, you only need JRE. You don’t need JDK
if you're not writing code.
6. What is JDK (Java Development Kit)?

JDK is a full setup to create and run Java programs.

JDK Contains:

• JRE (Java Runtime Environment)

• Compiler (javac)

• Tools (for debugging, documentation, etc.)

What you can do with JDK:

• Write Java programs

• Compile them (turn your code into machine language)

• Run them

Example:
You install JDK if you're a Java developer.

Complete (Real-Time Flow):

1. You write a Java file: Hello.java

2. You compile it: javac Hello.java → creates Hello.class

3. JVM takes Hello.class

4. JIT helps run it faster

5. You see the result on screen!


Java Syntax
Syntax means rules you must follow while writing Java code.

Basic Java Syntax Rules:

• Java code must be inside a class

• Code runs from the main method

• Every statement ends with semicolon ;

• Curly brackets { } are used to group code

• Java is case-sensitive (Example: Main and main are not the same)

What is a Data Type?


• Data type means:
What type of value you are storing in a variable.
Example:

• int age = 25;

• Here, int is the data type — it tells Java to store a whole number.

Types of Data Types in Java


• Java has two main types of data types:

1. Primitive Data Types

2. Non-Primitive Data Types

Primitive Data Types (8 types)

These are basic and fixed-size data types in Java.


Non-Primitive Data Types

These are more advanced. Not fixed-size. We can create or customize them.

Variables in Java
A variable is a container used to store values.

int age = 25; // age is variable

float price = 99.99f; // price is variable

char grade = 'A'; // grade is variable

boolean isPassed = true; // isPassed is variable

String name = "Subbiah"; // name is variable

Rules for Variable Names:

• Must start with a letter (A–Z or a–z), or (_ or $)

• Cannot start with a number

• Cannot use Java keywords like int, class as names

Operators:
Operators are special symbols in Java that perform operations on variables and values. They
are fundamental to programming logic.
1. Arithmetic Operators
2. Relational Operators
3. Logical Operators
4. Assignment Operators
5. Unary Operators
6. Bitwise Operators
7. Ternary Operators
Typecasting
Input in Java
Java doesn’t have cin or scanf like C/C++. Instead, we use:

a. Scanner (Most commonly used)

b. BufferedReader (Faster, used when handling large input)


Comments in Java
What is a Comment?
A comment is a line of text in code that Java will ignore during execution.

Used to:
• Explain what the code is doing
• Add notes/reminders
• Disable code temporarily (for debugging)
Java Naming Conventions
Java has rules + best practices for naming classes, variables, methods, etc.

Why use naming conventions?


• Improves readability
• Makes code look clean and standard
• Required for large team projects and interview
Mini Calculator Using switch in Java

import java.util.Scanner;

public class MiniCalculator {


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

// Input first number


System.out.print("Enter first number: ");
double num1 = sc.nextDouble();

// Input second number


System.out.print("Enter second number: ");
double num2 = sc.nextDouble();
// Input operator
System.out.print("Choose operation (+, -, *, /, %): ");
char operator = sc.next().charAt(0);

double result;

// Switch based on operator


switch (operator) {
case '+':
result = num1 + num2;
System.out.println("Result: " + result);
break;
case '-':
result = num1 - num2;
System.out.println("Result: " + result);
break;
case '*':
result = num1 * num2;
System.out.println("Result: " + result);
break;
case '/':
if (num2 == 0) {
System.out.println("Error: Division by zero");
} else {
result = num1 / num2;
System.out.println("Result: " + result);
}
break;
case '%':
if (num2 == 0) {
System.out.println("Error: Modulus by zero");
} else {
result = num1 % num2;
System.out.println("Result: " + result);
}
break;
default:
System.out.println("Invalid operator!");
}

sc.close(); // good practice to close Scanner


}
}
Loops in Java
Loops help you run a block of code multiple times.

Three types of loops:


1. for loop
2. while loop
3. do-while loop

1. for Loop
Definition:
The for loop is used when number of iterations is known.

Syntax:

for (initialization; condition; update)


{

// block of code

}
Flow:
1. Initialize variable
2. Check condition
3. Run block
4. Update (increment/decrement)
5. Repeat until condition is false

2. while Loop
Definition:
The while loop is used when you don’t know how many times the
loop should run — only when a condition is true.

Syntax:

while (condition) {

// block of code

}
Flow:

1. Check condition
2. If true → run block
3. Go back and check again
4. Stops when condition is false

3. do-while Loop
Definition:

do-while is like while — but it runs the block at least once, even if the
condition is false.
Syntax:
do {

// block of code

} while (condition);
break, continue, and return in Java
These are used to change the normal flow of execution inside loops or
methods.

1. break
Definition:

break is used to exit from a loop (or switch) immediately, even if the
loop condition is still true.
Usage:
• To stop a loop early
• To exit a switch case
2. continue
Definition:

continue skips the current iteration of the loop and jumps to the next
iteration.
Usage:

• When you want to skip some values but not break the loop
3. return
Definition:

return is used to exit from a method and optionally return a value to


the caller.
Usage:

• To stop execution inside a method


• To send a result to the place where the method was called
Object-Oriented Programming (OOP) in Java:

1. What is a Class?
Definition:

A class is like a blueprint or template that defines the structure and


behaviour of objects.
It contains:
• Fields (variables) — data
• Methods (functions) — actions
Constructor in Java
Definition:
A constructor is a special method that runs automatically when you create an
object using new.

Purpose:
• Initialize objects (set default values)
• Looks like a method, but name = class name
• No return type (not even void)
this Keyword
Definition:
this refers to the current object (the object that is calling the
method or constructor).

Use Cases:
1. To refer to current class variables
2. To call current class methods
3. To call another constructor inside same class

Example 1: Resolving variable name conflict

Explanation:
• When you do Student s = new Student("Ravi");,
the constructor is called with "Ravi" as the parameter.
• this.name = name; assigns "Ravi" to the class variable name.
• s.show(); prints "Name: Ravi".
Example 2: Calling another constructor using this()

Summary:
• this() is used to call another constructor inside the same class.
• Must be the first statement in the constructor.
• Helps to reuse constructor logic and avoid code duplication.
super Keyword
Definition:
super refers to the parent class (superclass)

Use Cases:
1. To access parent class methods or variables
2. To call parent class constructor
What is Inheritance?
Inheritance is the process where one class (child/subclass) inherits the
properties and behaviors (fields and methods) of another class
(parent/superclass).

Why use inheritance?


• Code Reusability: You don’t need to rewrite the same code in multiple
classes.
• Improved Structure: You can organize shared code in parent classes.
• Polymorphism: Allows method overriding and dynamic method
dispatch.
Important Notes:
1. Every class in Java implicitly extends Object class.
2. Constructor of parent class is automatically called before child constructor.
3. Private members are not inherited.
4. Use super to access parent methods or constructors.
5. Use @Override to override parent methods in child.
1. Compile-Time Polymorphism ( Method Overloading
What is Method Overloading?
• When multiple methods have the same name, but different parameters
(type, number, or order) in the same class.
• The method call is resolved at compile time.
2. Runtime Polymorphism ( Method Overriding)
What is Method Overriding?
• When a child class provides its own version of a method that is already
present in the parent class.
• Method is chosen at runtime using the actual object type, not reference
type.
What is Abstraction?
Abstraction means hiding complex details and showing only the necessary
parts to the user.
• It helps to reduce complexity.
• Focus only on what an object does, not how it does it.

How do we achieve abstraction in Java?


Two ways:
1. Abstract Classes
2. Interfaces

Abstract Class

What is an abstract class?


• A class declared with keyword abstract.
• Can have abstract methods (methods without body) and concrete
methods (with body).
• Cannot create an object of abstract class directly.
• Child class must implement abstract methods (unless child class is
abstract too).
Explanation (in comments):
• abstract void sound(); means all subclasses must provide their own
sound() implementation.
• sleep() method has a body and can be used by subclasses directly.
• You cannot create object of abstract class directly.
• The subclass (Dog) implements the abstract method sound().
Interface
What is an interface?
• A 100% abstract type (before Java 8).
• Can contain only abstract methods (before Java 8) and constants.
• Java 8+ allows default and static methods in interfaces.
• A class can implement multiple interfaces (helps achieve multiple
inheritance).
What is Encapsulation?
Encapsulation is the process of wrapping data (variables) and methods
together as a single unit (class), and restricting direct access to some
components of an object.

Real-Life Example:
Think of a bank account:
• You cannot access the balance directly.
• You must use methods like getBalance() and deposit(amount).
Access Modifiers in Java

Access modifiers control the visibility of:


• Classes
• Methods
• Variables
• Constructors
They decide where a member can be accessed from (within same class,
package, or outside).
Arrays in Java

Including:

• 1D Arrays (One-Dimensional)

• 2D Arrays (Two-Dimensional)

• Jagged Arrays (Irregular 2D arrays)

What is an Array?
An array is a collection of elements (same type), stored in consecutive
memory locations.
• Fixed size (you decide size at creation)
• Index-based (starts from 0)
• Can be 1D, 2D, or more
Array Sorting and Searching
Sort in Descending Order (manual way):
Java’s Arrays.sort() does not sort primitives in descending directly. We can:
• Use reverse loop after sort
• OR use Collections.reverseOrder() with Integer[]
Array Searching
1. Linear Search (Normal search)
• Works on unsorted or sorted arrays
• Time complexity: O(n)
//Linear search start here

2. Binary Search (Only for sorted arrays)


• Much faster: O(log n)
• Uses Arrays.binarySearch(array, key)
2. StringBuilder in Java (java.lang.StringBuilder)
What is StringBuilder?
• Used to modify strings without creating new objects.
• It is mutable.
• Faster than String in loops.
• Not thread-safe (means not safe for multithreaded apps).
3. StringBuffer in Java (java.lang.StringBuffer)
• Same as StringBuilder
• But it is thread-safe
• Slightly slower than StringBuilder
What is Garbage Collection?
Garbage Collection (GC) in Java is the process of automatically freeing
memory by removing unused objects from the Heap.

Java takes care of memory management for you!

Why is it needed?
In languages like C/C++, the programmer must manually release memory using
free() or delete.
But in Java:
• When an object is no longer used (no references),
• It becomes eligible for garbage collection
• JVM's Garbage Collector will delete it to free memory.
Note: finalize() method is not guaranteed to run immediately. It's called by
JVM before object is collected.
finalize() Method
What is it?
• A special method in Java called by the Garbage Collector before
destroying an object.
• Used to clean up resources (like closing files, DB connections) — but not
recommended in modern Java (deprecated in Java 9).
Exception Handling in Java

What is an Exception?
An exception is a runtime error that can stop your program if not handled.
Examples:
• Dividing by zero
• Accessing invalid array index
• Using null reference
Explanation of Each Block:
try
• Put risky code here
• Like division, file opening, etc.

catch
• Handles the exception
• You can print message, log it, or do alternative logic

finally
• Always runs
• Used to close resources (file, DB, etc.)
• Even if exception occurs or not
throw vs throws in Java
They both deal with exceptions, but they are completely different in usage
and purpose.
2. Custom Exceptions in Java
When built-in exceptions are not enough, we can create our own exception
classes.

How to Create Custom Exception?


1. Extend the Exception class → for Checked exception

2. Extend RuntimeException → for Unchecked exception


Wrapper Classes in Java
Integer, Double, Character, etc.
Autoboxing & Unboxing
Java Collections Framework

1. What is Java Collections Framework?


Java Collections Framework (JCF) is a set of interfaces and classes that provide
powerful ways to store, retrieve, and manipulate groups of objects
(collections).

Why Use It?


• No need to write your own data structure logic
• Provides reusable, efficient implementations (List, Set, Map, Queue)
• Helps you organize, search, sort, and manage data easily
1. What is Set?
• Set is a child interface of Collection
• Used to store unique elements only
• No indexing, so no .get(index) like in List
What is Map?
A Map stores data in key-value pairs where:
• Keys must be unique
• Values can be duplicated
• You use get(key) to fetch values
Map is not a child of Collection.
What is Queue?
• A Queue is a collection that stores elements in order, typically First In
First Out (FIFO).
• It is part of the Java Collections Framework.
• Defined in java.util.Queue interface.
Additional Info
1. Iterator
• Used to loop through collections
• Works with Set, List, Queue
• Can remove elements while iterating
• Only works forward

2. ListIterator
• Works only on List (ArrayList, LinkedList)
• Can go forward and backward
• Can add, remove, update during traversal
3. Enumeration (Legacy - old version)
• Used only for legacy classes like Vector, Hashtable
• Read-only
• Only forward direction
Sorting and Filtering Examples
What is Stream API?
• Stream API helps you process collections (List, Set) in a functional style
• Doesn’t modify the original list
• You can use operations like:
filter(), map(), collect(), forEach(), count(), sorted(), etc.
Java 8 Date and Time API — specifically:
• LocalDate

• LocalTime

• LocalDateTime

• Period

• Duration
These classes are found in the package java.time.*
5. Duration – Difference between two LocalTime or LocalDateTime (in
hours, minutes, seconds)
What is Multithreading?
Multithreading means running multiple parts of a program at the same time
(concurrently).
For example: downloading a file and showing progress bar both at the same
time.
What is Thread Safety?
Thread safety means:
“When multiple threads access a shared resource (like a variable, file, or
object), it behaves correctly and predictably.”
In thread-safe code, you will not get wrong or corrupted results even when
multiple threads access it at the same time.
Expected Output: 2000
Real Output: Varies like 1782, 1954, etc.

Because count++ is not atomic (it's actually 3 operations: read → add →


write).
What is Deadlock?
Deadlock is a situation where two or more threads are blocked forever,
waiting for each other to release the lock.
In simple words:
Thread A holds Lock 1 and waits for Lock 2.
Thread B holds Lock 2 and waits for Lock 1.
Both are stuck forever!

Real-Life Analogy
Imagine:

• Person A has Key1 and wants Key2 to enter a room.

• Person B has Key2 and wants Key1.


• Both refuse to let go. They wait forever.
How to Prevent Deadlock

1. Lock Ordering
Always acquire locks in the same order in all threads.
3. Avoid Nested Locks
Avoid using one lock inside another lock, if possible.

4. Use Timed Waiting


Example: tryLock(timeout) in ReentrantLock

What is a Race Condition?


A Race Condition occurs when two or more threads access shared data and try
to change it at the same time. Because thread execution order is
unpredictable, the final result becomes inconsistent.

Example of Race Condition


Let’s say two threads are trying to increment a counter variable from 0 to
1000.
Sometimes you may get:
• 1956
• 1990

• 2000 (rare, but possible)

• 1883
Because count++ is not atomic, both threads may:
• Read the same value at the same time
• Increment it
• Write back an outdated value
ExecutorService, Callable, and Future in Java
Java provides a modern and powerful way to handle threads using
the java.util.concurrent package. The main concepts here are:

1. ExecutorService
What is it?
ExecutorService is an interface used to manage and control thread
pools. It separates task submission from thread creation and
execution.
Byte Stream
Reads/Writes data in bytes (8 bits)
• Handles any type of data (binary or text)
• Not character-aware (no encoding handled)
• Base classes: InputStream and OutputStream

Common Classes:
• FileInputStream
• FileOutputStream
• BufferedInputStream
• BufferedOutputStream
Character Stream
Reads/Writes data in characters (16 bits)
• Specifically designed for text data
• Handles encoding (like UTF-8, UTF-16) automatically
• Base classes: Reader and Writer

Common Classes:
• FileReader
• FileWriter
• BufferedReader
• BufferedWriter
Why Use It?
• To save an object’s state to a file
• To transfer objects between systems (e.g., over a network)
• To store object in a database or cache
Real Use Cases
• Storing session state (e.g., in web apps)
• Messaging: Send Java objects through network (like RMI, sockets)
• Caching: Save object states in serialized form
• Saving game progress in desktop apps

JDBC (Java Database Connectivity)


JDBC allows Java applications to connect and interact with databases like
MySQL, Oracle, PostgreSQL, etc.

JDBC Workflow Steps


1. Load the Driver
2. Establish the Connection
3. Create a Statement
4. Execute the Query
5. Process the ResultSet
6. Close the Resources
What is Connection Pooling in Java?
Simple Definition:
Connection Pooling is a technique to reuse database connections instead of
creating a new one every time.

Without Pooling
Every time your code runs:
1. Load Driver
2. Open a new connection
3. Use it
4. Close it

Repeating this for each request is slow and expensive, especially in large
applications.

With Connection Pooling


• A pool of pre-created connections is maintained.
• When you need a connection, you borrow it from the pool.
• After use, you return it (not close).
• The pool reuses it for the next request.
Benefit:

• Reuse existing connections

• Improves performance

• Efficient resource management

Real-Life Analogy

Think of it like renting a power bank from a station:


• You don’t buy a new one every time.
• You borrow, use, return.
• Someone else can use it again.
You can suppress:
• "unchecked"
• "deprecation"
• "rawtypes"

3. Reflection Basics
Reflection is a feature that allows Java code to inspect and modify classes,
methods, fields, and annotations at runtime.
Use Cases:
• Frameworks (like Spring, Hibernate)
• Tools that scan classes and methods
• Unit testing frameworks
What are Design Patterns?
Design patterns are proven solutions to common problems in software design.
They improve code reusability, scalability, and maintainability.

1. Singleton Pattern

Purpose:
Ensure that a class has only one instance and provides a global point of access
to it.

Real-World Example:
• One Database Connection Manager
• One Logger class
• One Configuration Reader
Key Rules:
• Constructor is private
• Static method gives access
• Static variable stores the instance

2. Factory Pattern

Purpose:
To create objects without exposing the object creation logic to the client and
to refer to the newly created object using a common interface.

Real-World Example:
• ShapeFactory creates objects like Circle, Square
• JDBC uses DriverManager:
Connection con = DriverManager.getConnection(...)
3. Builder Pattern
Purpose:
To build complex objects step-by-step, especially when an object has many
optional fields.
4. Strategy Pattern
Purpose:
Encapsulate different algorithms (or strategies) and make them
interchangeable at runtime.
5. Observer Pattern
Purpose:
When one object changes, all its dependents (observers) are automatically
notified.
---------------------------------------------------------------------------------------------------------

You might also like