[Go to site: main page, start]

0% found this document useful (0 votes)
348 views43 pages

Java Programming Practical Assignment

This document contains 13 programming questions and their solutions in Java. The questions cover basic Java concepts like writing a simple "Hello World" program, using constructors, calculating simple interest, finding the average and sum of user-input numbers, using the Calendar class, working with packages and arrays, object-oriented concepts like inheritance and polymorphism, working with databases using JDBC including executing queries and deleting records, and more. Each question is followed by the output.

Uploaded by

Abhishek Shaha
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)
348 views43 pages

Java Programming Practical Assignment

This document contains 13 programming questions and their solutions in Java. The questions cover basic Java concepts like writing a simple "Hello World" program, using constructors, calculating simple interest, finding the average and sum of user-input numbers, using the Calendar class, working with packages and arrays, object-oriented concepts like inheritance and polymorphism, working with databases using JDBC including executing queries and deleting records, and more. Each question is followed by the output.

Uploaded by

Abhishek Shaha
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
  • Java Programming Assignment 1
  • Java Programming Assignment 2
  • Java Programming Assignment 3
  • Java Programming Assignment 4
  • Java Programming Assignment 5
  • Java Programming Assignment 6
  • Java Programming Assignment 7
  • Java Programming Assignment 8
  • Java Programming Assignment 9
  • Java Programming Assignment 10
  • Java Programming Assignment 11
  • Java Programming Assignment 12
  • Java Programming Assignment 13
  • Java Programming Assignment 14
  • Java Programming Assignment 15
  • Java Programming Assignment 16
  • Java Programming Assignment 17
  • Java Programming Assignment 18
  • Java Programming Assignment 19
  • Java Programming Assignment 20

Practical Assignment

Name :- Sourabh Ashok Lamdade

Subject :- Java Programming PRN :- 2020080496

Q.1 Write a program that displays Welcome Java message

class Welcome

public static void main (String[]args)

[Link]("Welcome to Java");

Output:
Q.2 Write a program in Java that demonstrate default constructor & parameterised
constructor.

Default Constructor

class Main

int a;

boolean b;

public static void main (String [] args)

Main obj= new Main();

[Link]("Default Value:");

[Link]("a=" + obj.a);

[Link]("b=" + obj.b);

Output:
Parameterised Constructor

class Main

String languages;

Main(String lang)

languages = lang;

[Link](languages + " Programming Language");

public static void main(String[] args)

Main obj1 = new Main("Java");

Main obj2 = new Main("Python");

Main obj3 = new Main("C");

Output:
Q.3 Write a program to Calculate a simple interest.

import [Link];

class Main

public static void main(String[] args)

Scanner input = new Scanner([Link]);

[Link]("Enter the principal: ");

double principal = [Link]();

[Link]("Enter the rate: ");

double rate = [Link]();

[Link]("Enter the time: ");

double time = [Link]();

double interest = (principal * time * rate) / 100;

[Link]("Principal: " + principal);

[Link]("Interest Rate: " + rate);

[Link]("Time Duration: " + time);

[Link]("Simple Interest: " + interest);

[Link]();

Output:
Q.4 Write a program to find the average and sum of the ‘N’ numbers using user input.

import [Link];

public class sum

public static void main (String [] args)

Scanner sc= new Scanner([Link]);

[Link]("Enter the array size:");

int len= [Link]();

int arr[]= new int[len];

double sum= 0;

double avg= 0;

[Link]("Enter the 5 array element");

for(int i=0;i<len;i++)

arr[i]= [Link]();

for(int i=0;i<len;i++)

sum += arr[i];

avg= sum/len;

[Link]("sum of"+len+"number in" + sum);

[Link]("Average is" + avg);

}
Output:
Q.5 Write a program to create simple class to findout area and perimeter of rectangle of
box using super keyword.

import [Link].*;

class Rectangle

double length;

double width;

void Area()

double area;

area = [Link] * [Link];

[Link]("Area of rectangle is : " + area);

void Perimeter()

double perimeter;

perimeter = 2 * ([Link] + [Link]);

[Link]("Perimeter of rectangle is : " + perimeter);

