[go: up one dir, main page]

0% found this document useful (0 votes)
43 views40 pages

Final JAVA PR Ans

Uploaded by

RJ Sahil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
43 views40 pages

Final JAVA PR Ans

Uploaded by

RJ Sahil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

Practical Examples

Write a java program to demonstrate the use of exception handling. Handled divide
by zero error.
ANS-

public class ExceptionHandlingDemo {


public static void main(String[] args) {
int numerator = 10;
int denominator = 0;
int result;

try {
result = divide(numerator, denominator);
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}

public static int divide(int numerator, int denominator) {


return numerator / denominator;
}
}
Write a java program to increment the thread up 1 to 10 by extending Thread class.
ANS -

public class IncrementThread extends Thread {


public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread: " + Thread.currentThread().getId() + ",
Number: " + i);
}
}

public static void main(String[] args) {


for (int i = 1; i <= 10; i++) {
IncrementThread thread = new IncrementThread();
thread.start();
}
}
}
Write a java program to implement array index out of bound exception.
ANS -

public class ArrayIndexOutOfBoundsDemo {


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};

try {
// Accessing index 5 which is out of bounds
int value = numbers[5];
System.out.println("Value: " + value);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
Write a java program to implement the concept of file handling, copy the content
from one file to another file.
ANS -

import java.io.*;

public class FileCopy {


public static void main(String[] args) {
String sourceFilePath = "path/to/source/file.txt";
String destinationFilePath = "path/to/destination/file.txt";

try (BufferedReader reader = new BufferedReader(new


FileReader(sourceFilePath));
BufferedWriter writer = new BufferedWriter(new
FileWriter(destinationFilePath))) {

String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}

System.out.println("File copied successfully!");

} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}

Write a Java program to input name & salary of employee & throw user defined
exception if entered salary is negative.
ANS -

import java.util.Scanner;

class NegativeSalaryException extends Exception {


public NegativeSalaryException(String message) {
super(message);
}
}

class Employee {
private String name;
private double salary;

public Employee(String name, double salary) throws NegativeSalaryException {


this.name = name;
if (salary < 0) {
throw new NegativeSalaryException("Salary cannot be negative.");
}
this.salary = salary;
}

public String getName() {


return name;
}

public double getSalary() {


return salary;
}
}

public class SalaryInput {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

try {
System.out.print("Enter employee name: ");
String name = scanner.nextLine();

System.out.print("Enter employee salary: ");


double salary = Double.parseDouble(scanner.nextLine());
Employee employee = new Employee(name, salary);
System.out.println("\nEmployee details:");
System.out.println("Name: " + employee.getName());
System.out.println("Salary: " + employee.getSalary());
} catch (NumberFormatException e) {
System.out.println("Invalid salary format. Please enter a numeric value.");
} catch (NegativeSalaryException e) {
System.out.println(e.getMessage());
}
}
}
Write a code segment to create connection to an access database through a java
application and
display list of tables in the database. Assume suitable data.
ANS -

import java.sql.*;
public class GFG {

// Step1: Main driver method


public static void main(String[] args)
{
try {
PreparedStatement p = null;
ResultSet rs = null;

Class.forName("com.mysql.cj.jdbc.Driver");

Connection con = DriverManager.getConnection(


"jdbc:mysql://localhost:3306/demodatabase",
"root", "password");

String sql = "select * from student";


p = con.prepareStatement(sql);
rs = p.executeQuery();
System.out.println("id\t\tname\t\temail");
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String email = rs.getString("email");
System.out.println(id + "\t\t" + name + "\t\t" + email);
}
}
catch (SQLException e) {
System.out.println(e);
}
}
}
Write a java program to send the message to the server “Hello Server” using
Socket Program.
ANS -

//Server.java
import java.io.*;
import java.net.*;
public class Server {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
//Client.java
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
Write a Java Program to define a class, describe its constructor, and overload the
constructors and instantiate its object. (Student- Sname, Roll No, Marks1, Marks2)
ANS -

public class Student {


private String sName;
private int rollNo;
private int marks1;
private int marks2;

public Student(String sName, int rollNo, int marks1, int marks2) {


this.sName = sName;
this.rollNo = rollNo;
this.marks1 = marks1;
this.marks2 = marks2;
}

public Student(String sName, int rollNo) {


this.sName = sName;
this.rollNo = rollNo;
this.marks1 = 0;
this.marks2 = 0;
}

public String getsName() {


return sName;
}

public int getRollNo() {


return rollNo;
}

public int getMarks1() {


return marks1;
}

public int getMarks2() {


return marks2;
}

public void displayDetails() {


System.out.println("Name: " + sName);
System.out.println("Roll No: " + rollNo);
System.out.println("Marks 1: " + marks1);
System.out.println("Marks 2: " + marks2);
}

public static void main(String[] args) {


// Creating object using constructor with all parameters
Student student1 = new Student("John Doe", 123, 90, 85);
student1.displayDetails();
System.out.println();

// Creating object using constructor with name and roll number only
Student student2 = new Student("Jane Smith", 456);
student2.displayDetails();
}
}
Write a java program to calculate the area of rectangle, tringle and circle by
implementing interface.
ANS -

interface Shape {
double calculateArea();
}

class Rectangle implements Shape {


private double length;
private double width;

public Rectangle(double length, double width) {


this.length = length;
this.width = width;
}

@Override
public double calculateArea() {
return length * width;
}
}

class Triangle implements Shape {


private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}

@Override
public double calculateArea() {
return 0.5 * base * height;
}
}

