0% found this document useful (0 votes)
4 views

javadocuments

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

javadocuments

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

1.

Introduction to Java

 Java is a high-level, object-oriented programming language.

 Developed by James Gosling at Sun Microsystems in 1995.

 Platform-independent due to the Java Virtual Machine (JVM).

2. Features of Java

 Simple: Easy to learn and use.

 Object-Oriented: Follows OOP principles like inheritance, polymorphism, encapsulation, and


abstraction.

 Platform-Independent: "Write Once, Run Anywhere" (WORA) enabled by JVM.

 Secure: Provides built-in security features.

 Robust: Strong memory management, exception handling.

 Multi-threaded: Supports concurrent programming.

3. Structure of a Java Program

java

Copy code

// Example of a simple Java program

public class Main {

public static void main(String[] args) {

System.out.println("Hello, World!"); // Prints output to the console

 Class: Java programs are organized into classes.

 main(): Entry point of the program.

 System.out.println(): Used to print output.

4. Java Data Types

Java has two categories of data types:

1. Primitive: byte, short, int, long, float, double, char, boolean.

2. Non-Primitive: String, Arrays, Classes, etc.


1. Primitive Data Types

a. byte

 Stores small integers (-128 to 127).

java

Copy code

public class ByteExample {

public static void main(String[] args) {

byte age = 25;

System.out.println("Age: " + age);

b. short

 Stores integers (-32,768 to 32,767).

java

Copy code

public class ShortExample {

public static void main(String[] args) {

short year = 2024;

System.out.println("Year: " + year);

c. int

 Stores integers (-2,147,483,648 to 2,147,483,647).

java

Copy code

public class IntExample {

public static void main(String[] args) {

int salary = 50000;

System.out.println("Salary: " + salary);

}
d. long

 Stores large integers (-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807).

java

Copy code

public class LongExample {

public static void main(String[] args) {

long population = 8000000000L; // Use 'L' for long literals

System.out.println("World Population: " + population);

e. float

 Stores decimals (6-7 decimal precision).

java

Copy code

public class FloatExample {

public static void main(String[] args) {

float price = 19.99f; // Use 'f' for float literals

System.out.println("Price: $" + price);

f. double

 Stores decimals (15-16 decimal precision).

java

Copy code

public class DoubleExample {

public static void main(String[] args) {

double distance = 384400.55; // Distance to the moon in km

System.out.println("Distance to the Moon: " + distance + " km");

g. char
 Stores a single character.

java

Copy code

public class CharExample {

public static void main(String[] args) {

char grade = 'A';

System.out.println("Grade: " + grade);

h. boolean

 Stores true or false.

java

Copy code

public class BooleanExample {

public static void main(String[] args) {

boolean isPassed = true;

System.out.println("Did the student pass? " + isPassed);

2. Non-Primitive Data Types

a. String

 Used for sequences of characters.

java

Copy code

public class StringExample {

public static void main(String[] args) {

String name = "Pavithra";

System.out.println("Name: " + name);

}
b. Array

 Stores multiple values of the same type.

java

Copy code

public class ArrayExample {

public static void main(String[] args) {

int[] marks = {85, 90, 78};

for (int mark : marks) {

System.out.println("Mark: " + mark);

c. Class

 A user-defined blueprint for objects.

java

Copy code

class Student {

String name;

int age;

void display() {

System.out.println("Name: " + name + ", Age: " + age);

public class ClassExample {

public static void main(String[] args) {

Student student = new Student();

student.name = "John";

student.age = 20;

student.display();
}

d.interface

An interface in Java is a blueprint for a class. It contains abstract methods (methods


without a body) that must be implemented by any class that "implements" the interface.
Interfaces are useful for achieving abstraction and multiple inheritance in Java.

interface Animal {

void sound(); // Abstract method

void eat(); // Abstract method

class Dog implements Animal {

public void sound() {

System.out.println("Dog barks");

public void eat() {

System.out.println("Dog eats bones");

public class InterfaceExample {

public static void main(String[] args) {

Dog dog = new Dog();

dog.sound();

dog.eat();

}
5.OPERATORS
1. Arithmetic Operators

Used to perform basic arithmetic operations.

Operator Description Example Result

+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division 10 / 2 5

% Modulus (Remainder) 10 % 3 1

Example:

java

Copy code

public class ArithmeticExample {

public static void main(String[] args) {

int a = 10, b = 3;

System.out.println("Addition: " + (a + b));

System.out.println("Subtraction: " + (a - b));

System.out.println("Multiplication: " + (a * b));

System.out.println("Division: " + (a / b));

System.out.println("Modulus: " + (a % b));

2. Relational (Comparison) Operators

Used to compare two values, resulting in a boolean value (true or false).

Operator Description Example Result

== Equal to 5 == 5 true

!= Not equal to 5 != 3 true


Operator Description Example Result

> Greater than 5>3 true

< Less than 3<5 true

>= Greater than or equal to 5 >= 5 true

<= Less than or equal to 3 <= 5 true

Example:

java

Copy code

public class RelationalExample {

public static void main(String[] args) {

int x = 10, y = 20;

System.out.println("x == y: " + (x == y));

System.out.println("x != y: " + (x != y));

System.out.println("x > y: " + (x > y));

System.out.println("x < y: " + (x < y));

System.out.println("x >= y: " + (x >= y));

System.out.println("x <= y: " + (x <= y));

3. Logical Operators

Used to combine multiple boolean expressions.

Operator Description Example Result

&& Logical AND true && false false

|| Logical OR ` Logical OR

! Logical NOT !true false

Example:

java
Copy code

public class LogicalExample {

public static void main(String[] args) {

boolean a = true, b = false;

System.out.println("a && b: " + (a && b));

System.out.println("a || b: " + (a || b));

System.out.println("!a: " + (!a));

4. Assignment Operators

Used to assign values to variables.

Operator Description Example Equivalent To

= Assignment a=5 a=5

+= Add and assign a += 5 a=a+5

-= Subtract and assign a -= 5 a=a-5

*= Multiply and assign a *= 5 a=a*5

/= Divide and assign a /= 5 a=a/5

%= Modulus and assign a %= 5 a=a%5

Example:

java

Copy code

public class AssignmentExample {

public static void main(String[] args) {

int a = 10;

a += 5;

System.out.println("a after a += 5: " + a);

a -= 3;
System.out.println("a after a -= 3: " + a);

5. Bitwise Operators

Operate on bits and perform bit-by-bit operations.

Operator Description Example Result

& Bitwise AND 5&3 1

` ` Bitwise OR `5

^ Bitwise XOR 5^3 6

~ Bitwise Complement ~5 -6

<< Left Shift 5 << 1 10

>> Right Shift 5 >> 1 2

Example:

java

Copy code

public class BitwiseExample {

public static void main(String[] args) {

int x = 5, y = 3;

System.out.println("x & y: " + (x & y));

System.out.println("x | y: " + (x | y));

System.out.println("x ^ y: " + (x ^ y));

System.out.println("~x: " + (~x));

System.out.println("x << 1: " + (x << 1));

System.out.println("x >> 1: " + (x >> 1));

6. Unary Operators
Work with a single operand.

Operator Description Example Result

+ Unary plus +x x

- Unary minus -x -x

++ Increment x++ or ++x x+1

-- Decrement x-- or --x x-1

! Logical NOT !true false

7. Ternary Operator

Used as a shorthand for if-else.

Syntax:

java

Copy code

condition ? expression1 : expression2;

Example:

java

Copy code

public class TernaryExample {

public static void main(String[] args) {

int a = 10, b = 20;

int max = (a > b) ? a : b;

System.out.println("The maximum is: " + max);

6.CONDITIONAL STATEMENTS
1. if Statement

Executes a block of code if the condition is true.


Syntax:

java

Copy code

if (condition) {

// code to execute if condition is true

Example:

java

Copy code

public class IfExample {

public static void main(String[] args) {

int number = 10;

if (number > 5) {

System.out.println("The number is greater than 5.");

2. if-else Statement

Executes one block of code if the condition is true and another block if it is false.

Syntax:

java

Copy code

if (condition) {

// code to execute if condition is true

} else {

// code to execute if condition is false

Example:

java
Copy code

public class IfElseExample {

public static void main(String[] args) {

int number = 4;

if (number % 2 == 0) {

System.out.println("The number is even.");

} else {

System.out.println("The number is odd.");

3. if-else-if Ladder

Used to check multiple conditions.

Syntax:

java

Copy code

if (condition1) {

// code to execute if condition1 is true

} else if (condition2) {

// code to execute if condition2 is true

} else {

// code to execute if none of the conditions are true

Example:

java

Copy code

public class IfElseIfExample {

public static void main(String[] args) {

int marks = 85;

if (marks >= 90) {


System.out.println("Grade: A+");

} else if (marks >= 75) {

System.out.println("Grade: A");

} else if (marks >= 50) {

System.out.println("Grade: B");

} else {

System.out.println("Grade: F");

4. switch Statement

Tests a variable against multiple values and executes a block of code that matches the value.

Syntax:

java

Copy code

switch (expression) {

case value1:

// code to execute if expression == value1

break;

case value2:

// code to execute if expression == value2

break;

// more cases...

default:

// code to execute if no case matches

Example:

java

Copy code

public class SwitchExample {


public static void main(String[] args) {

int day = 3;

switch (day) {

case 1:

System.out.println("Monday");

break;

case 2:

System.out.println("Tuesday");

break;

case 3:

System.out.println("Wednesday");

break;

default:

System.out.println("Invalid day");

5. Nested if Statements

An if statement inside another if statement.

Syntax:

java

Copy code

if (condition1) {

if (condition2) {

// code to execute if both conditions are true

Example:
java

Copy code

public class NestedIfExample {

public static void main(String[] args) {

int age = 25;

boolean hasLicense = true;

if (age >= 18) {

if (hasLicense) {

System.out.println("You are eligible to drive.");

} else {

System.out.println("You need a license to drive.");

} else {

System.out.println("You are not old enough to drive.");

7.LOOP STATEMENTS

1. for Loop

The for loop repeats a block of code a specified number of times.

Syntax:

java

Copy code

for (initialization; condition; increment/decrement) {

// Code to be executed

Example:
java

Copy code

public class ForLoopExample {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

System.out.println("Iteration: " + i);

2. while Loop

The while loop repeats a block of code as long as a specified condition is true.

Syntax:

java

Copy code

while (condition) {

// Code to be executed

Example:

java

Copy code

public class WhileLoopExample {

public static void main(String[] args) {

int i = 1;

while (i <= 5) {

System.out.println("Iteration: " + i);

i++;

}
3. do-while Loop

The do-while loop executes the code block once, then checks the condition, and repeats if true.

Syntax:

java

Copy code

do {

// Code to be executed

} while (condition);

Example:

java

Copy code

public class DoWhileExample {

public static void main(String[] args) {

int i = 1;

do {

System.out.println("Iteration: " + i);

i++;

} while (i <= 5);

Using break in Loops

The break statement terminates the loop immediately.

Example with for loop:

java

Copy code

public class BreakExample {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

if (i == 3) {

break; // Exit the loop when i == 3


}

System.out.println("Iteration: " + i);

Using continue in Loops

The continue statement skips the current iteration and jumps to the next one.

Example with while loop:

java

Copy code

public class ContinueExample {

public static void main(String[] args) {

int i = 0;

while (i < 5) {

i++;

if (i == 3) {

continue; // Skip this iteration

System.out.println("Iteration: " + i);

Using switch in Loops

A switch statement can be used inside loops to control the flow based on a variable's value.

Example with for loop and switch:

java

Copy code

public class SwitchInLoop {

public static void main(String[] args) {


for (int day = 1; day <= 4; day++) {

switch (day) {

case 1:

System.out.println("Monday");

break;

case 2:

System.out.println("Tuesday");

break;

case 3:

System.out.println("Wednesday");

break;

default:

System.out.println("Invalid day");

break;

Example Combining break and continue with Loops

java

Copy code

public class LoopControlExample {

public static void main(String[] args) {

for (int i = 1; i <= 10; i++) {

if (i % 2 == 0) {

continue; // Skip even numbers

if (i > 7) {

break; // Stop the loop when i > 7

}
System.out.println("Odd number: " + i);

Summary

 break: Exits the loop immediately.

 continue: Skips the current iteration and moves to the next.

 switch: Provides a structured way to handle multiple cases, often within loops.

8.Methods in Java
Methods in Java are blocks of code designed to perform a specific task. They help make code
modular, reusable, and easy to maintain.

1. Method Declaration and Definition

A method must be declared and defined before it can be used.

Syntax:

java

Copy code

returnType methodName(parameters) {

// Method body (statements to execute)

Example:

java

Copy code

public class MethodExample {

// Method Declaration and Definition

public void greet() {


System.out.println("Hello, welcome to Java!");

public static void main(String[] args) {

MethodExample obj = new MethodExample();

obj.greet(); // Calling the method

2. Method Parameters

(a) Passing by Value

Java always uses pass-by-value, meaning a copy of the variable is passed to the method. Any changes
made inside the method do not affect the original value.

Example:

java

Copy code

public class PassByValue {

public void changeValue(int num) {

num = num + 10; // Changes only the local copy

public static void main(String[] args) {

int x = 20;

PassByValue obj = new PassByValue();

obj.changeValue(x);

System.out.println("Original value of x: " + x); // Output: 20

(b) Passing by Reference

Objects are passed by reference. Changes made to the object inside the method affect the original
object.

Example:
java

Copy code

class Box {

int length = 5;

public class PassByReference {

public void modify(Box b) {

b.length = 10; // Changes the original object

public static void main(String[] args) {

Box box = new Box();

PassByReference obj = new PassByReference();

obj.modify(box);

System.out.println("Modified length: " + box.length); // Output: 10

3. Method Return Types

Methods can return values. The return type specifies the data type of the value returned by the
method.

Example:

java

Copy code

public class ReturnExample {

public int add(int a, int b) {

return a + b; // Returning the sum

public static void main(String[] args) {


ReturnExample obj = new ReturnExample();

int sum = obj.add(5, 10);

System.out.println("Sum: " + sum); // Output: 15

4. Method Overloading

Method overloading allows multiple methods with the same name but different parameter lists.

Example:

java

Copy code

public class MethodOverloading {

// Overloaded methods

public int add(int a, int b) {

return a + b;

public double add(double a, double b) {

return a + b;

public static void main(String[] args) {

MethodOverloading obj = new MethodOverloading();

System.out.println("Integer sum: " + obj.add(5, 10)); // Output: 15

System.out.println("Double sum: " + obj.add(5.5, 10.5)); // Output: 16.0

5.Recursion in Java
Recursion is a technique in which a method calls itself to solve smaller instances of a problem. Every
recursive method must have a base case, which stops the recursion when a condition is met, and a
recursive step, which reduces the problem size.

Syntax of a Recursive Method

java

Copy code

returnType methodName(parameters) {

if (base case condition) {

return result; // Base case: stops the recursion

return methodName(smallerProblem); // Recursive step

1. Factorial Calculation

A classic example of recursion is finding the factorial of a number.

Example:

java

Copy code

public class RecursionExample {

public int factorial(int n) {

if (n == 1) { // Base case

return 1;

return n * factorial(n - 1); // Recursive call

public static void main(String[] args) {

RecursionExample obj = new RecursionExample();

int result = obj.factorial(5);

System.out.println("Factorial of 5: " + result); // Output: 120

}
}

9.Strings in Java
The String class in Java represents a sequence of characters and is widely used for handling text.
Strings in Java are immutable, meaning once a string object is created, its value cannot be changed.

Let's go through each topic related to strings in detail:

String Class and Methods

The String class is part of the java.lang package and provides various methods to manipulate strings.

1. length(): Returns the length of the string (the number of characters).

java

Copy code

String str = "Hello";

System.out.println(str.length()); // Output: 5

2. charAt(int index): Returns the character at the specified index.

java

Copy code

String str = "Hello";

System.out.println(str.charAt(1)); // Output: e
3. substring(int start): Returns a new string starting from the specified index to the end of the
string.

java

Copy code

String str = "Hello World";

System.out.println(str.substring(6)); // Output: World

4. substring(int start, int end): Returns a new string from the start index to end - 1 index.

java

Copy code

String str = "Hello World";

System.out.println(str.substring(0, 5)); // Output: Hello

5. equals(Object another): Compares two strings for content equality.

java

Copy code

String str1 = "hello";

String str2 = "hello";

System.out.println(str1.equals(str2)); // Output: true

6. toUpperCase(): Converts all characters in the string to uppercase.

java

Copy code

String str = "hello";

System.out.println(str.toUpperCase()); // Output: HELLO

7. toLowerCase(): Converts all characters in the string to lowercase.

java

Copy code

String str = "HELLO";

System.out.println(str.toLowerCase()); // Output: hello

8. trim(): Removes leading and trailing whitespace from the string.

java

Copy code

String str = " hello ";


System.out.println(str.trim()); // Output: hello

String Concatenation

You can concatenate strings in Java using:

1. The + Operator: Concatenates two strings.

java

Copy code

String str1 = "Hello";

String str2 = "World";

String result = str1 + " " + str2;

System.out.println(result); // Output: Hello World

2. Using StringBuilder: For efficient string concatenation, especially in loops or multiple


concatenations.

java

Copy code

StringBuilder sb = new StringBuilder();

sb.append("Hello");

sb.append(" ");

sb.append("World");

System.out.println(sb.toString()); // Output: Hello World

StringBuilder is more efficient than using the + operator because it does not create a new string
object each time a new string is added.

String Comparison

1. equals(Object obj): Compares the content of two strings for equality.

java

Copy code

String str1 = "hello";

String str2 = "hello";

System.out.println(str1.equals(str2)); // Output: true

2. == (Reference comparison): Compares the references of the two strings (not the content).

java
Copy code

String str1 = "hello";

String str2 = new String("hello");

System.out.println(str1 == str2); // Output: false (different references)

3. compareTo(String another): Compares two strings lexicographically (based on the Unicode


values of characters).

o Returns a negative integer if the first string is lexicographically less than the second.

o Returns 0 if the strings are equal.

o Returns a positive integer if the first string is lexicographically greater than the
second.

java

Copy code

String str1 = "apple";

String str2 = "banana";

System.out.println(str1.compareTo(str2)); // Output: -1 (because 'a' < 'b')

Immutable Nature of Strings in Java

 In Java, strings are immutable. Once a string object is created, its value cannot be changed.

 When you modify a string, a new string object is created. For example:

java

Copy code

String str = "hello";

str = str + " world"; // Creates a new string object

System.out.println(str); // Output: hello world

 If you perform multiple modifications to a string, it creates a new object each time, which
can be inefficient for large strings or in loops. This is one reason why using StringBuilder or
StringBuffer is preferred for such cases.

10.Exception Handling in Java


Exception handling in Java is a powerful mechanism to handle runtime errors, ensuring that the
normal flow of the application is not disrupted. It involves the use of keywords like try, catch, finally,
throw, and throws. Here’s a detailed explanation:
What are Exceptions?

An exception is an event that disrupts the normal flow of the program. It can occur due to errors like
dividing by zero, accessing an invalid array index, or other unforeseen circumstances during the
execution of the program. Java provides a robust mechanism to handle these exceptions so that the
program can continue executing even after an error occurs.

Examples of common exceptions:

 ArithmeticException: Occurs when there is an arithmetic error (e.g., division by zero).

 ArrayIndexOutOfBoundsException: Occurs when trying to access an invalid index of an


array.

 NullPointerException: Occurs when an object reference is null, but methods or fields are
accessed.

Try, Catch, Finally Blocks

1. try Block: Contains the code that may throw an exception. It is followed by one or more
catch blocks or a finally block.

java

Copy code

try {

// Code that might throw an exception

int result = 10 / 0; // ArithmeticException

2. catch Block: Catches exceptions thrown by the try block and handles them.

java

Copy code

catch (ArithmeticException e) {

// Code to handle the exception

System.out.println("Error: Division by zero");

3. finally Block: This block is always executed after the try-catch block, regardless of whether an
exception occurred or not. It is typically used to close resources like file streams or database
connections.

java

Copy code
finally {

// Code to close resources

System.out.println("This is always executed");

Handling Exceptions with Try-Catch

The general syntax of a try-catch block:

java

Copy code

try {

// Code that may throw an exception

} catch (ExceptionType e) {

// Code to handle the exception

Example:

java

Copy code

try {

int[] arr = new int[5];

arr[10] = 50; // ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {

System.out.println("Error: Array index out of bounds");

Finally Block (Executed Regardless of Exception)

The finally block is always executed after the try-catch blocks, even if no exception occurs or if an
exception is caught. It is generally used for cleaning up resources (e.g., closing files or releasing
database connections).

Example:

java

Copy code

try {
int result = 10 / 2;

System.out.println("Result: " + result);

} catch (ArithmeticException e) {

System.out.println("Error: " + e.getMessage());

} finally {

System.out.println("This will always execute");

Output:

sql

Copy code

Result: 5

This will always execute

Types of Exceptions

Java exceptions are divided into two main categories:

1. Checked Exceptions:

o These exceptions are checked at compile-time. The program will not compile unless
these exceptions are either caught using a try-catch block or declared to be thrown.

o Examples: IOException, SQLException, FileNotFoundException.

o These exceptions must be handled or declared in the method signature using the
throws keyword.

Example:

java

Copy code

try {

FileReader fr = new FileReader("nonexistentfile.txt"); // Checked exception

} catch (IOException e) {

System.out.println("File not found: " + e.getMessage());

2. Unchecked Exceptions (Runtime Exceptions):

o These exceptions are not checked at compile-time. These are usually caused by
programming bugs and do not need to be explicitly handled or declared.
o Examples: NullPointerException, ArrayIndexOutOfBoundsException,
ArithmeticException.

Example:

java

Copy code

try {

int result = 10 / 0; // Unchecked exception

} catch (ArithmeticException e) {

System.out.println("Cannot divide by zero");

Throwing Exceptions

You can throw exceptions manually using the throw keyword. This is often used to enforce certain
conditions or validate input.

Syntax:

java

Copy code

throw new ExceptionType("Error message");

Example:

java

Copy code

public void checkAge(int age) {

if (age < 18) {

throw new IllegalArgumentException("Age must be 18 or older");

System.out.println("Age is valid");

throw Keyword

The throw keyword is used to explicitly throw an exception in your program. It can throw both
checked and unchecked exceptions.

Example:
java

Copy code

public class Example {

public static void main(String[] args) {

try {

throw new Exception("An error occurred");

} catch (Exception e) {

System.out.println("Caught Exception: " + e.getMessage());

throws Keyword (Declaring Exceptions in Method Signature)

The throws keyword is used in a method signature to declare that a method may throw one or more
exceptions. This is typically used with checked exceptions, indicating that the calling method should
handle or declare the exception.

Syntax:

java

Copy code

public void method() throws ExceptionType1, ExceptionType2 {

// Code that may throw exceptions

Example:

java

Copy code

public void readFile() throws IOException {

FileReader fr = new FileReader("file.txt");

fr.read();

In this case, the readFile() method declares that it might throw an IOException, and it must be either
caught or declared by the caller.
Creating Custom Exceptions

You can create your own exception classes by extending the Exception class for checked exceptions
or RuntimeException for unchecked exceptions.

Example:

java

Copy code

class CustomException extends Exception {

public CustomException(String message) {

super(message);

public class Example {

public static void main(String[] args) {

try {

throw new CustomException("This is a custom exception");

} catch (CustomException e) {

System.out.println("Caught: " + e.getMessage());

Output:

vbnet

Copy code

Caught: This is a custom exception

Summary of Exception Handling Concepts

 try: Code block that may throw an exception.

 catch: Code block that handles the exception.

 finally: Code block that executes regardless of an exception.

 Checked Exceptions: Exceptions that must be handled or declared (e.g., IOException).


 Unchecked Exceptions: Exceptions that don't need to be declared (e.g.,
ArithmeticException).

 throw: Used to manually throw exceptions.

 throws: Used to declare exceptions in method signatures.

 Custom Exceptions: User-defined exceptions created by extending Exception or


RuntimeException.

11.Basic Input/Output (I/O) in Java


Input and Output (I/O) operations in Java are essential for interacting with users and external data
sources like files. Java provides multiple ways to handle I/O, from basic user input to reading and
writing files. Here's an overview of the most common I/O methods:

Reading Input from User

To read user input from the console, Java provides various classes, with the most commonly used
being the Scanner class. This class can read input from various sources such as the keyboard
(System.in).

Using the Scanner class to Read Input

The Scanner class in java.util is used to capture user input. Below is an example demonstrating how
to use Scanner to read different types of input.

java

Copy code

import java.util.Scanner;

public class UserInputExample {

public static void main(String[] args) {

// Create a Scanner object to read input from the user


Scanner scanner = new Scanner(System.in);

// Reading a string input

System.out.print("Enter your name: ");

String name = scanner.nextLine();

// Reading an integer input

System.out.print("Enter your age: ");

int age = scanner.nextInt();

// Display the input

System.out.println("Hello, " + name + ". You are " + age + " years old.");

// Close the scanner to prevent resource leak

scanner.close();

 nextLine(): Reads a complete line of text.

 nextInt(): Reads an integer.

 nextDouble(): Reads a floating-point number.

Outputting Data

In Java, you can output data to the console using the System.out object, which provides methods
such as print() and println().

 System.out.print(): Outputs data without moving to the next line.

 System.out.println(): Outputs data followed by a new line.

Example:

java

Copy code

public class OutputExample {

public static void main(String[] args) {


System.out.print("Hello "); // No newline after this output

System.out.print("World!"); // No newline

System.out.println(" - Welcome to Java!"); // Newline after this output

System.out.println("This is a new line.");

Output:

vbnet

Copy code

Hello World! - Welcome to Java!

This is a new line.

12.File I/O (File Handling)


Java provides several classes to perform file operations. You can read from and write to files using
classes like FileReader, BufferedReader, FileWriter, and BufferedWriter.

Reading from Files (FileReader, BufferedReader)

1. FileReader: Used to read characters from a file.

2. BufferedReader: Provides efficient reading of text from a character-based input stream. It


can be used with FileReader to improve performance.

Example of reading from a file:

java

Copy code

import java.io.FileReader;

import java.io.BufferedReader;

import java.io.IOException;

public class FileReadingExample {

public static void main(String[] args) {

try {
// Create FileReader object to read a file

FileReader fileReader = new FileReader("example.txt");

BufferedReader bufferedReader = new BufferedReader(fileReader);

String line;

// Reading line by line until the end of the file

while ((line = bufferedReader.readLine()) != null) {

System.out.println(line);

// Close the reader

bufferedReader.close();

} catch (IOException e) {

e.printStackTrace();

 readLine(): Reads one line of text from the file.

 close(): Closes the file after reading to release the resources.

Writing to Files (FileWriter, BufferedWriter)

1. FileWriter: Used to write characters to a file.

2. BufferedWriter: Writes text to a file efficiently by buffering the data before writing it.

Example of writing to a file:

java

Copy code

import java.io.FileWriter;

import java.io.BufferedWriter;

import java.io.IOException;

public class FileWritingExample {


public static void main(String[] args) {

try {

// Create FileWriter object to write to a file

FileWriter fileWriter = new FileWriter("output.txt");

BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);

// Writing data to the file

bufferedWriter.write("Hello, this is a test!");

bufferedWriter.newLine(); // Add a new line

bufferedWriter.write("Writing to a file in Java.");

// Close the writer

bufferedWriter.close();

} catch (IOException e) {

e.printStackTrace();

 write(): Writes text to the file.

 newLine(): Adds a new line in the file.

 close(): Closes the file after writing.

Summary of I/O Methods:

1. Reading Input:

o Use Scanner class to read data from the user (e.g., nextLine(), nextInt(),
nextDouble()).

2. Outputting Data:

o Use System.out.print() and System.out.println() to display data on the console.

3. File Reading:

o Use FileReader and BufferedReader to read text from a file efficiently.

4. File Writing:
o Use FileWriter and BufferedWriter to write data to a file.

You might also like