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

Index Java 1.1.0

The document contains 22 questions related to Java programming concepts and examples of code to implement those concepts. The questions cover topics such as finding the number of digits in a number, calculating factorials recursively, multiplying matrices, generating Fibonacci sequences, printing diamond patterns, using static variables, constructors, inheritance, packages and more. Sample code is provided as the answer for each question.

Uploaded by

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

Index Java 1.1.0

The document contains 22 questions related to Java programming concepts and examples of code to implement those concepts. The questions cover topics such as finding the number of digits in a number, calculating factorials recursively, multiplying matrices, generating Fibonacci sequences, printing diamond patterns, using static variables, constructors, inheritance, packages and more. Sample code is provided as the answer for each question.

Uploaded by

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

P age |2

INDEX

S_no. TITLE Page no.

1. Write a program to find number of digits in a number input by the user.

2. Write a program to find the factorial of a number using recursion.

3. Write a java program to find product of two matrices in java.

4. Write a program to print fibnonic series in java

5. Write a program to print diamond pattern in java.

6. Write a program to implement static variable in java.

7. Write a program to implement constructors in java.

8. Create a user defined package and use their classes in java.

9. Write a program to implement simple inheritance in java.

10. Write a program to implement Hierarchical inheritance in java

11. Write a program to implement method overloading in java.

12. Write a program to implement method overriding in java.

13. Write a program to implement dynamic method dispatch in java.

14. Write a program to implement abstract class in java.

15. Write a program to implement interfaces in java.

16. Write a simple Multithread program in java.

17. Write a program to handle try and multiple catch block.

18. Create a custom exception and throw in case of age<18 for voting.

19. Create a student table using <TABLE> tag in html.

20. Write a program to draw different shapes using graphics methods.

21. Create a login form in AWT.

22. Create a calculator using event listener in java.


Q-1 Write a program to find number of digits in a number input by the user?

import java.util.Scanner;