class Circle implements Shape {


private double radius;

public Circle(double radius) {


this.radius = radius;
}

@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
public class AreaCalculation {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5, 10);
double rectangleArea = rectangle.calculateArea();
System.out.println("Rectangle Area: " + rectangleArea);

Triangle triangle = new Triangle(4, 6);


double triangleArea = triangle.calculateArea();
System.out.println("Triangle Area: " + triangleArea);

Circle circle = new Circle(3);


double circleArea = circle.calculateArea();
System.out.println("Circle Area: " + circleArea);
}
}
Write a program using Applet For configuring Applets by passing parameters.
ANS -

<html>
<body>
<applet code="ParameterApplet.class" width="200" height="100">
<param name="message" value="Welcome to my Applet!">
</applet>
</body>
</html>

//ParameterApplet.java
import java.applet.Applet;
import java.awt.*;

public class ParameterApplet extends Applet {


private String message;

@Override
public void init() {
message = getParameter("message");
if (message == null) {
message = "Hello, Applet!";
}
}

@Override
public void paint(Graphics g) {
g.drawString(message, 20, 20);
}
}
Write a java program to design a Button and TextBox using awt .
ANS -

import java.awt.*;
import java.awt.event.*;

public class ButtonAndTextBoxExample {


public static void main(String[] args) {
// Create a Frame
Frame frame = new Frame("Button and TextBox Example");

// Create a Button
Button button = new Button("Click Me");

// Create a TextBox
TextField textField = new TextField();

// Set the layout manager for the frame


frame.setLayout(new FlowLayout());

// Add the button and text field to the frame


frame.add(button);
frame.add(textField);

// Create an event listener for the button


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String text = textField.getText();
System.out.println("Button clicked! Text entered: " + text);
}
});

// Set the size of the frame and make it visible


frame.setSize(300, 200);
frame.setVisible(true);
}
}
Write a JSP program shows the Fibonacci series up to a particular term, while
input is taken from HTML form.
ANS -

//Fibonacci.html
<!DOCTYPE html>
<html>
<head>
<title>Fibonacci Series</title>
</head>
<body>
<h2>Fibonacci Series</h2>
<form action="fibonacci.jsp" method="post">
Enter the term:
<input type="number" name="term" required>
<input type="submit" value="Generate">
</form>
</body>
</html>
//Fibonacci.jsp
<!DOCTYPE html>
<html>
<head>
<title>Fibonacci Series</title>
</head>
<body>
<h2>Fibonacci Series</h2>
<%-- Retrieve the term value from the request --%>
<% int term = Integer.parseInt(request.getParameter("term")); %>

<%-- Calculate the Fibonacci series --%>


<% int firstTerm = 0;
int secondTerm = 1;

// Display the first two terms of the series


out.println(firstTerm + "<br>");
out.println(secondTerm + "<br>");

// Generate and display the remaining terms


for (int i = 3; i <= term; i++) {
int nextTerm = firstTerm + secondTerm;
out.println(nextTerm + "<br>");

// Update the firstTerm and secondTerm


firstTerm = secondTerm;
secondTerm = nextTerm;
}
%>
</body>
</html>
Write an applet for each of following graphics methods.
drawoval() , drawrect() , drawline() , filloval()
ANS -

import java.applet.Applet;
import java.awt.*;

public class GraphicsMethodsApplet extends Applet {


@Override
public void paint(Graphics g) {
// Draw an oval
g.drawOval(50, 50, 100, 100);

// Draw a rectangle
g.drawRect(200, 50, 100, 50);

// Draw a line
g.drawLine(50, 200, 250, 200);

// Fill an oval
g.fillOval(200, 150, 100, 100);
}
}

Write a JSP program for calculating factorial of number.


ANS -

<!DOCTYPE html>
<html>
<head>
<title>Factorial Calculator</title>
</head>
<body>
<h2>Factorial Calculator</h2>
<form action="factorial.jsp" method="post">
Enter a number:
<input type="number" name="number" required>
<input type="submit" value="Calculate">
</form>

<%-- Retrieve the number from the request --%>


<% int number = Integer.parseInt(request.getParameter("number"));

// Calculate the factorial


