parajulirajesh.com.np

Assignment

program example to implement throw keyword used to throw an exception explicity program example

public class ThrowExample {

// Method to divide two numbers
static int divide(int a, int b) {
if (b == 0) {
// Explicitly throwing an exception
throw new ArithmeticException(“Cannot divide by zero!”);
}
return a / b;
}

public static void main(String[] args) {
try {
int result = divide(10, 0); // Will trigger the exception
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
System.out.println(“Exception caught: ” + e.getMessage());
}

System.out.println(“Program continues…”);
}
}

throws keyword used program example

public class DivideByZeroThrows {

// Method declaring exception using throws
static int divide(int a, int b) throws ArithmeticException {
return a / b; // May throw ArithmeticException
}

public static void main(String[] args) {
try {
int result = divide(10, 0); // Calling method
System.out.println(“Result: ” + result);
} catch (ArithmeticException e) {
System.out.println(“Exception handled: Cannot divide by zero.”);
}

System.out.println(“Program continues…”);
}
}

Write a java program to read a data from the file "numbers.txt" using character stream.

import java.io.FileReader;
import java.io.IOException;

public class ReadNumbers {
public static void main(String[] args) {
try {
FileReader fr = new FileReader(“numbers.txt”);
int ch;

while((ch = fr.read()) != 1){
System.out.print((char)ch);
}

fr.close();
}
catch(IOException e){
System.out.println(e);
}
}
}

 

1. Import Statements

 
import java.io.FileReader;
import java.io.IOException;
 

import java.io.FileReader;

  • Imports the FileReader class from the java.io package.
  • It is used to read characters from a file.

import java.io.IOException;

  • Imports the IOException class.
  • This exception occurs when there is an error during file operations like:
      • File not found
      • File cannot be opened
      • File reading error

2. Class Declaration

 
public class ReadNumbers
 
  • Declares a class named ReadNumbers.
  • Every Java program must have at least one class.

3. Main Method

 
public static void main(String[] args)
 

This is the starting point of the Java program.

Explanation:

KeywordMeaning
publicaccessible from anywhere
staticcan run without creating object
voiddoes not return value
main()program execution starts here

4. Try Block

 
try {
 
  • Used for exception handling.
  • File operations may cause errors, so we place them inside try.

5. Creating FileReader Object

 
FileReader fr = new FileReader(“numbers.txt”);
 

Explanation:

  • FileReaderclass used to read characters from file
  • frobject of FileReader
  • "numbers.txt"file to be read

So this line means:

Open the file numbers.txt for reading

If the file does not exist, an IOException occurs.


6. Declaring Variable

 
int ch;
 
  • ch stores the character read from the file
  • read() returns an integer value (ASCII/Unicode)

Example:

CharacterASCII Value
149
250
space32

7. While Loop (Reading File)

 
while((ch = fr.read()) != 1)
 

This is the most important line.

Step-by-step process

  1. fr.read() reads one character from the file
  2. The character value is stored in ch
  3. If the file has data, it continues
  4. If end of file, read() returns 1
  5. Loop stops when 1 is reached

Example file content:

10 20
 

Characters read:

StepCharacterASCII
1149
2048
3space32
4250
5048

8. Printing the Character

 
System.out.print((char)ch);
 
  • ch contains ASCII value
  • (char)ch converts it to actual character

Example:

Value in chAfter (char)Output
491′1
480′0

So the program prints the same content as the file.


9. Closing the File

 
fr.close();
 
  • Closes the file after reading.
  • Important to release system resources.

10. Catch Block

 
catch(IOException e){
System.out.println(e);
}
 

Handles errors during file reading.

Example errors:

  • File not found
  • Permission denied
  • File read error

If an error occurs, it prints the exception message.

import java.sql.*;

public class SimpleJDBC {
public static void main(String[] args) {

// Step 1: Register Driver
try {
Class.forName(“com.mysql.cj.jdbc.Driver”);

// Step 2: Create Connection
String url = “jdbc:mysql://localhost:3306/”;
String user = “root”;
String password = “”; // XAMPP default is empty

Connection con = DriverManager.getConnection(url, user, password);
System.out.println(“Connected Successfully!”);

// Step 3: Create Statement
Statement stmt = con.createStatement();

// Step 4: Write Query (Create Database if not exists)
String query = “CREATE DATABASE IF NOT EXISTS mydatabase”;
stmt.executeUpdate(query);
System.out.println(“Database created or already exists!”);

// Step 5: (Optional) Fetch databases using ResultSet
ResultSet rs = stmt.executeQuery(“SHOW DATABASES”);

System.out.println(“List of Databases:”);
while (rs.next()) {
System.out.println(rs.getString(1));
}

// Step 6: Close connections
rs.close();
stmt.close();
con.close();

System.out.println(“Connection Closed!”);

} catch (Exception e) {
System.out.println(e);
}
}
}

write java program to Create Database, Create Table, Insert Data, and Retrieve Data from the database

import java.sql.*;

public class FullJDBCExample {
public static void main(String[] args) {

try {
// Step 1: Register Driver
Class.forName(“com.mysql.cj.jdbc.Driver”);

// Step 2: Connect to MySQL (no database yet)
Connection con = DriverManager.getConnection(
“jdbc:mysql://localhost:3306/”,
“root”,
“”
);

Statement stmt = con.createStatement();

// Step 3: Create Database
stmt.executeUpdate(“CREATE DATABASE IF NOT EXISTS studentdb”);
System.out.println(“Database created!”);

// Step 4: Use Database
stmt.executeUpdate(“USE studentdb”);

// Step 5: Create Table
String createTable = “CREATE TABLE IF NOT EXISTS students (” +
“id INT PRIMARY KEY AUTO_INCREMENT, ” +
“name VARCHAR(50), ” +
“age INT)”;
stmt.executeUpdate(createTable);
System.out.println(“Table created!”);

// Step 6: Insert Data
stmt.executeUpdate(“INSERT INTO students(name, age) VALUES (‘Ram’, 22)”);
stmt.executeUpdate(“INSERT INTO students(name, age) VALUES (‘Shyam’, 24)”);
System.out.println(“Data inserted!”);

// Step 7: Retrieve Data
ResultSet rs = stmt.executeQuery(“SELECT * FROM students”);

System.out.println(“Student Records:”);
while (rs.next()) {
System.out.println(
rs.getInt(“id”) + ” ” +
rs.getString(“name”) + ” ” +
rs.getInt(“age”)
);
}

// Step 8: Close Connection
rs.close();
stmt.close();
con.close();

System.out.println(“Connection closed!”);

} catch (Exception e) {
System.out.println(e);
}
}
}

Scroll to Top

Rajesh Parajuli

BICTE GMC

LEC.RAJESH PARAJULI

Address: Ghodaghodi Municipality-1 Sukhad kailali

Contact: 9847546279

Ghodaghodi Multiple Campus BICTE