0% found this document useful (0 votes)
9 views28 pages

Java Note

Uploaded by

homephonenova7
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
9 views28 pages

Java Note

Uploaded by

homephonenova7
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 28

// Import statements (optional)

import java.util.Scanner*;

// Class declaration
public class ClassName {

// Fields (variables)
private int field1;
private String field2;

// Constructor
public ClassName() {
// Initialization code
}

// Overloaded Constructor (optional)


public ClassName(int field1, String field2) {
this.field1 = field1;
this.field2 = field2;
}

// Methods
public void someMethod() {
// Method code
}

// Getter and Setter methods (optional)


public int getField1() {
return field1;
}

public void setField1(int field1) {


this.field1 = field1;
}

// Main method (if needed)


public static void main(String[] args) {
// Create object and test the class
ClassName obj = new ClassName();
obj.someMethod();
}
}
// Step 1: Import the Scanner class
import java.util.Scanner;

public class UserInputExample {


public static void main(String[] args) {

// Step 2: Create a Scanner object


Scanner scanner = new Scanner(System.in);

// Step 3: Get String input from the user


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

// Read a String
String name = scanner.nextLine();

// Get integer input from the user


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

// Read an integer
int age = scanner.nextInt();

// Get double input from the user


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

// Read a double
double gpa = scanner.nextDouble();

// Get boolean input from the user


System.out.print("(true/false): ");

// Read a boolean
boolean isFullTime = scanner.nextBoolean();

// Output the input values


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("GPA: " + gpa);
// Close the scanner to prevent resource leaks
scanner.close();

Loops
For :

for (initialization; condition; update) {


// Code to be executed
}
for (int i = 0; i < 5; i++) {
System.out.println(i); // Prints numbers from 0 to 4
}

While:-
while (condition) {
// Code to be executed
}

int i = 0;
while (i < 5) {
System.out.println(i); // Prints numbers from 0 to 4
i++;
}

do – while :-
do {
// Code to be executed
} while (condition);

int i = 0;
do {
System.out.println(i); // Prints numbers from 0 to 4
i++;
} while (i < 5);

loop through array


Traditional for Loop
int[] numbers = {10, 20, 30, 40, 50};

// Use a for loop to iterate through the array


for (int i = 0; i < numbers.length; i++) {
System.out.println("Element at index " + i + ": " + numbers[i]);
}

Enhanced for Loop (for-each)

for (dataType element : array) {


// Code to be executed
}

int[] numbers = {1, 2, 3, 4, 5};


for (int number : numbers) {
System.out.println(number); // Prints each element in the array
}

File handling
Key Classes in File Handling:
1.File Class: Used to create, delete, and get
information about a file or directory.
2.FileWriter Class: Used to write data to a file.
3.FileReader Class: Used to read data from a
file.
4.BufferedReader & BufferedWriter: Used to
efficiently read from or write to a file.
These libraries needs to be import
(When creates file/ Delete file)
import java.io.File;

(When use normal file reader )


import java.io.FileReader;
(When use bufferreader)
import java.io.FileReader
import java.io.BufferedReader;

(When use normal file writer )


import java.io.FileWriter;

(When use normal bufferwriter )


import java.io.FileWriter;
import java.io.BufferedWriter;

5. 1. Creating a File
6. The File class can be used to create a file.

public static void main(String[] args) {


File file = new File("example.txt");
file.createNewFile(); // No try-catch for IOException here
}

Writing
FileWriter writer = new FileWriter("filename.txt");
writer.write("Hello, World!");
writer.close();

BufferedWriter bw = new BufferedWriter(new FileWriter("filename.txt"));


bw.write("Hello, World!");
bw.newLine();
bw.close();

Behavior:

1. File Doesn't Exist: If "example.txt" doesn't exist, FileWriter will create it.
2. File Already Exists: If the file exists, the contents will be overwritten (unless appending
mode is specified).

Appending Mode:

To prevent overwriting and append data to the file instead, you can use FileWriter in append
mode:

BufferedWriter writer = new BufferedWriter(new FileWriter("example.txt",


true)); // true enables append mode
Deleting
import java.io.File;

public class DeleteFile {


public static void main(String[] args) {
File file = new File("example.txt");
file.delete(); // Deletes the file
}
}

Reading
import java.io.FileReader;

public class ReadFile {


public static void main(String[] args) throws Exception {
FileReader reader = new FileReader("example.txt");
int ch;
while ((ch = reader.read()) != -1) {
System.out.print(ch);
}
reader.close(); // Close the file after reading
}
}

import java.io.BufferedReader;
import java.io.FileReader;

public class ReadFileWithBuffer {


public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close(); // Always close the buffer after use
}
}