int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i;
}
%>
<%-- Display the result --%>
<h3>Factorial of <%= number %> is: <%= factorial %></h3>
</body>
</html>
Write a Java Program to demonstrate Keyboard events using Applet & awt.
ANS -

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class KeyboardEventsApplet extends Applet implements KeyListener {


private String keyPressedMessage = "Key Pressed: ";
private String keyReleasedMessage = "Key Released: ";
private String keyTypedMessage = "Key Typed: ";

@Override
public void init() {
// Register the applet to receive keyboard events
addKeyListener(this);

// Set the focus to the applet, so it can receive keyboard events


requestFocus();
}

@Override
public void keyTyped(KeyEvent e) {
char keyChar = e.getKeyChar();
System.out.println(keyTypedMessage + keyChar);
}

@Override
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println(keyPressedMessage + KeyEvent.getKeyText(keyCode));
}

@Override
public void keyReleased(KeyEvent e) {
int keyCode = e.getKeyCode();
System.out.println(keyReleasedMessage + KeyEvent.getKeyText(keyCode));
}
}
Write a Java Program to implement inheritance and demonstrate use of method
overriding.
ANS -

class Shape {
protected String color;

public Shape(String color) {


this.color = color;
}

public void draw() {


System.out.println("Drawing a shape");
}
}

class Circle extends Shape {


private double radius;

public Circle(String color, double radius) {


super(color);
this.radius = radius;
}

@Override
public void draw() {
System.out.println("Drawing a circle with radius " + radius + " and color " +
color);
}
}

class Rectangle extends Shape {


private double length;
private double width;

public Rectangle(String color, double length, double width) {


super(color);
this.length = length;
this.width = width;
}

@Override
public void draw() {
System.out.println("Drawing a rectangle with length " + length + ", width " +
width + " and color " + color);
}
}

public class InheritanceExample {


public static void main(String[] args) {
Circle circle = new Circle("Red", 5.0);
circle.draw();
Rectangle rectangle = new Rectangle("Blue", 4.0, 6.0);
rectangle.draw();
}
}
Write a program using Applet to display a message in the Applet.
ANS -

import java.applet.Applet;
import java.awt.*;
/* <applet code="MessageApplet.class" width=500 height=500> </applet> */

public class MessageApplet extends Applet {


private String message = "Hello, Applet!";

@Override
public void paint(Graphics g) {
g.drawString(message, 20, 20);
}
}
Create an abstract class shape. Derive class sphere from it. Calculate area and
volume of sphere (use method overriding)

abstract class Shape{


double radius,ht;
Shape(double a, double b){
radius = a;
ht= b;
}
abstract double area();
abstract double volume();
}
class Sphere extends Shape{
Sphere(double a){
super(a,0);
}
double area(){
System.out.print("\nArea of Sphere:");
return (4*3.14*radius*radius);
}
double volume(){
System.out.print("\nVolume of Sphere:");
return (4*3.14*radius*radius*radius)/3;
}
}
class AbstractDemo{
public static void main(String args[]){
Shape s;
s = new Sphere(5);
System.out.print(s.area());
System.out.print(s.volume());
System.out.println();
}
}
Write a client-server program which displays the server machine”s date and time
on the client machine.

client.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Client{
public static void main(String args[]) throws Exception{
Socket s = new Socket("localhost",4444);
BufferedReader br = new
BufferedReader(newInputStreamReader(s.getInputStream()));
System.out.println("From Server:"+br.readLine());
}
}

server.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Server{
public static void main(String args[]) throws Exception{
ServerSocket ss = new ServerSocket(4444);
while(true){
Socket s = ss.accept();
PrintStream ps = new PrintStream(s.getOutputStream());
ps.println(new Date());
s.close();
}
}
}
Define class MyDate with members day, month, year. Define default and
parameterized constructors. Accept values from the command line and create a
date object. Throw user defined exceptions – “InvalidDayException” or
“InvalidMonthException” if the day and month are invalid. If the date is valid,
display message “Valid date”.
class InvalidDateException extends Exception{
public String toString(){
return "Invalid Date given";
}
}

class MyDate{
public static void main(String[]args){
try{
if(args.length<3)
throw new NullPointerException();
else{
int dd=Integer.parseInt(args[0]);
int mm=Integer.parseInt(args[1]);
int yy=Integer.parseInt(args[2]);
boolean leap=((yy%400==0)||(yy%4==0 && yy%100!=0));
if(mm < 1||mm >12)
throw new InvalidDateException();
switch(mm){
case 1:
case 2:
if(!leap && dd>28)
throw new InvalidDateException();
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
if(dd < 1||dd>30)
throw new InvalidDateException();
case 11:
case 12:
if(dd < 1||dd >31)
throw new InvalidDateException();
}
System.out.println("Valid input");
}
}catch(Exception e){
System.out.println(e);
}
}
}

Output: -
java MyDate
java.lang.NullPointerException
java MyDate 23 5 2000
Valid input
java MyDate 23 15 2000
Invalid Month given
java MyDate 30 2 2000
Invalid Date given

You might also like