public class NumberOfDigits {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.print("Enter a number: ");


int number = scanner.nextInt();

// Handle negative numbers:


if (number < 0) {
number = -number; // Convert to positive for accurate digit count
}

// Using Math.log10() for efficiency and clarity:


int numOfDigits = (int) Math.ceil(Math.log10(number)) + 1;

// Handle special cases (0 and negative number with 1 digit):


if (number == 0) {
numOfDigits = 1;
}

System.out.println("The number of digits in " + number + " is: " + numOfDigits);


}
}
Q-2Write a program to find the factorial of a number using recursion ?
public class Factorial {

public static long factorial(int n) {

if (n == 0) {

return 1;

} else if (n < 0) {

throw new IllegalArgumentException("Factorial is not defined for negative numbers");

} else {

return n * factorial(n - 1);

}}

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a non-negative number: ");

int number = scanner.nextInt();

try {

long result = factorial(number);

System.out.println("The factorial of " + number + " is: " + result);

} catch (IllegalArgumentException e) {

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

}
Q-3Write a java program to find product of two matrices in java?
public class MatrixProduct {

public static void main(String[] args) {

// Input matrices (modify these as needed)

int[][] matrixA = {

{1, 2, 3},

{4, 5, 6}

};

int[][] matrixB = {

{7, 8},

{9, 10},

{11, 12}

};

// Validate matrix dimensions for multiplication

if (matrixA[0].length != matrixB.length) {

System.out.println("Error: matrices cannot be multiplied. Number of columns in first matrix ("

+ matrixA[0].length + ") must equal number of rows in second matrix (" + matrixB.length
+ ").");

return;

// Calculate product matrix

int[][] product = new int[matrixA.length][matrixB[0].length];

for (int i = 0; i < matrixA.length; i++) {

for (int j = 0; j < matrixB[0].length; j++) {

for (int k = 0; k < matrixA[0].length; k++) {

product[i][j] += matrixA[i][k] * matrixB[k][j];

} // Print the original matrices and the product matrix

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

printMatrix(matrixA);

System.out.println("Matrix B:");
printMatrix(matrixB);

System.out.println("Product of matrices:");

printMatrix(product);

// Helper function to print a matrix

public static void printMatrix(int[][] matrix) {

for (int i = 0; i < matrix.length; i++) {

for (int j = 0; j < matrix[i].length; j++) {

System.out.print(matrix[i][j] + " ");

System.out.println();

}
Q-4 Write a program to print fibnonic series in java ?
public class FibonacciRecursion {

public static int fibonacci(int n) {


if (n <= 1) {
return n;
} else {
return fibonacci(n - 1) + fibonacci(n - 2);
}
}

public static void main(String[] args) {


int numTerms = 10;

for (int i = 0; i < numTerms; i++) {


System.out.print(fibonacci(i) + " ");
}
}
}
Q=5 Write a program to print diamond pattern in java?
import java.util.Scanner;
public class DiamondPattern {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of rows: ");
int rows = scanner.nextInt();
if (rows <= 0) {
System.out.println("Error: Number of rows must be positive.");
return;
}

int midRow = (rows + 1) / 2;


for (int i = 1; i <= midRow; i++) {
for (int j = 1; j <= midRow - i; j++) {
System.out.print(" ");
}

for (int j = 1; j <= 2 * i - 1; j++) {


System.out.print("*");
}

System.out.println();
}
for (int i = midRow - 1; i >= 1; i--) {
for (int j = 1; j <= midRow - i; j++) {
System.out.print(" ");
}

for (int j = 1; j <= 2 * i - 1; j++) {


System.out.print("*");
}

System.out.println();
}
}

}
Q-6Write a program to implement static variable in java.?
Employee emp1 = new Employee("Alice", 101);

Employee emp2 = new Employee("Bob", 102);

emp1.display();

emp2.display();

Employee.company = "XYZ Ltd.";

emp1.display();

emp2.display();

OUTPUT

Name: Alice
ID: 101
Company: ABC Inc.
Name: Bob
ID: 102
Company: ABC Inc.
Name: Alice
ID: 101
Company: XYZ Ltd.
Name: Bob
ID: 102
Company: XYZ Ltd.
Q-7 Write a program to implement constructors in java?
// Define a class
class Car {
String make;
String model;
int year;

public Car(String make, String model, int year) {


this.make = make;
this.model = model;
this.year = year;
}
public Car() {
this.make = "Unknown";
this.model = "Unknown";
this.year = 0;
}
public void displayInfo() {
System.out.println("Make: " + make);
System.out.println("Model: " + model);
System.out.println("Year: " + year);
}
}
public class Main {
public static void main(String[] args) {
// Creating objects using different constructors
Car car1 = new Car("Toyota", "Camry", 2020);
Car car2 = new Car();

System.out.println("Car 1:");
car1.displayInfo();
System.out.println("\nCar 2:");
car2.displayInfo();
}
}
Q-8Create a user defined package and use their classes in java.?
└── example

└── mypackage

└── Calculator.java

package com.example.mypackage;

public class Calculator {

public int add(int a, int b) {

return a + b;

public int subtract(int a, int b) {

return a - b;

}
// Main.java
import com.example.mypackage.Calculator;
public class Main {
public static void main(String[] args) {
Calculator calculator = new Calculator();
int result1 = calculator.add(5, 3);
System.out.println("5 + 3 = " + result1);
int result2 = calculator.subtract(10, 4);
System.out.println("10 - 4 = " + result2);
}
}

OUTPUT
5+3=8
10 - 4 = 6
Q-9 Write a program to implement simple inheritance in java.?
// Parent class
class Vehicle {
// Me String brand;
int year;
public Vehicle(String brand, int year) {
this.brand = brand;
this.year = year;
public void displayInfo() {
System.out.println("Brand: " + brand);
System.out.println("Year: " + year);
}
}
class Car extends Vehicle {
int mileage;
public Car(String brand, int year, int mileage) {
super(brand, year);
this.mileage = mileage;
}
public void displayCarInfo() {
displayInfo();
System.out.println("Mileage: " + mileage);
}
}
public class Main {
public static void main(String[] args) {
// Create a Car object
Car myCar = new Car("Toyota", 2020, 50000);
System.out.println("Car Information:");
myCar.displayCarInfo();
}
}
Q-10Write a program to implement Hierarchical inheritance in java?
// Parent class

class Vehicle {

String brand;

int year;

public Vehicle(String brand, int year) {

this.brand = brand;

this.year = year;

public void displayInfo() {

System.out.println("Brand: " + brand);

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

class Car extends Vehicle {

int mileage;

public Car(String brand, int year, int mileage) {

super(brand, year);

this.mileage = mileage;

public void displayCarInfo() {

displayInfo();

System.out.println("Mileage: " + mileage);

class Truck extends Vehicle {

int capacity;

public Truck(String brand, int year, int capacity) {

super(brand, year);

this.capacity = capacity;

}
public void displayTruckInfo() {

displayInfo();

System.out.println("Capacity: " + capacity + " tons");

public class Main {

public static void main(String[] args) {

Car myCar = new Car("Toyota", 2020, 50

Truck myTruck = new Truck("Ford", 2018, 5);

System.out.println("Car Information:");

myCar.displayCarInfo();

System.out.println("\nTruck Information:");

myTruck.displayTruckInfo();

}
Q-11 Write a program to implement method overloading in java.?
public class OverloadingExample {
public int add(int a, int b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}

public double add(double a, double b) {


return a + b;
}
public String add(String a, String b) {
return a + b;
}

public static void main(String[] args) {


OverloadingExample obj = new OverloadingExample();
int sum1 = obj.add(3, 4);
System.out.println("Sum of 3 and 4 is: " + sum1);

int sum2 = obj.add(3, 4, 5);


System.out.println("Sum of 3, 4, and 5 is: " + sum2);

double sum3 = obj.add(3.5, 4.5);


System.out.println("Sum of 3.5 and 4.5 is: " + sum3);

String result = obj.add("Hello", " World");


System.out.println("Concatenated string: " + result);
}

}
Q-12 Write a program to implement method overriding in java.?

// Parent class

class Animal {

// Method to make sound

public void makeSound() {

System.out.println("Animal makes a sound"); }}

class Dog extends Animal {

@Override

public void makeSound() {

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

class Cat extends Animal @Override

public void makeSound() {

System.out.println("Cat meows"); }}

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();

Cat myCat = new Cat();

System.out.print("Dog: ");

myDog.makeSound();

System.out.print("Cat: ");

myCat.makeSound();

}
Q-13Write a program to implement dynamic method dispatch in java.?
// Parent class

class Animal {

public void makeSound() {

System.out.println("Animal makes a sound");}}

class Dog extends Animal

@Override

public void makeSound() {

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

class Cat extends Animal { @Override

public void makeSound() {

System.out.println("Cat meows"); }}public class Main {

public static void main(String[] args) {

Animal myDog = new Dog();

Animal myCat = new Cat();

System.out.print("Dog: ");

myDog.makeSound();

System.out.print("Cat: ");

myCat.makeSound();}}
Q-14 Write a program to implement abstract class in java.?

// Abstract class

abstract class Shape { abstract double calculateArea();

class Circle extends Shape {

double radius; public Circle(double radius) {

this.radius = radius;

}@Override

double calculateArea() { return Math.PI * radius * radius;

}}

class Rectangle extends Shape {double length;

double width; public Rectangle(double length, double width) {

this.length = length;

this.width = width;

} @Override double calculateArea() {

return length * width; }

public class Main {

public static void main(String[] args) {

Circle circle = new Circle(5);

Rectangle rectangle = new Rectangle(4, 6);

System.out.println("Area of Circle: " + circle.calculateArea()); System.out.println("Area of Rectangle:


" + rectangle.calculateArea());

}}
Q-15 Write a program to implement interfaces in java.?

// Interface defining methods for a shape

interface Shape {

double calculateArea(); double calculatePerimeter();

class Circle implements Shape {

double radius;

public Circle(double radius) {

this.radius = radius;

@Override

public double calculateArea() {

return Math.PI * radius * radius;

@Override

public double calculatePerimeter() {

return 2 * Math.PI * radius;

class Rectangle implements Shape {

double length;

double width;

public Rectangle(double length, double width) {

this.length = length;

this.width = width;

@Override

public double calculateArea() {

return length * width;

} @Override
public double calculatePerimeter() {

return 2 * (length + width);

// Main class

public class Main {

public static void main(String[] args) {

Circle circle = new Circle(5);

Rectangle rectangle = new Rectangle(4, 6);

System.out.println("Circle - Area: " + circle.calculateArea() + ", Perimeter: " +


circle.calculatePerimeter());

System.out.println("Rectangle - Area: " + rectangle.calculateArea() + ", Perimeter: " +


rectangle.calculatePerimeter());

}
Q-16Write a simple Multithread program in java.?
// Define a class that implements the Runnable interface

class MyRunnable implements Runnable { @Override

public void run() {

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

System.out.println(Thread.currentThread().getName() + ": " + i);

try {

Thread.sleep((long) (Math.random() * 1000));

} catch (InterruptedException e) {

e.printStackTrace();

}}}}

public class Main {

public static void main(String[] args) {

Thread thread1 = new Thread(new MyRunnable(), "Thread 1");

Thread thread2 = new Thread(new MyRunnable(), "Thread 2");

thread1.start();

thread2.start();

}
Q-17Write a program to handle try and multiple catch block.?
public class Main {

public static void main(String[] args) {

try {

int result = divide(10, 0);

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

} catch (ArithmeticException e) {

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

} catch (ArrayIndexOutOfBoundsException e) {

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

} catch (Exception e) {

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

} public static int divide(int a, int b) {

return a / b;

}
Q-18Create a custom exception and throw in case of age<18 for voting.?
// Custom exception class for invalid age

class InvalidAgeException extends Exception {

public InvalidAgeException(String message) {

super(message);}}

public class Main {

public static void canVote(int age) throws InvalidAgeException {

if (age < 18) {

throw new InvalidAgeException("Age is less than 18, cannot vote.");

} else {

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

}} public static void main(String[] args) {

try {

canVote(16); // Age less than 18

} catch (InvalidAgeException e) {

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

}
Q-19Create a student table using <TABLE> tag in html.?
<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Student Table</title>

<style>

table {

width: 100%;

border-collapse: collapse;

th, td {

border: 1px solid black;

padding: 8px;

text-align: left;

th {

background-color: #f2f2f2;

</style>

</head>

<body>

<h2>Student Table</h2>

<table>

<tr>

<th>ID</th>

<th>Name</th>

<th>Age</th>
<th>Grade</th>

</tr>

<tr>

<td>1</td>

<td>John Doe</td>

<td>18</td>

<td>12</td>

</tr>

<tr>

<td>2</td>

<td>Jane Smith</td>

<td>17</td>

<td>11</td>

</tr>

<tr>

<td>3</td>

<td>Michael Johnson</td>

<td>16</td>

<td>10</td>

</tr>

</table>

</body>

</html>
Q-20 Write a program to draw different shapes using graphics methods.?

import javax.swing.*;

import java.awt.*;

public class DrawShapes extends JFrame {

public DrawShapes() {

setTitle("Drawing Shapes");

setSize(400, 400);

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

setLocationRelativeTo(null);

setVisible(true);

} @Override

public void paint(Graphics g) {

super.paint(g);

g.setColor(Color.BLUE);

g.drawLine(50, 50, 200, 50);

g.setColor(Color.RED);

g.drawRect(50, 100, 100, 50);

g.setColor(Color.GREEN);

g.fillRect(200, 100, 100, 50);

g.setColor(Color.MAGENTA);

g.drawOval(50, 200, 100, 50);

g.setColor(Color.ORANGE);

g.fillOval(200, 200, 100, 50); g.setColor(Color.CYAN);

g.drawRoundRect(50, 300, 100, 50, 10, 10);

g.setColor(Color.YELLOW) g.fillRoundRect(200, 300, 100, 50, 20, 20);

} public static void main(String[] args) {

new DrawShapes();

}}
Q-21 Create a login form in AWT.?
import java.awt.*;
import java.awt.event.*;

public class LoginForm extends Frame implements ActionListener {


TextField usernameField, passwordField;
Button loginButton;
Label messageLabel;

public LoginForm() {
setLayout(new FlowLayout());
add(new Label("Username:"));
usernameField = new TextField(20);
add(usernameField);
add(new Label("Password:"));
passwordField = new TextField(20);
passwordField.setEchoChar('*');
add(passwordField);
loginButton = new Button("Login");
add(loginButton);
messageLabel = new Label();
add(messageLabel);
loginButton.addActionListener(this);
setTitle("Login Form");
setSize(300, 150);
setVisible(true);
}

@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText();
String password = passwordField.getText();

if (username.equals("admin") && password.equals("password")) {


messageLabel.setText("Login Successful!");
} else {
messageLabel.setText("Invalid Username or Password!");
}
}

public static void main(String[] args) {


new LoginForm();
}

}
Q-22 Create a calculator using event listener in java.?
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class GUICalculator extends JFrame {


private JButton button1;
private JButton button2;
private JButton button3;
private JButton button4;
private JTextField textField1;
private JTextField textField2;
private JTextField textField3;

public static void main(String[] args) {


GUICalculator cal = new GUICalculator();
cal.setTitle("GUI Calculator");
cal.setSize(600, 400);
cal.setVisible(true);
cal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public GUICalculator() {
JPanel panel1 = new JPanel();
button1 = new JButton("+");
button2 = new JButton("-");
button3 = new JButton("*");
button4 = new JButton("/");
textField1 = new JTextField(20);
textField2 = new JTextField(20);
textField3 = new JTextField(20);

ListenForButton listenForButton = new ListenForButton();


button1.addActionListener(listenForButton);
button2.addActionListener(listenForButton);
button3.addActionListener(listenForButton);
button4.addActionListener(listenForButton);

panel1.add(textField1);
panel1.add(textField2);
panel1.add(textField3);
panel1.add(button1);
panel1.add(button2);
panel1.add(button3);
panel1.add(button4);

this.add(panel1);
}

private class ListenForButton implements ActionListener {


@Override
public void actionPerformed(ActionEvent e) {
double number1 = 0;
double number2 = 0;

try {
number1 = Double.parseDouble(textField1.getText());
number2 = Double.parseDouble(textField2.getText());
} catch (Exception error) {
error.printStackTrace();
}

if (e.getSource() == button1) {
textField3.setText(number1 + number2 + "");
} else if (e.getSource() == button2) {
textField3.setText(number1 - number2 + "");
} else if (e.getSource() == button3) {
textField3.setText(number1 * number2 + "");
} else if (e.getSource() == button4) {
textField3.setText(number1 / number2 + "");
}
}
}
}

You might also like