 FileReader("example.txt"): Opens the file for


reading.
 reader.read(): Reads one character at a time
until the end of the file (-1).
 close(): Always close the file after use to free
resources.

in Java, handling exceptions is mandatory when


dealing with file handling operations because
many of the methods involved (such as reading
from or writing to files) can throw checked
exceptions, particularly IOException.

Options to Handle Exceptions


Using try-catch:

This is the recommended approach because it allows you to handle the


exception within the method, improving robustness.
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {


public static void main(String[] args) {
try {
FileReader reader = new FileReader("example.txt");
int ch;
while ((ch = reader.read()) != -1) {
System.out.print((char) ch);
}
reader.close();
} catch (IOException e) {
e.printStackTrace(); // Handles the exception
}
}
}

Using throws:

If you don't want to handle the exception in your method, you can pass the
responsibility to the calling method using the throws keyword.
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {


public static void main(String[] args) throws IOException {
FileReader reader = new FileReader("example.txt");
int ch;
while ((ch = reader.read()) != -1) {
System.out.print(ch);
}
reader.close(); // Close the file after reading
}
}

Complete Example with try-catch:


import java.io.*;

public class FileOperations {


public static void main(String[] args) {
// 1. Creating and Writing to a File
try {
BufferedWriter writer = new BufferedWriter(new
FileWriter("example.txt"));
writer.write("Hello, World!");
writer.newLine(); // Adds a new line
writer.write("This is a test file.");
writer.close(); // Close the buffer after writing
System.out.println("File created and written successfully.");
} catch (IOException e) {
e.printStackTrace();
}

// 2. Reading from the File


try {
BufferedReader reader = new BufferedReader(new
FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // Print each line from the file
}
reader.close(); // Close the buffer after reading
} catch (IOException e) {
e.printStackTrace();
}

// 3. Deleting the File


File file = new File("example.txt");
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
}
}

Complete Example with throws:


import java.io.*;

public class FileOperationsWithThrows {

public static void main(String[] args) throws IOException {


createAndWriteFile();
readFile();
deleteFile();
}

// 1. Creating and Writing to a File


public static void createAndWriteFile() throws IOException {
BufferedWriter writer = new BufferedWriter(new
FileWriter("example.txt"));
writer.write("Hello, World!");
writer.newLine(); // Adds a new line
writer.write("This is a test file.");
writer.close(); // Close the buffer after writing
System.out.println("File created and written successfully.");
}

// 2. Reading from the File


public static void readFile() throws IOException {
BufferedReader reader = new BufferedReader(new
FileReader("example.txt"));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // Print each line from the file
}
reader.close(); // Close the buffer after reading
}

// 3. Deleting the File


public static void deleteFile() throws IOException {
File file = new File("example.txt");
if (file.delete()) {
System.out.println("File deleted successfully.");
} else {
System.out.println("Failed to delete the file.");
}
}
}

String Class
Immutable: Once a String object is created, it cannot be changed. Any
operation that modifies a string creates a new object.

String Creation:

1. Using String Literals:

String str = "Hello";

2. Using new Keyword:


String str = new String("Hello");

charAt(int index):

Returns the character at the specified index.


String str = "Hello";
char ch = str.charAt(1); // ch = 'e'

length(): Returns the length of the string.


int len = str.length(); // len = 5

substring(int beginIndex, int endIndex): Extracts a substring.


String sub = str.substring(0, 3); // sub = "Hel"

toLowerCase() / toUpperCase(): Converts the string to lowercase or uppercase.


String lower = str.toLowerCase(); // lower = "hello"

trim(): Removes leading and trailing whitespace.


String trimmed = " Hello ".trim(); // trimmed = "Hello"

equals(Object obj) / equalsIgnoreCase(String anotherString): Compares two


strings for equality.
boolean isEqual = str.equals("hello"); // false

split(String regex): Splits a string based on a delimiter or regular expression.


String[] parts = str.split(" "); // Splits "Hello World" into ["Hello",
"World"]

replace(char oldChar, char newChar): Replaces occurrences of a character.


String newStr = str.replace('l', 'r'); // newStr = "Herro"

String Builder

 Mutable: Unlike String, which is immutable, StringBuilder allows


modifications to its content without creating new objects.
 Efficient: Provides better performance than String when dealing
with multiple string manipulations (e.g., appending, inserting, or
deleting).
 Non-Synchronized: It is not thread-safe (use StringBuffer for
thread-safe operations).

Declaration:

With Initial Content:

Common Methods:

append(): Adds a string or any other data type to the end.


sb.insert(5, ","); // sb = "Hello, World"

insert(index, str): Inserts a string at the specified index.


sb.insert(5, ","); // sb = "Hello, World"

delete(start, end): Removes characters between start (inclusive) and


end (exclusive).
sb.delete(5, 7); // sb = "HelloWorld"

replace(start, end, str): Replaces the characters between start and end
with the given string.
sb.replace(5, 10, "Java"); // sb = "Hello Java"

reverse(): Reverses the contents of the StringBuilder.


sb.reverse(); // sb = "avaJ olleH"
toString(): Converts the StringBuilder to a String.
String result = sb.toString();

ength() and capacity():

 length(): Returns the number of characters in the builder.

 capacity(): Returns the current capacity (allocated storage space).

int len = sb.length(); // Returns the length of the string


int cap = sb.capacity(); // Returns the capacity of the builder

Arrays
2-D Arrays
Array List
Key Points:

 Resizable: Unlike arrays, ArrayList can dynamically grow or shrink in


size.

 Performance: Insertion and removal of elements from the end are


fast (O(1)), but inserting or removing elements from the middle is
slower (O(n)).

 Generic: You can specify the type of elements it stores, ensuring type
safety (e.g., ArrayList<Integer>, ArrayList<String>).
ArrayLists are widely used for dynamic data storage when the number of
elements can vary during runtime.

Map
Key Points:

 Efficiency: HashMap offers constant-time performance (O(1)) for basic operations like
put() and get().
 Sorted Map: Use TreeMap if you need sorted keys.
 Iteration Order: Use LinkedHashMap to maintain insertion order.

Map is a powerful data structure for associating keys with values, and it is widely used for
lookups, counting occurrences, or representing relationships between entities.

Speed comparison
Time

1. O(1) - Constant Time Complexity

Definition: An algorithm is said to have O(1) time complexity if its


execution time remains constant, regardless of the size of the input data.
In other words, the running time does not change as the input grows.

O(n) - Linear Time Complexity

Definition: An algorithm has O(n) time complexity if its running time grows linearly with the
size of the input. In other words, if the input size doubles, the running time will also double.

You might also like