class UseRectangle {

public static void main(String args[])

Rectangle rect = new Rectangle();


[Link] = 15.854;

[Link] = 22.65;

[Link]("Length = " + [Link]);

[Link]("Width = " + [Link]);

[Link]();

[Link]();

Output:
Q.6 Write a program to design class shape using abstract method and classes.

abstract class Shape

abstract void draw();

class Rectangle extends Shape

void draw()

[Link]("drawing rectangle");

class Circle1 extends Shape

void draw()

[Link]("drawing circle");

class Abstraction1

public static void main(String args[])

Shape s=new Circle1();

[Link]();

} }
Output:
Q.7 Write a program using calendar that displays current year, month, date.

import [Link];

import [Link];

import [Link];

class Calendar

public static void

getDayMonthYear(String date)

LocalDate currentDate= [Link](date);

int day = [Link]();

Month month = [Link]();

int year = [Link]();

[Link]("Day: " + day);

[Link]("Month: " + month);

[Link]("Year: " + year);

public static void main(String args[])

String date = "2021-08-09";

getDayMonthYear(date);

}}

Output:
Q.8 Write a program using calendar current year, day of week, week of month, hours,
minute, seconds, milisec.
Q.9 Write a program to create package that displays Welcome to Package.

import [Link].*;

class simple

public static void main(String[] args)

Scanner myObj = new Scanner([Link]);

String Message;

[Link]("Enter You Message");

Message = [Link]();

[Link]("Your Message is : " + Message);

Output:
Q.10 Write a program to create package array list using 10 elements.

import [Link];

class Package1

public static void main (String [] args)

ArrayList<Integer> list= new ArrayList<>();

[Link](1);

[Link](2);

[Link](3);

[Link](4);

[Link](5);

[Link](6);

[Link](7);

[Link](8);

[Link](9);

[Link](10);

[Link](list);

Output:
Q.11 Implement program to calculate area of a square take method calc( ) in super
class as well in sub class(using method overriding).

Java Code :
import [Link];
class shape
{
float result ;
public void calc (float a)
{
result = a * a ;

}
}
class rectangle extends shape
{
public void calc(float a )
{
[Link](a);
[Link]("Area of Square:" + [Link]);
}
}
public class TestRectangle
{
public static void main(String[] args)
{
float a;
Scanner sc = new Scanner([Link]);
[Link]("Enter the side of Square:");
a = [Link]();
rectangle s = new rectangle();
[Link](a);
}
}
Output :
Q.12 Write a program to execute select query using JDBC(Create one table Employee)

Java Code :
import [Link].*;

class JdbcSelect

public static void main(String args[])

try

[Link]("[Link]");

[Link]("Drivers are loaded");

Connection con = [Link]("jdbc:odbc:Demo");

[Link]("Connection is Created");

Statement st = [Link]();

[Link]("CREATE TABLE Employee(EmpID int,FirstName


varchar(255),LastName varchar(255),Department varchar(50),Salary
int);");

[Link]("Table is created");

