- Java is easy to learn and understand
- Syntax is similar to C++
- Eliminates complex features like pointers and operator overloading
- Makes programs easier to write and maintain
- Based on OOP principles: encapsulation, inheritance, polymorphism, abstraction
- Everything is treated as an object
- Improves code reusability and modularity
- Follows Write Once, Run Anywhere (WORA)
- Code is compiled into bytecode
- Runs on any system with JVM without modification
- Programs can be executed on different platforms
- Fixed size of data types ensures portability
- Bytecode is platform-independent
- No use of pointers prevents unauthorized access
- Bytecode verifier checks code safety
- Class loader and security manager enhance security
- Provides secure execution environment
- Strong memory management
- Automatic garbage collection
- Exception handling mechanism
- Reduces runtime errors and crashes
- Not dependent on any specific hardware architecture
- Bytecode can run on any system with JVM
- Ensures cross-platform compatibility
- Java bytecode is interpreted by JVM
- Enables platform independence
- Supports flexible execution and debugging
- Uses Just-In-Time (JIT) compiler
- Converts bytecode into native machine code
- Improves execution speed
- Supports execution of multiple threads simultaneously
- Improves CPU utilization
- Useful in real-time applications
- Supports network-based applications
- Provides APIs like RMI, networking packages
- Enables communication between systems
- Supports dynamic class loading at runtime
- Allows modification and extension of programs
- Makes Java flexible and adaptable
- Java has 12 main features (buzzwords)
- Platform independent and secure are most important
- Supports OOP and multithreading
- Widely used due to robustness and portability
- Scanner class is used to take input from the user at runtime
- It belongs to the java.util package
- It can read different types of data like int, float, double, String, etc.
- It uses input streams such as System.in
| Method | Description |
|---|---|
| nextInt() | Reads integer value |
| nextFloat() | Reads float value |
| nextDouble() | Reads double value |
| next() | Reads single word |
| nextLine() | Reads entire line |
| nextBoolean() | Reads boolean value |
- Scanner sc = new Scanner(System.in); → creates Scanner object
- nextLine() → reads string input
- nextInt() → reads integer input
- Input is taken from keyboard and displayed
- Easy to use for input handling
- Supports multiple data types
- More flexible than older methods (like BufferedReader)
- Scanner belongs to java.util
- Used for user input
- Methods like nextInt(), nextLine() commonly used
- Must import package before use
- Inheritance is an OOP concept where a subclass acquires properties and methods of a superclass
- Implemented using the extends keyword
- Promotes code reusability and establishes hierarchical relationships
One subclass inherits from one superclass
A class inherits from another class, forming a chain
Multiple subclasses inherit from one superclass
Java does not support multiple inheritance using classes
Achieved using interfaces
- Code reusability
- Reduces redundancy
- Improves readability and maintainability
- Supports polymorphism
- Inheritance uses extends keyword
- Types: Single, Multilevel, Hierarchical, Multiple (via interfaces)
- Enables reuse and hierarchy
- Important concept in OOP
Method Overloading: Multiple methods with the same name but different parameter lists in the same class (compile-time polymorphism).
Method Overriding: Subclass provides a specific implementation of a method already defined in its superclass (runtime polymorphism).
| Feature | Method Overloading | Method Overriding |
|---|---|---|
| Definition | Same method name, different parameters | Same method name and parameters |
| Location | Same class | Parent and child class |
| Polymorphism | Compile-time | Runtime |
| Parameters | Must differ (number/type/order) | Must be same |
| Return Type | Can differ | Must be same or covariant |
| Binding | Early binding | Late binding |
| Inheritance | Not required | Required |
| Execution | Decided at compile time | Decided at runtime |
- In overloading, methods differ in parameters but exist in the same class
- In overriding, subclass changes behavior of superclass method
- Overloading improves readability, overriding enables runtime behavior change
- Overloading → same class, different parameters, compile-time
- Overriding → inheritance, same signature, runtime
- Both support polymorphism in Java
- Java Swing is a GUI toolkit used to create window-based desktop applications
- It is part of the javax.swing package
- Built on top of AWT but provides more advanced and flexible components
- Platform independent (runs on any system with JVM)
- Lightweight components (not dependent on OS)
- Rich set of GUI components
- Highly customizable (font, color, size)
- Event-driven programming
- Follows MVC architecture
- JFrame → main window
- JDialog → dialog box
- JApplet → applet container
- JPanel → used to group components
- JScrollPane → provides scrolling
- JButton → clickable button
- JLabel → display text/image
- JTextField → single-line input
- JTextArea → multi-line input
- FlowLayout → arranges in a row
- BorderLayout → North, South, East, West, Center
- GridLayout → grid structure
- BoxLayout → row/column arrangement
- Used to handle user actions like button clicks
- Uses listeners (e.g., ActionListener)
- Event → Listener → Response
- Desktop applications
- Banking systems
- Text editors
- Management systems
- GUI-based tools
- Swing is part of javax.swing
- Used for GUI development
- Provides rich and flexible components
- Event-driven and platform independent
- A thread is a lightweight process that allows multiple tasks to run concurrently within a program
- Used to achieve multitasking and improve performance
- Threads share the same memory space
- Improves CPU utilization
- Enables multitasking
- Faster program execution
- Efficient resource sharing
- Create a class that extends Thread
- Override run() method
- Call start() method
class MyThread extends Thread
{
public void run()
{
System.out.println("Thread using Thread class");
}
}
public class Test
{
public static void main(String[] args)
{
MyThread t1 = new MyThread(); // New state
t1.start(); // Runnable → Running
}
}
- Create a class that implements Runnable
- Override run() method
- Pass object to Thread and call start()
class MyRunnable implements Runnable
{
public void run()
{
System.out.println("Thread using Runnable interface");
}
}
public class Test
{
public static void main(String[] args)
{
MyRunnable obj = new MyRunnable();
Thread t2 = new Thread(obj);
t2.start();
}
}
| Feature | Thread Class | Runnable Interface |
|---|---|---|
| Inheritance | Extends Thread | Implements Runnable |
| Flexibility | Less flexible (cannot extend another class) | More flexible |
| Code Reuse | Limited | Better reuse |
| Recommended | Less preferred | More preferred |
- start() → starts thread execution
- run() → contains logic
- sleep() → pauses execution
- join() → waits for another thread
- yield() → gives chance to other threads
- Thread enables multitasking
- Two ways: Thread class & Runnable interface
- start() method is used to begin execution
- Runnable method is preferred in real applications
A package in Java is a collection of related classes and interfaces grouped together to organize code and avoid naming conflicts.
- Organizes large programs into logical groups
- Avoids naming conflicts
- Provides access protection
- Improves code reusability and maintainability
Use package keyword at the beginning of the program
package mypackage;
package mypackage;
public class Test
{
public void display()
{
System.out.println("Package created");
}
}
Use command:
javac -d . Test.java
This creates a folder named mypackage
import mypackage.Test;
public class Demo
{
public static void main(String[] args)
{
Test t = new Test();
t.display();
}
}
public class Demo
{
public static void main(String[] args)
{
mypackage.Test t = new mypackage.Test();
t.display();
}
}
- Built-in packages → Provided by Java (e.g., java.lang, java.util)
- User-defined packages → Created by programmer
- Prevents naming conflicts
- Provides access control using modifiers
- Improves readability and structure
- Supports modular programming
- Package = group of related classes
- Use package keyword to create
- Use import to access
- Two types: Built-in and User-defined
Control statements are used to control the flow of execution of a program based on conditions, loops, and branching.
- 1. Conditional (Decision-Making) Statements
- 2. Looping (Iterative) Statements
- 3. Jumping (Branching) Statements
Executes block only if condition is true
int x = 10;
if(x > 0)
{
System.out.println("Positive number");
}
Executes one block if condition is true, otherwise another
int x = -5;
if(x > 0)
{
System.out.println("Positive");
}
else
{
System.out.println("Negative");
}
Used to check multiple conditions
int marks = 75;
if(marks >= 90)
{
System.out.println("A");
}
else if(marks >= 75)
{
System.out.println("B");
}
else
{
System.out.println("C");
}
Used to select one case from many options
int day = 2;
switch(day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid");
}
Used to execute a block of code repeatedly until a condition is satisfied
Condition is checked before execution
int i = 1;
while(i <= 5)
{
System.out.println(i);
i++;
}
Executes at least once
int i = 1;
do
{
System.out.println(i);
i++;
}
while(i <= 5);
Used when number of iterations is known
for(int i = 1; i <= 5; i++)
{
System.out.println(i);
}
Used for arrays and collections
int arr[] = {1,2,3};
for(int x : arr)
{
System.out.println(x);
}
Terminates loop or switch immediately
for(int i = 1; i <= 5; i++)
{
if(i == 3)
{
break;
}
System.out.println(i);
}
Skips current iteration and continues loop
for(int i = 1; i <= 5; i++)
{
if(i == 3)
{
continue;
}
System.out.println(i);
}
Exits from method and optionally returns value
int add(int a, int b)
{
return a + b;
}
Start → Condition → Execution → Update → Repeat → End
Controls decision-making, looping, and branching
- Enables decision making
- Reduces code repetition
- Improves program efficiency
- Makes programs dynamic and flexible
- Three types: Conditional, Looping, Jumping
- if, switch → decision making
- for, while, do-while → looping
- break, continue, return → control flow
- Essential for program logic and execution control
Thread life cycle represents the various states a thread goes through from creation to termination during execution.
New → Runnable → Running → Waiting/Blocked → Runnable → Running → Terminated
- Thread is created using new Thread()
- Not yet started
- No CPU allocation
- Thread is ready for execution
- After calling start() method
- Waiting for CPU scheduling
- Thread is actively executing
- CPU is assigned by scheduler
- Executes run() method
- Thread is temporarily inactive
- Waiting for resource or another thread
- Methods causing this state:
- sleep()
- wait()
- join()
- Thread completes execution
- Cannot be restarted again
- New → Runnable → by calling start()
- Runnable → Running → CPU scheduler selects thread
- Running → Waiting/Blocked → sleep(), wait()
- Waiting → Runnable → after completion of waiting
- Running → Terminated → execution finishes
class MyThread extends Thread
{
public void run()
{
System.out.println("Thread using Thread class");
}
}
public class Test
{
public static void main(String[] args)
{
MyThread t1 = new MyThread(); // New state
t1.start(); // Runnable → Running
}
}
class MyRunnable implements Runnable
{
public void run()
{
System.out.println("Thread using Runnable interface");
}
}
public class Test
{
public static void main(String[] args)
{
MyRunnable obj = new MyRunnable();
Thread t2 = new Thread(obj);
t2.start();
}
}
- start() → starts execution
- run() → contains logic
- sleep() → pauses thread
- join() → waits for another thread
- yield() → gives chance to other threads
- Thread has 5 states: New, Runnable, Running, Waiting, Terminated
- start() begins execution
- Threads improve multitasking
- Two ways: Thread class & Runnable interface
- String is a class in java.lang used to represent a sequence of characters
- Strings are immutable, i.e., once created, they cannot be changed
- Stored in a special memory area called String pool
String s1 = "Java";
- Stored in String pool
- Memory efficient
String s2 = new String("Programming");
- Stored in heap memory
- Creates new object
- Immutable in nature
- Thread-safe
- Provides many built-in methods
- Efficient memory management using String pool
Returns length of string
s.length();
Returns character at specific index
s.charAt(2);
Extracts part of string
s.substring(1,4);
Compares two strings
s1.equals(s2);
Compares strings ignoring case
s1.equalsIgnoreCase(s2);
Joins two strings
s1.concat(s2);
Converts case
s.toUpperCase();
Finds position of character
s.indexOf('a');
Replaces characters
s.replace('a','b');
Removes leading and trailing spaces
s.trim();
class StringDemo
{
public static void main(String[] args)
{
String s = "Java Programming";
System.out.println("Length: " + s.length());
System.out.println("Uppercase: " + s.toUpperCase());
System.out.println("Substring: " + s.substring(0,4));
System.out.println("Character: " + s.charAt(2));
}
}
| Feature | String | StringBuffer | StringBuilder |
|---|---|---|---|
| Nature | Immutable | Mutable | Mutable |
| Thread Safety | Yes | Yes | No |
| Performance | Slow | Moderate | Fast |
- String belongs to java.lang
- Immutable and stored in String pool
- Provides many built-in functions
- StringBuffer & StringBuilder used for modification
Operators are special symbols used to perform operations on variables and values such as arithmetic, comparison, and logical operations.
Used for mathematical calculations
| Operator | Operation |
|---|---|
| + | Addition |
| - | Subtraction |
| * | Multiplication |
| / | Division |
| % | Modulus |
class ArithmeticDemo
{
public static void main(String[] args)
{
int a = 10, b = 5;
System.out.println(a + b);
System.out.println(a - b);
System.out.println(a * b);
System.out.println(a / b);
System.out.println(a % b);
}
}
Used to compare two values (returns boolean result)
| Operator | Meaning |
|---|---|
| == | Equal to |
| != | Not equal |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
class RelationalDemo
{
public static void main(String[] args)
{
int a = 10, b = 5;
System.out.println(a > b);
System.out.println(a == b);
}
}
Used to combine conditions
| Operator | Meaning |
|---|---|
| && | Logical AND |
| ! | Logical NOT |
class LogicalDemo
{
public static void main(String[] args)
{
int a = 10;
System.out.println(a > 0 && a < 20);
System.out.println(!(a > 5));
}
}
Used to assign values
| Operator | Example |
|---|---|
| = | a = 10 |
| += | a += 5 |
| -= | a -= 2 |
| *= | a *= 3 |
| /= | a /= 2 |
class AssignmentDemo
{
public static void main(String[] args)
{
int a = 10;
a += 5;
System.out.println(a);
}
}
Operate on a single operand
| Operator | Operation |
|---|---|
| ++ | Increment |
| -- | Decrement |
| ! | Logical NOT |
class UnaryDemo
{
public static void main(String[] args)
{
int a = 5;
a++;
System.out.println(a);
}
}
Perform operations on bits
| Operator | Meaning |
|---|---|
| & | AND |
| | | OR |
| ^ | XOR |
| ~ | Complement |
class BitwiseDemo
{
public static void main(String[] args)
{
int a = 5, b = 3;
System.out.println(a & b);
System.out.println(a | b);
}
}
Short form of if-else
class TernaryDemo
{
public static void main(String[] args)
{
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println(max);
}
}
Used to shift bits left or right
| Operator | Meaning |
|---|---|
| << | Left shift |
| >> | Right shift |
class ShiftDemo
{
public static void main(String[] args)
{
int a = 4;
System.out.println(a << 1);
}
}
- Operators perform operations on data
- Types: Arithmetic, Relational, Logical, Assignment, Unary, Bitwise, Ternary, Shift
- Used for calculations and decision-making
- Essential for program logic
Exception handling is a mechanism used to handle runtime errors and continue program execution normally without crashing.
- Contains code that may cause exception
- Must be followed by catch or finally
- Handles specific exception
- Executes only when exception occurs
- Executes always (exception occurs or not)
- Used for cleanup (closing files, resources)
- Program executes statements inside try block
- If no exception → skip catch, execute finally
- If exception occurs → control jumps to matching catch block
- Exception is handled → finally block executes
- Program continues normally
class ExceptionDemo
{
public static void main(String[] args)
{
try
{
System.out.println("Step 1: Before exception");
int a = 10 / 0;
System.out.println("Step 2: After exception");
}
catch(ArithmeticException e)
{
System.out.println("Exception caught: Division by zero");
}
finally
{
System.out.println("Finally block executed");
}
System.out.println("Program continues normally");
}
}
- "Step 1" is printed before exception
- Exception occurs at 10/0, so "Step 2" is skipped
- Control moves to catch block → prints error message
- finally block executes always
- Program continues after exception handling
class NoException
{
public static void main(String[] args)
{
try
{
int a = 10 / 2;
System.out.println("Result: " + a);
}
catch(ArithmeticException e)
{
System.out.println("Error");
}
finally
{
System.out.println("Finally executed");
}
}
}
class MultiCatchDemo
{
public static void main(String[] args)
{
try
{
int arr[] = new int[3];
arr[5] = 10;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Array index error");
}
catch(Exception e)
{
System.out.println("General exception");
}
}
}
- try block → risky code
- catch block → handles exception
- finally → always executes
- Multiple catch → handles different exceptions
- Order: specific → general
- Prevents program crash
- Maintains smooth execution
- Improves reliability
- Helps debugging and error handling
- Exception handling = try + catch + finally
- Program does not terminate abruptly
- finally block always executes
- Output-based questions are common ✔
MVC (Model–View–Controller) is a design pattern that separates an application into three components: Model, View, and Controller for better organization and maintainability.
View → Controller → Model
(Model and View do not communicate directly)
- Represents data and business logic of the application
- Responsible for data processing and database operations
- Independent of user interface
- Sends updated data to Controller/View
Example:
Student data, database records
- Represents the user interface (UI)
- Displays data to the user
- Receives input from user (keyboard, mouse)
- Does not contain business logic
Example:
Forms, buttons, text fields (Swing GUI)
- Acts as an intermediary between Model and View
- Receives user input from View
- Processes input and updates Model
- Updates View based on Model changes
- User interacts with View
- View sends input to Controller
- Controller processes logic and updates Model
- Model updates data
- Controller updates View
- View displays updated output
| Component | Responsibility |
|---|---|
| Model | Data handling and business logic |
| View | User interface and display |
| Controller | Controls flow and communication |
- Separation of concerns
- Easy maintenance and scalability
- Improved code reusability
- Independent development of components
- Web applications (Spring MVC)
- Desktop applications (Java Swing)
- Mobile applications
- Enterprise systems
// Model
class Student
{
String name;
}
// View
interface StudentView
{
void display(String name);
}
// Controller
class StudentController
{
Student model;
StudentView view;
StudentController(Student m, StudentView v)
{
model = m;
view = v;
}
void updateView()
{
view.display(model.name);
}
}
- MVC = Model + View + Controller
- Controller connects Model and View
- Improves modularity and testing
- Widely used in GUI and web applications
- Used to make decisions based on conditions
- Executes different blocks of code depending on true/false conditions
Executes block only when condition is true
class IfExample
{
public static void main(String[] args)
{
int x = 10;
if(x > 0)
{
System.out.println("Positive number");
}
}
}
Executes one block if condition is true, otherwise another
class IfElseExample
{
public static void main(String[] args)
{
int x = -5;
if(x > 0)
{
System.out.println("Positive");
}
else
{
System.out.println("Negative");
}
}
}
Used to check multiple conditions
class LadderExample
{
public static void main(String[] args)
{
int marks = 75;
if(marks >= 90)
{
System.out.println("Grade A");
}
else if(marks >= 75)
{
System.out.println("Grade B");
}
else
{
System.out.println("Grade C");
}
}
}
Used to select one case from many options
class SwitchExample
{
public static void main(String[] args)
{
int day = 2;
switch(day)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
}
}
}
- Used to execute a block of code repeatedly until a condition becomes false
Condition checked before execution
class WhileExample
{
public static void main(String[] args)
{
int i = 1;
while(i <= 5)
{
System.out.println(i);
i++;
}
}
}
Executes at least once
class DoWhileExample
{
public static void main(String[] args)
{
int i = 1;
do
{
System.out.println(i);
i++;
}
while(i <= 5);
}
}
Used when number of iterations is known
class ForExample
{
public static void main(String[] args)
{
for(int i = 1; i <= 5; i++)
{
System.out.println(i);
}
}
}
Used for arrays and collections
class EnhancedFor
{
public static void main(String[] args)
{
int arr[] = {1,2,3};
for(int x : arr)
{
System.out.println(x);
}
}
}
- Conditional → if, if-else, switch
- Looping → while, do-while, for, enhanced for
- Used for decision-making and repetition
- Essential for program control flow
- Encapsulation is the process of wrapping data (variables) and methods into a single unit (class)
- Data is hidden using access modifiers and accessed through getter and setter methods
- Uses private access modifier for variables
- Provides public methods to access data
- Ensures data security and control
class Student
{
private String name;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
public class Test
{
public static void main(String[] args)
{
Student s = new Student();
s.setName("John");
System.out.println(s.getName());
}
}
- Data hiding
- Improved security
- Better control over data
- Easy maintenance
- Inheritance allows one class (subclass) to acquire properties and methods of another class (superclass)
- Implemented using extends keyword
- Code reusability
- Supports hierarchical classification
- Reduces redundancy
- Enables method overriding
class Animal
{
void eat()
{
System.out.println("Animal eats");
}
}
class Dog extends Animal
{
void bark()
{
System.out.println("Dog barks");
}
}
public class Test
{
public static void main(String[] args)
{
Dog d = new Dog();
d.eat();
d.bark();
}
}
- Code reuse
- Improves readability
- Supports polymorphism
- Easy extension of existing code
- Encapsulation → data hiding using getters/setters
- Inheritance → reuse using extends
- Both are core OOP principles
- Helps build modular and secure applications
- Swing components are GUI elements used to build desktop applications
- Part of javax.swing package
- Provide rich and flexible UI elements
Main containers that hold all components
| Component | Description |
|---|---|
| JFrame | Main window of application |
| JDialog | Dialog box window |
| JApplet | Applet container |
Used to organize components
| Component | Description |
|---|---|
| JPanel | Groups components |
| JScrollPane | Adds scrolling feature |
| JSplitPane | Divides window |
| Component | Description |
|---|---|
| JLabel | Displays text or image |
| JButton | Clickable button |
| JTextField | Single-line text input |
| JTextArea | Multi-line text input |
| JCheckBox | Multiple selection |
| JRadioButton | Single selection |
| JComboBox | Dropdown list |
| JTable | Displays data in tabular form |
Controls arrangement of components
| Layout | Description |
|---|---|
| FlowLayout | Left to right |
| BorderLayout | North, South, East, West, Center |
| GridLayout | Grid format |
| BoxLayout | Row/column arrangement |
- Handles user actions
- Uses listeners (e.g., ActionListener)
- Event → Listener → Action
- A simple banking UI allows user to:
- Enter account details
- Deposit or withdraw money
- Display balance
import javax.swing.*;
import java.awt.event.*;
public class BankApp
{
public static void main(String[] args)
{
JFrame frame = new JFrame("Banking Application");
JLabel l1 = new JLabel("Amount:");
l1.setBounds(50, 50, 100, 30);
JTextField tf = new JTextField();
tf.setBounds(150, 50, 150, 30);
JButton deposit = new JButton("Deposit");
deposit.setBounds(50, 100, 100, 30);
JButton withdraw = new JButton("Withdraw");
withdraw.setBounds(200, 100, 100, 30);
JLabel result = new JLabel("Balance: 0");
result.setBounds(50, 150, 200, 30);
final int[] balance = {0};
deposit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int amt = Integer.parseInt(tf.getText());
balance[0] += amt;
result.setText("Balance: " + balance[0]);
}
});
withdraw.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
int amt = Integer.parseInt(tf.getText());
balance[0] -= amt;
result.setText("Balance: " + balance[0]);
}
});
frame.add(l1);
frame.add(tf);
frame.add(deposit);
frame.add(withdraw);
frame.add(result);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
}
- JFrame → main window
- JLabel → displays text
- JTextField → input amount
- JButton → deposit/withdraw actions
- ActionListener → handles button clicks
- Balance updates dynamically
- Platform independent
- Rich GUI controls
- Flexible and customizable
- Supports event-driven programming
- Swing components belong to javax.swing
- Three categories: Top-level, Intermediate, Basic
- Layout managers control UI
- Used to build real-time applications like banking systems
- Streams are used to perform input and output operations in Java
- A stream is a sequence of data flowing between source and destination
- Java provides I/O classes in java.io package
- Used to read data from a source (file, keyboard)
- Example: FileInputStream, BufferedReader
- Used to write data to a destination (file, console)
- Example: FileOutputStream, PrintWriter
| Type | Description | Classes |
|---|---|---|
| Byte Stream | Handles binary data | FileInputStream, FileOutputStream |
| Character Stream | Handles text data | FileReader, FileWriter |
import java.io.*;
class ReadFile
{
public static void main(String[] args) throws Exception
{
FileInputStream fis = new FileInputStream("test.txt");
int i;
while((i = fis.read()) != -1)
{
System.out.print((char)i);
}
fis.close();
}
}
import java.io.*;
class ReadFileChar
{
public static void main(String[] args) throws Exception
{
FileReader fr = new FileReader("test.txt");
int i;
while((i = fr.read()) != -1)
{
System.out.print((char)i);
}
fr.close();
}
}
import java.io.*;
class WriteFile
{
public static void main(String[] args) throws Exception
{
FileOutputStream fos = new FileOutputStream("test.txt");
String data = "Hello Java";
fos.write(data.getBytes());
fos.close();
}
}
import java.io.*;
class WriteFileChar
{
public static void main(String[] args) throws Exception
{
FileWriter fw = new FileWriter("test.txt");
fw.write("Hello World");
fw.close();
}
}
- Import java.io package
- Create stream object
- Open file
- Read or write data
- Close stream
Improves performance by reducing I/O operations
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
import java.io.*;
class FileDemo
{
public static void main(String[] args) throws Exception
{
FileWriter fw = new FileWriter("test.txt");
fw.write("Java I/O Example");
fw.close();
FileReader fr = new FileReader("test.txt");
int i;
while((i = fr.read()) != -1)
{
System.out.print((char)i);
}
fr.close();
}
}
- Supports file handling
- Handles both text and binary data
- Provides efficient data processing
- Flexible and scalable
- Streams = flow of data
- Two types: Input (read), Output (write)
- Byte stream & Character stream
- Must close stream after use
- Important classes: FileInputStream, FileOutputStream, FileReader, FileWriter

0 Comments