Nested Loop in java
1
12
123
1234
12345
Solution:
public class NumberPattern {
public static void main(String[] args) {
// Outer loop for the rows
for (int i = 1; i <= 5; i++) { // Directly using the value 5
// Inner loop for the columns
for (int j = 1; j <= i; j++) {
System.out.print(j); // Print the current column number
}
System.out.println(); // Move to the next line after each row
}
}
}
Parameterized Constructor
Example 1
public class sum {
// Instance variables
int num1;
int num2;
// Parameterized constructor
public sum(int a, int b) {
num1 = a;
num2 = b;
}
// Method to calculate the sum
public int calculateSum() {
return num1 + num2;
}
// Method to display the numbers and their sum
public void displaySum() {
System.out.println(“Number 1: ” + num1);
System.out.println(“Number 2: ” + num2);
System.out.println(“Sum: ” + calculateSum());
}
public static void main(String[] args) {
// Creating an object using the parameterized constructor
sum calculator = new sum(10, 20);
// Displaying the numbers and their sum
calculator.displaySum();
}
}
Example 2
Inheritance in java
Inheritance is a fundamental concept in object-oriented programming that allows a new class (subclass or derived class) to inherit properties and behaviors (fields and methods) from an existing class (superclass or base class). This promotes code reusability and establishes a natural hierarchy between classes.
- Superclass (Parent Class): The class whose properties and methods are inherited.
- Subclass (Child Class): The class that inherits from the superclass.
Syntax of Single Inheritance:// Superclass
class A {
// Fields and methods of the class A
}
// Subclass
class B extends A {
// Fields and methods of the class B
}
Program Example1:
// Superclass
class Animal {
void eat() {
System.out.println(“This animal eats food.”);
}
}
// Subclass
class Dog extends Animal {
void bark() {
System.out.println(“The dog barks.”);
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited method
dog.bark(); // Subclass-specific method
}
}
Program Example2:
class Campus{
String C_name=”GMC”;
}
class School extends Campus
{
String S_name=”GPSS”;
public static void main(String args[]){
School s=new School();
System.out.println(“School name is:”+s.S_name);
System.out.println(“Campus name is:”+s.C_name);
}
}
Compile: javac School.java
Run: java School
Program Example3:
class Father //parent class
{
String surname=”Parajuli”;
}
class son extends Father //class son is child class
{
String name=”rajesh”;
}
public class inherit //driver class
{
public static void main(String args[]) // Main functionn
{
son ss=new son(); //creating an object of child class
System.out.println(“Name of the son is: “+ss.name+ ” ” +ss.surname); //accessing father class member using child class object
}
}
Syntax of Multilevel Inheritance:
class A {
// Fields and methods of the class A
}
class B extends A {
// Fields and methods of the class B
}
class C extends B {
// Fields and methods of the class C
}
Example1:
// Base class (Superclass)
class Animal {
void eat() {
System.out.println(“This animal eats food.”);
}
}
// Intermediate class (Derived class)
class Cat extends Animal {
void meow() {
System.out.println(“The cat meows.”);
}
void scratch() {
System.out.println(“The cat scratches.”);
}
}
// Derived class (Sub-subclass)
class Kitten extends Cat {
void play() {
System.out.println(“The kitten plays.”);
}
}
public class Main {
public static void main(String[] args) {
Kitten kitten = new Kitten();
kitten.eat(); // Inherited from Animal
kitten.meow(); // Inherited from Cat
kitten.scratch(); // Inherited from Cat
kitten.play(); // Defined in Kitten
}
}
Exception Handling Syntax:
public returnType methodName() throws ExceptionType1, ExceptionType2 {
try {
// Code that might throw an exception
throw new ExceptionType1(“Exception message”);
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} finally {
// Code that will always run (e.g., resource cleanup)
}
}
Program Example:
public class Example {
public static void main(String[] args) {
try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println(“Caught Exception: ” + e.getMessage());
} finally {
System.out.println(“Execution finished.”);
}
}
public static void divide(int a, int b) throws ArithmeticException {
if (b == 0) {
throw new ArithmeticException(“Division by zero is not allowed”);
} else {
System.out.println(“Result: ” + a / b);
}
}
}
JDBC Java Database Connectivity
import java.sql.*; // Import the SQL package for database connectivity
// Define a public class named ‘database’
public class database {
// Main method to execute the program
public static void main(String args[]) throws Exception {
try {
// Load the MySQL JDBC driver
Class.forName(“com.mysql.cj.jdbc.Driver”);
// Establish a connection to the database named ‘testdb’ running on localhost
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/testdb”, “root”, “”);
System.out.println(“Connection to database successfully established”);
// Create a Statement object to execute SQL queries
Statement stmt = con.createStatement();
// Execute a query to select all records from the ‘users’ table
ResultSet rs = stmt.executeQuery(“select * from users”);
// Loop through the result set and print the ‘id’ and ‘name’ fields for each record
while (rs.next()) {
// Retrieve the ‘id’ as an integer and ‘name’ as a string, and print them
System.out.println(rs.getInt(“id”) + ” ” + rs.getString(“name”));
}
// Close the database connection
con.close();
} catch (Exception e) {
// Print any exceptions that occur during the process
System.out.print(e);
}
}
}
Q. Inserting data into table at the time of programming
import java.sql.*; // Import the SQL package for database connectivity
// Define a public class named ‘database’
public class database {
// Main method to execute the program
public static void main(String args[]) throws Exception {
try {
// Load the MySQL JDBC driver
Class.forName(“com.mysql.cj.jdbc.Driver”);
// Establish a connection to the database named ‘testdb’ running on localhost
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/testdb”, “root”, “”);
System.out.println(“Connection to database successfully established”);
// Create a Statement object to execute SQL queries
Statement stmt = con.createStatement();
// Insert a new record into the ‘users’ table
String insertQuery = “INSERT INTO users (id, name) VALUES (3, ‘John Doe’)”;
int rowsAffected = stmt.executeUpdate(insertQuery);
if (rowsAffected > 0) {
System.out.println(“Record inserted successfully.”);
}
// Execute a query to select all records from the ‘users’ table
ResultSet rs = stmt.executeQuery(“select * from users”);
// Loop through the result set and print the ‘id’ and ‘name’ fields for each record
while (rs.next()) {
// Retrieve the ‘id’ as an integer and ‘name’ as a string, and print them
System.out.println(rs.getInt(“id”) + ” ” + rs.getString(“name”));
}
// Close the database connection
con.close();
} catch (Exception e) {
// Print any exceptions that occur during the process
System.out.print(e);
}
}
}
Write java program that establish connection with database and execute CRUD operations using JDBC
import java.sql.*; // Import the SQL package for database connectivity
// Define a public class named ‘database’
public class database {
// Main method to execute the program
public static void main(String args[]) throws Exception {
try {
// Load the MySQL JDBC driver
Class.forName(“com.mysql.cj.jdbc.Driver”);
// Establish a connection to the database named ‘testdb’ running on localhost
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/testdb”, “root”, “”);
System.out.println(“Connection to database successfully established”);
// Create a Statement object to execute SQL queries
Statement stmt = con.createStatement();
// 1. CREATE: Insert a new record into the ‘users’ table
String insertQuery = “INSERT INTO users (id, name) VALUES (1, ‘Alice’), (2, ‘Bob’), (3, ‘Charlie’)”;
int rowsAffected = stmt.executeUpdate(insertQuery);
System.out.println(“Inserted ” + rowsAffected + ” records into the ‘users’ table.”);
// 2. READ: Retrieve and display all records from the ‘users’ table
System.out.println(“Reading records from the ‘users’ table:”);
ResultSet rs = stmt.executeQuery(“SELECT * FROM users”);
while (rs.next()) {
System.out.println(rs.getInt(“id”) + ” ” + rs.getString(“name”));
}
// 3. UPDATE: Update a record in the ‘users’ table
String updateQuery = “UPDATE users SET name = ‘David’ WHERE id = 2”;
rowsAffected = stmt.executeUpdate(updateQuery);
System.out.println(“Updated ” + rowsAffected + ” record(s) in the ‘users’ table.”);
// 4. DELETE: Delete a record from the ‘users’ table
String deleteQuery = “DELETE FROM users WHERE id = 3”;
rowsAffected = stmt.executeUpdate(deleteQuery);
System.out.println(“Deleted ” + rowsAffected + ” record(s) from the ‘users’ table.”);
// Verify the changes after UPDATE and DELETE
System.out.println(“Verifying the updated records:”);
rs = stmt.executeQuery(“SELECT * FROM users”);
while (rs.next()) {
System.out.println(rs.getInt(“id”) + ” ” + rs.getString(“name”));
}
// Close the database connection
con.close();
} catch (Exception e) {
// Print any exceptions that occur during the process
System.out.print(e);
}
}
}