[Link]("INSERT INTO Employee


VALUES(1,'Allen','Max','Manager',50000);");

[Link]("INSERT INTO Employee


VALUES(2,'Matt','demon','Developer',20000);");

[Link]("INSERT INTO Employee


VALUES(3,'Alex','mac','Sounds',10000);");

[Link]("INSERT INTO Employee


VALUES(4,'Kale','poes','Visuals',52000);");

[Link]("INSERT INTO Employee


VALUES(5,'Lowis','Mills','Producer',54000);");

[Link]("Recored Inserted");

ResultSet rs = [Link]("SELECT * FROM Employee;");


while([Link]())

for(int i=1;i<6;i++)

[Link]([Link](i));

catch(Exception e)

[Link](e);

}
Output :
Q.13 Write a Program using jdbc which shows how to delete records from table.

Java code :

import [Link].*;

class JdbcDelete

public static void main(String args[])

try

[Link]("[Link]");

[Link]("Drivers are loaded");

Connection con = [Link]("jdbc:odbc:Demo");

[Link]("Connection is Created");

Statement st = [Link]();

[Link]("DELETE FROM Employee WHERE FirstName='Alex'");

[Link]("Record Deleted");

[Link]();

catch (Exception e)

[Link](e);

}
Output :
Q.14 Write a program implement servlet for displaying Hello.

Java code :
// [Link]
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>TO DO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Click here to go <a href="NewServlet">Click</a></h2>
</body>
</html>

//[Link]

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class NewServlet extends HttpServlet {

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
[Link]("text/html;charset=UTF-8");
try ( PrintWriter out = [Link]()) {
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet NewServlet</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("<h1>Hello....! Welcome to My first servlet </h1>");
[Link]("</body>");
[Link]("</html>");

}
}

Output :
Q.15 Write a program to implement Servlet to take values from client and display it.

Java code :

// [Link]

<!DOCTYPE html>

<!--

To change this license header, choose License Headers in Project Properties.

To change this template file, choose Tools | Templates

and open the template in the editor.

-->

<html>

<head>

<title>TO DO supply a title</title>

<meta charset="UTF-8">

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

</head>

<body>

<form name="loginForm" method="get" action="ClientServlet">

Name : <input type="text" name="name"/> <br/><br/>

Address : <input type="text" name="address"/> <br/><br/>

Mobile No. : <input type="text" name="number"/> <br/><br/>

E-mail : <input type="text" name="email"/> <br/><br/>

<input type="submit" value="Login" />

</form>

</body>

</html>
//[Link]

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet(urlPatterns = {"/ClientServlet"})

public class ClientServlet extends HttpServlet {

@Override

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html;charset=UTF-8");

/* TODO output your page here. You may use following sample code. */

String Name = [Link]("name");

String Address = [Link]("address");

String mobile = [Link]("number");

String email = [Link]("email");

[Link]("Name: " + Name);

[Link]("Address: " + Address);

[Link]("mobile: " + mobile);


[Link]("Email: " + email);

PrintWriter out = [Link]();

[Link]("<!DOCTYPE html>");

[Link]("<html>");

[Link]("<head>");

[Link]("<title></title>");

[Link]("</head>");

[Link]("<body>");

[Link]("<h2>Your name is:" + Name + "</h2>");

[Link]("<h2>Your Address is:" + Address + "</h2>");

[Link]("<h2>Your Mobile number is:" + mobile + "</h2>");

[Link]("<h2>Your E-mail ID is:" + email + "</h2>");

[Link]("</body>");

[Link]("</html>");

}
Output :

Sourabh Lamdade

Miraj

8698423695

salamdade@[Link]

SSourabh Lamdade

MirajMiraj

8698423695
salamdade@[Link]
Q.16 Write a program to implement Session Management using all four types.

Java code :

// [Link]

<!DOCTYPE html>

<html>

<head>

<meta charset="US-ASCII">

<title>Login Page</title>

</head>

<body>

<form action="LoginServlet" method="get">

Username: <input type="text" name="username">

<br><br>

Password: <input type="password" name="password">

<br><br>

<input type="submit" value="Login">

</form>

</body>

</html>

// [Link]

import [Link];

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet("/LoginServlet")

public class LoginServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

public LoginServlet() {

super();

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

[Link]("text/html;charset=UTF-8");

//[Link]().append("Served at:
").append([Link]());

try {

PrintWriter out=[Link]();

String username=[Link]("username");

String password=[Link]("password");

[Link]("<p> Welcome: "+username + "</p>");

[Link]("<p> Here is your password: "+password + "</p>");


HttpSession session=[Link]();

[Link]("username",username);

[Link]("password",password);

[Link]("<a href='NewServlet'>View </a>");

[Link]();

}catch (Exception e) {

// TODO: handle exception

[Link](e);

// [Link]

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

@WebServlet(urlPatterns = {"/NewServlet"})

public class NewServlet extends HttpServlet {

public NewServlet() {

super();

protected void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// TODO Auto-generated method stub

//[Link]().append("Served at:
").append([Link]());

try{

[Link]("text/html");

PrintWriter p=[Link]();

HttpSession session = [Link](false);

String myName=(String)[Link]("username");

String mypass=(String)[Link]("password");

[Link]("<p>Youre username is : "+myName + "</p>");

[Link]("<p> Youre Password is : "+mypass + "</p>");

[Link]();

}catch (Exception e) {

// TODO: handle exception

[Link](e);

}
Output :

sourabh

Sourabh123

Sourabh

Sourabh123

sourabh

Sourabh123
Q.17 Write a Program using jdbc which shows how to update records in table.

Java Code :

import [Link].*;

class JdbcUpdate

public static void main(String args[])

try

[Link]("[Link]");

[Link]("Drivers are loaded");

Connection con = [Link]("jdbc:odbc:Demo");

[Link]("Connection is Created");

Statement st = [Link]();

[Link]("UPDATE Employee SET


FirstName='Johnny',Department='Janitor',Salary=9000 WHERE
LastName='poes'");

[Link]("Record Updated");

[Link]();

catch(Exception e)

[Link](e);

}
}

Output:
Q.18 WAP to implement RMI(Show only msg welcome to rmi)

Java Code :

// [Link]

import [Link];

import [Link];

public interface Hello extends Remote

String sayHello() throws RemoteException;

// [Link]

import [Link];

import [Link];

public class HelloImp extends UnicastRemoteObject implements Hello

protected HelloImp() throws RemoteException

super();

public String sayHello()

return "Hello world...!";

// [Link]

import [Link];
public class HelloClient

public static void main(String[] args)

try

Hello h = (Hello) [Link]("//[Link]:1099/calculatorservice");

[Link]([Link]());

catch(Exception e)

[Link]("Exception occer:");

// [Link]

import [Link];

public class HelloServer

HelloServer()

try

Hello h = new HelloImp();

[Link]("rmi://localhost:1099/calculatorservice",h);

}
catch(Exception e)

[Link]("Exception occurs:");

public static void main(String[] args)

new HelloServer();

Output :
Q.19 JSP Program to display given number in words.

Java Code :

Output :
Q.20 Write a program using RMI which shows the different operations like addition,
subtraction, division, multiplication. (For implementing this use scanner class)

Java Code :

// [Link]

import [Link];

import [Link];

public interface Operation extends Remote

public long addition(long a , long b) throws RemoteException;

public long substraction(long a , long b) throws RemoteException;

public long multiplication(long a , long b) throws RemoteException;

public long division(long a , long b) throws RemoteException;

import [Link];

import [Link];

// [Link]

public class OperationImp extends UnicastRemoteObject implements Operation

protected OperationImp() throws RemoteException

super();

public long addition (long a,long b) throws RemoteException

return a+b;
}

public long substraction(long a,long b) throws RemoteException

return a-b;

public long multiplication(long a,long b) throws RemoteException

return a*b;

public long division(long a,long b) throws RemoteException

return a/b;

// [Link]

import [Link];

import [Link];

public class OperationClient

public static void main(String[] args)

try

{
Operation c = (Operation)
[Link]("//[Link]:1099/calculatorservice");

Scanner sc = new Scanner([Link]);

[Link]("Enter the first number:");

long a = [Link]();

[Link]("Enter the second number:");

long b = [Link]();

[Link]();

[Link]("Addition:" +[Link]( a , b));

[Link]("Substraction:" +[Link](a , b));

[Link]("multiplication:" +[Link]( a , b));

[Link]("division:" +[Link]( a , b));

catch(Exception e)

[Link]("Exception occer:");

// [Link]

import [Link];

public class OperationServer

OperationServer()

try

{
Operation c = (Operation) new OperationImp();

[Link]("rmi://[Link]:1099/calculatorservice",c);

catch(Exception e)

[Link]("Exception occurs:");

public static void main(String[] args)

new OperationServer();

Output :

Common questions

Powered by AI

Java programs utilize JDBC (Java Database Connectivity) to interact with databases for tasks such as creating tables, inserting, updating, and deleting records. In managing employee data, JDBC provides a rich set of features. For example, a Java program can load a JDBC driver (e.g., `Class.forName` method), establish a connection to the database, and create SQL statements to execute queries. The program then utilizes `Statement` objects to execute SQL commands, such as creating an `Employee` table, inserting new employee records, updating existing ones, and deleting records based on specific criteria. Through JDBC, Java offers a flexible and consistent interface to various databases and streamlines typical database operations .

Session management in Java Servlet applications can be effectively implemented through various approaches to maintain user state across multiple requests. The document outlines using HttpSession, cookies, and other types, including URL rewriting and hidden form fields, for session management. In the servlet example, HttpSession is used where a session object is created and attributes like username and password are set. This session persists across requests, enabling the application to remember user-specific data and provide a seamless user experience. Each method has specific scenarios of best use, such as cookies when small amounts of data need to persist or session objects for more secure, large data handling .

RMI (Remote Method Invocation) in Java allows applications to call methods located in different Java Virtual Machines (JVMs), enabling a form of remote communication between objects. It extends the object-oriented model to support distributed computing. In the context given, Java RMI is used to define and implement interfaces (like `Operation`) that specify remote methods, such as `addition`, `substraction`, `multiplication`, and `division`. RMI's architecture involves stubs and skeletons to handle method invocation, parameter passing, and returning values across JVMs. The invocation is seamless and transparent to the client, simulating a local call while leveraging the distributed computing power .

The "super" keyword in Java is used to call the method of the parent class in a subclass. By using "super", a subclass can access methods and fields of the parent class that it is extending. In the context of the given document, the "super" keyword is used to demonstrate method overriding in calculating the area of a square. The superclass has a method `calc()` which computes the result, and the subclass calls this method using `super.calc(a)` to utilize the parent class's implementation before printing the computed area, illustrating a clear understanding of inheritance and method overriding .

Packages in Java play a crucial role in organizing and structuring code. They act as containers that group related classes and interfaces, which helps avoid naming conflicts and controls access levels within the program. According to the document, creating a package allows for the streamlined organization of classes such as the example of a `Package1` class which utilizes an `ArrayList` to display elements. By grouping classes into packages, developers can manage large codebases more efficiently, facilitate code reuse, and also provide a namespace for manageable scaling in large projects .

Method overriding in Java significantly enhances code reusability and polymorphism by allowing a subclass to provide a specific implementation of a method already defined in its superclass. This enables subclasses to inherit the functionality of the parent class while customizing behavior to specific needs. It increases the flexibility and maintainability of the code because changes in the parent class methods can automatically apply to subclasses without modifying them. The document's example of `calc()` method in geometric calculations illustrates how method overriding allows each shape class to customize the calculation while reusing the logic provided by the parent class .

Using Java abstractions to implement shapes may pose challenges such as complexity in design where understanding and navigating abstract class hierarchies can be difficult, particularly for new developers or maintaining legacy systems. Another challenge is ensuring consistent behavior across different implementations. These can be mitigated through thorough documentation, defining clear and concise APIs, and implementing comprehensive test suites that ensure all subclasses conform to expected behavior. Additionally, using design patterns like Template Method can provide a framework around which the abstract pattern can be constructed, promoting reusability and consistency .

Servlets in Java facilitate web-based interactions by allowing Java applications to respond to requests made by clients, typically through a web browser. They run on a server, handle GET and POST requests, and can generate dynamic web content. For example, as described in the document, a servlet like `NewServlet` is implemented to process requests, such as displaying a dynamic "Hello" message to users interacting with the servlet from a web page. This involves using classes like `HttpServletRequest` and `HttpServletResponse` to read client data and send responses, respectively, effectively handling the request-response cycle in a web environment .

Abstract classes and methods in Java provide a powerful mechanism for designing flexible and scalable software components by providing a template for other classes. The use of an abstract class, like `Shape`, with an abstract method `draw()`, allows for the creation of subclasses like `Rectangle` and `Circle1` that must implement their own versions of `draw()`. This ensures that each specific shape class has a consistent interface for initialization and behavior definition while allowing each subclass to provide a specific implementation. This leads to a modular design where extending with new shape types only requires the implementation of the abstract methods without altering existing code .

Using both default and parameterized constructors in Java provides flexibility and clarity in object instantiation. The default constructor initializes objects with default values, ensuring that object fields have initial values even if none are provided explicitly during instantiation. On the other hand, parameterized constructors allow the setting of initial values at the time of object creation, thus enabling more controlled and intentional initialization. This is beneficial for initializing fields with different values directly, thereby reducing the need for setter methods and making the code more concise and readable .

Practical Assignment
Name :- Sourabh Ashok Lamdade                             
Subject :- Java Programming
Q.2 Write a program in Java that demonstrate default constructor & parameterised 
constructor.
Default Constructor
class Main
Parameterised Constructor
class Main 
{
 String languages;
  Main(String lang)
 {
    languages = lang;
    System.out.printl
Q.3 Write a program to Calculate a simple interest.
import java.util.Scanner;
class Main 
{
  public static void main(String[
Q.4 Write a program to find the average and sum of the ‘N’ numbers using user input.
import java.util.Scanner;
public class s
Output:
Q.5 Write a program to create simple class to findout area and perimeter of rectangle of 
box using super keyword.
import jav
rect.length = 15.854;
rect.width = 22.65;
System.out.println("Length = " + rect.length);
System.out.println("Width = " + rect
Q.6 Write a program to design class shape using abstract method and classes.
abstract class Shape
{  
    abstract void draw(
Output:

You might also like