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

JAVAASSINEW2

Java Assignment for b.sc computer science hons

Uploaded by

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

JAVAASSINEW2

Java Assignment for b.sc computer science hons

Uploaded by

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

1.

Write a Java code to find the sum of any number of integers entered as command line arguments.

public class SumOfNumbers1


{
public static void main(String args[])
{
int n1 = 225, n2 = 115, sum;
sum = n1 + n2;
System.out.println("The sum of numbers is: "+sum);
}
}

Output:

Backward Skip 10sPlay VideoForward Skip 10s


The sum of numbers is: 340
2.Write a Java code to calculate factorial of a number. Take input from keyboard using following classes

i)Data Input Stream

ii)Buffered Reader

iii)Scannner

import java.util.Scanner;

class fact

public static void main(String[]args){

int n,fact=1;

System.out.print("enter any number");

Scanner r=new Scanner(System.in);

n=r.nextInt();

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

fact=fact*i;

System.out.print("factorial "+fact);

ii)Source code:-

import java.io.*;
class Factorial1

public static void main(String args[])

BufferedReader bf = new BufferedReader(new

InputStreamReader(System.in));

int a = 0, f = 1;

try

System.out.println("Enter the number to find factorial:");

a = Integer.parseInt(bf.readLine());

catch (Exception e)

e.printStackTrace();

if (a == 0 || a == 1)

System.out.println("factorial of this number is 1");

else

for (int i = a; i > 0; i--)

f = f * i;

System.out.println("factorial of this number is:" + f);

Output:-

Enter the number to find factorial:

factorial of this number is:40320

iii)Source code:-

import java.util.Scanner;

public class Factorial2


{

public static void main(String[] args)

int num, i, fact = 1;

Scanner s = new Scanner(System.in);

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

num = s.nextInt();

for (i = num; i >= 1; i--)

fact = fact * i;

System.out.println("\nFactorial Result = " + fact);

Output:-

Enter a Number: 6

Factorial Result = 720

3. Write a Java to print all prime numbers within a given range.

INPUT

import java.util.Scanner;

class A

public static void main(String[]args) {

int n1, n2,i,j;

System.out.print("enter two numbers");

Scanner r = new Scanner(System.in);

n1 = r.nextInt();

n2 = r.nextInt();

for (i = n1; i <= n2; i++)

for(j=2;j<=i;j++)

if(i%j==0)
break;

if(i==j)

System.out.print(j+" ");

OUTPUT

enter two numbers

50

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47

4 Write a Java code to take ten numbers as input and sort them is ascending order.

INPUT

Write a Java code to take ten numbers as input


and sort them is asscendig order.
Source Code:-
import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
int count, temp;

//User inputs the array size


Scanner scan = new Scanner(System.in);
System.out.print("Enter number of elements you want in the array: ");
count = scan.nextInt();

int num[] = new int[count];


System.out.println("Enter array elements:");
for (int i = 0; i < count; i++)
{

num[i] = scan.nextInt();
}
scan.close();
for (int i = 0; i < count; i++)
{
for (int j = i + 1; j < count; j++)
{
if (num[i] > num[j])
{
temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
System.out.print("Array Elements in Ascending Order: ");
for (int i = 0; i < count - 1; i++)
{
System.out.print(num[i] + ", ");
}
System.out.print(num[count - 1]);
}
}
Output:-
Enter number of elements you want in the array: 10
Enter array elements:
3
5
8
9
1
12

45
34
21
67
Array Elements in Ascending Order: 1, 3, 5, 8, 9, 12, 21, 34, 45, 67
5.Write a Java code to take Account no. Name and
Balance as input of ten customers and display the name and
account no. of those customers whose balance is less than one
thousand.
Source code:-
import java.util.Scanner;
public class CustomerAccounts
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int numberOfCustomers = 10;
String[] accountNumbers = new String[numberOfCustomers];
String[] names = new String[numberOfCustomers];
double[] balances = new double[numberOfCustomers];
for (int i = 0; i < numberOfCustomers; i++)
{
System.out.println("Enter details for Customer " + (i + 1) + ":");
System.out.print("Account Number: ");
accountNumbers[i] = scanner.nextLine();
System.out.print("Name: ");
names[i] = scanner.nextLine();
System.out.print("Balance: ");
balances[i] = scanner.nextDouble();
scanner.nextLine();
System.out.println();
}
System.out.println("Customers with a balance less than 1000:");

boolean found = false;


for (int i = 0; i < numberOfCustomers; i++)
{
if (balances[i] < 1000)
{
System.out.println("Name: " + names[i]);
System.out.println("Account Number: " +
accountNumbers[i]);
System.out.println();
found = true;
}
}
if (!found)
{
System.out.println("No customers have a balance less than
1000.");
}
}
}
Output:-
Enter details for Customer 1:
Account Number: 12289654
Name: A
Balance: 100
Enter details for Customer 2:
Account Number: 24875101
Name: B
Balance: 1857
Enter details for Customer 3:
Account Number: 43280317
Name: C
Balance: 20
Enter details for Customer 4:

Account Number: 12349874


Name: D
Balance: 8000
Enter details for Customer 5:
Account Number: 3216433
Name: E
Balance: 814
Enter details for Customer 6:
Account Number: 65120977
Name: F
Balance: 9014
Enter details for Customer 7:
Account Number: 789420144
Name: G
Balance: 301
Enter details for Customer 8:
Account Number: 523324278
Name: H
Balance: 8571
Enter details for Customer 9:
Account Number: 61327780
Name: I
Balance: 600
Enter details for Customer 10:
Account Number: 23892574898
Name: J
Balance: 50
Customers with a balance less than 1000:
Name: A
Account Number: 12289654
Name: C
Account Number: 43280317
Name: E

Account Number: 3216433


Name: G
Account Number: 789420144
Name: I
Account Number: 61327780
Name: J
Account Number: 23892574898
6. Create a class named Figure. Make Circle, square
and triangle as object of the class Figure and calculate their
surface area by concept of constructor overloading.
Source code:-
public class Figure
{
private double surfaceArea;
public Figure()
{
surfaceArea = 0.0;
}
public Figure(double radius)
{
calculateCircleArea(radius);
}
public Figure(double side1, double side2, double side3)
{
calculateTriangleArea(side1, side2, side3);
}
public Figure(float side)
{
calculateSquareArea(side);
}
private void calculateCircleArea(double radius)
{
surfaceArea = Math.PI * radius * radius;

}
private void calculateTriangleArea(double side1, double side2, double side3)
{
double s = (side1 + side2 + side3) / 2;
surfaceArea = Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
private void calculateSquareArea(double side)
{
surfaceArea = side * side;
}
public double getSurfaceArea()
{
return surfaceArea;
}
public static void main(String[] args)
{
Figure circle = new Figure(5.0); // Creating a circle object with radius
5.0
System.out.println("Circle Surface Area: " + circle.getSurfaceArea());
Figure triangle = new Figure(3.0, 4.0, 5.0); // Creating a triangle object
with sides 3.0, 4.0, and 5.0
System.out.println("Triangle Surface Area: " +
triangle.getSurfaceArea());
Figure square = new Figure(7.0); // Creating a square object with side
7.0
System.out.println("Square Surface Area: " + square.getSurfaceArea());
}
}
Output:-
Circle Surface Area: 78.53981633974483
Triangle Surface Area: 6.0
Square Surface Area: 153.93804002589985

7.Create a class named Figure. Make circle, square


and triangle as object of the Figure and calculate their surface
area by concept of method overloading.
Source code:-
class Figure
{
void area(float r)
{
System.out.println("The area of Circle is
"+Math.PI*Math.pow(r,2)+"sq units");
}
void area (double a)
{
System.out.println("The area of the Square is "+ Math.pow
(a,2)+"sq.units");
}
void area (double x, double y, double z)
{
double s =( x+y+z)/2;
System.out.println("The area of the Triangle is "+ Math.sqrt(s*(s-x)*(sy)+(s-z))+"sq.units");
}
}
class Area
{
public static void main (String args[])
{
Figure ob = new Figure ();
ob.area(5.2);
ob.area(6);
ob.area(2,3,4);
}
}

Output:-

The area of the Circle is 113.09733552923255 sq.units


The area of the Square is 27.04000000003 sq.units
The area of the Triangle is 4.1683330001332 sq.units
Question 8:-Create a class Parent with one variable and one
method. Create a class Child which inherits members from
parent. Use the members of parent from child class and from
third party environment.
Source code:-
class Parent
{
int pval;
public Parent (int x)
{
pval = x;
}
public void display()
{
System.out.println("This is the Parent class with value = " + pval);
}
}
class Child extends Parent
{
int cval;
public Child (int a, int b)
{
super(a);
cval = b;
}
public void display()
{
super.display();

System.out.println("This is the Child class with value = " + cval);


}
}
public class Inheritance
{
public static void main (String args[])
{
System.out.println("This statement is within main() method.");
Child obj = new Child(10, 17);
obj.display();
}
}
Output:-
This statement is within main() method.
This is the Parent class with value = 10
This is the Child class with value = 17
9.Write a java code to check whether a given string is palindrome or not?

INPUT

public static void main(String[] args) {

String str = "Radar", reverseStr = "";

int strLength = str.length();for (int i = (strLength - 1); i >=0; --i) {


reverseStr = reverseStr + str.charAt(i);

if (str.toLowerCase().equals(reverseStr.toLowerCase())) {

System.out.println(str + " is a Palindrome String.");

else {

System.out.println(str + " is not a Palindrome String.");

OUTPUT

Radar is a palindromes string

10. Write a java code to show that String class is immutable and StringBuffer class is mutable.

INPUT:

public class ProveStringImmutable {

public static void referenceCheck(Object x, Object y) {

if (x == y) {

System.out.println("Both pointing to the same reference");

} else {

System.out.println("Both are pointing to different reference");

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

String st1 = "Java"; String st2 = "Java";

referenceCheck(st1, st2);

st1 += "ava";

System.out.println("After Modification");

referenceCheck(st1, st2); }

Output:

Before Modification in st1

Both pointing to the same reference


After Modification

Both are pointing to different reference

11. Consider a class that represents an account in a

bank. Let the minimum balance for the account be Rs 1000.

Write a program in java that throws an exception when a

withdrawal results in the balance decreasing to value less than

Rs. 1000.

Source code:-

import java.util.Scanner;

class InsufficientBalanceException extends Exception

public String getMessage()

return "Withdrawal failed !(Minimum balance should be 1000 Rs) ";

class Account

private int accNo;

private double bal;

public void setAccount(int num,double rs)

accNo=num;

bal=rs;

public void deposit(double am)

bal+=am;

System.out.println("Successfully deposited amount "+am+" rs");

System.out.println("New balance : "+bal);

public void withdrawal(double am) throws

InsufficientBalanceException

{
double newBal=bal-am;

if(newBal<1000)

throw new InsufficientBalanceException();

bal=newBal;

System.out.println("Successfully withdrawal "+am+" rs");

System.out.println("New balance : "+bal);

public class Q11_InsufficientBalance

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

System.out.println("Enter the Account number and initial amount

:");

int n=sc.nextInt();

double b=sc.nextDouble();

Account acc=new Account();

acc.setAccount(n,b);

System.out.println("Enter the amount to deposit :");

double am=sc.nextDouble();

acc.deposit(am);

System.out.println("Enter the amount to withdrawal :");

double with=sc.nextDouble();

try

acc.withdrawal(with);

catch(InsufficientBalanceException e)

System.out.println(e.getMessage());

}
}

Output:-

Enter the Account number and initial amount :

2200336

1500

Enter the amount to deposit :

500

Successfully deposited amount 500.0 rs

New balance : 2000.0

Enter the amount to withdrawal :

1200

Withdrawal failed !(Minimum balance should be 1000 Rs)

12-Write a Java code to create a package named “testpackage”, create a class named “Add” under this package

which contains a method named ”display”. Import this package in another Java program.

Source code:-

package testpackage;

public class Add

public void display()

System.out.println("This Statement is within 'Add' class of package

'testpackage'.");

import testpackage.Add;

public class Importing

public static void main (String args[])

System.out.println("This statement is within main() method.");

Add obj = new Add();

System.out.println("Creating 'Add' Object.");


obj.display();

Output:-

This statement is within main() method.

Creating 'Add' Object.

This Statement is within 'Add' class of package 'testpackage'

13.Write a Java code to use the numbers of outer

class from inner class and vice versa.

INPUT

// Outer From Inner

class Outer

private static int x=0;

Public class Inner

void print()

System.out.println(x);

public static void main(String[] args)

Outer out = new Outer();

Outer.Inner in = out.new Inner();

Output:-

Source code:-

// Inner From Outer

import java.io.*;

public class OuterClass


{

private int outerVariable = 10;

public class InnerClass

private int innerVariable = 5;

public void accessInnerVariable()

InnerClass innerClass = new InnerClass();

System.out.println(innerClass.innerVariable);

public static void main (String[]args)

OuterClass o=new OuterClass();

o.accessInnerVariable();

Output:-

14.Write a Java code to create Interface. Implement this Interface in another Java Program.

Source code:-

public interface MyInterface

void display();

public class MyClass implements MyInterface

public void display()

System.out.println("Implementation of display() method");

}
public static void main(String[] args)

MyClass obj = new MyClass();

obj.display();

Output:-

Implementation of display() method

15.Write a java code to implement Multi-Threading concept.

INPUT

class A extends Thread

public void run()

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

System.out.print("sumit");

class B

public static void main(String []args){

A t=new A();

t.start();

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

System.out.print("mahato");

OUTPUT

mahatomahatomahatomahatomahatosumitsumitsumitsumitsumit
Question 16:-Write an Applet code to draw lines, rectangles, ovals and arcs.
Source code:-
import java.awt.*;

import java.applet.*;

public class AppletDrawing extends Applet {

public void paint(Graphics g)

{ g.drawLine(50,50,250,50);

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

g.drawOval(50,250,150,100);

g.drawArc(50,400,150,100,45,270);
}}

OUTPUT:
17.Write an Applet code to implement passing parameters in Applet using “PARAM” tag.

INPUT:

Import java.awt*;

Import java.applet.*;

public class HelloJavaParam extends Applet

String str;

str= getParameter(“string”);

if(str==null)

str=”java”;

public void paint(Graphics g)

g.drawstring(str,10,100)

The HTML file for HelloJavaParam applet

<HTML>

<! Parameterized HTML file>

<HEAD>

<TITLE> welcome to java applets</TITLE>

</HEAD>

<BODY>

<APPLET CODE=”HelloJavaParam.class

WIDHT=400

HEIGHT=200>

<PARAM NAME = “string”

VALUE=”Applet!”>

</APPLET>

</BODY>
</HTML>

OUTPUT

18. Write an Applet code to display image in a browse

INPUT

import java.awt.*;

import java.applet.*;

public class AppletImage extends Applet

private Image i;

public void init()

i=getImage(getDocumentBase(),"Screenshot_2023-07-15-10-07-46-

19_99c04817c0de5652397fc8b56c3b3817.jpg");

public void paint(Graphics g)

g.drawImage(i,100,100,500,400,this);

<!DOCTYPE html>
<html lang="en">

<head>

<meta charset="UTF-8">

<title>Applet Image</title>

</head>

Page 42 of 48

<body>

<applet code="AppletImage" height =500 width="200">

</applet>

</body>

</html>

OUTPUT

19.Write an Applet code to play audio file(wav file.


INPUT
import java.awt.*;

import java.applet.*;

import java.net.*;

public class AppletAudio extends Applet

{ private AudioClip audio;

public void init()

{ URL url=getClass().getResource("feluda-harmonica.wav");
audio=getAudioClip(url); }
public void start()
{ audio.play(); }
public void stop()
{ audio.stop(); } }

OUTPUT

Question 20:-Write an Applet code to calculate speed of a car.

Take input distance and the time using Text field

INPUT

import java.awt.*;

import java.applet.*;

import java.awt.event.*;

public class Speed extends Applet implements ActionListener

Button b1;

TextField tf1,tf2,tf3;

Label lb1,lb2,lb3;

public void init()

lb1 =new Label("Enter Dist (m) :-");

lb1.setBounds(100,40,100,20);

tf1 =new TextField();

tf1.setBounds(210,40,100,20);

lb2 =new Label("Enter Time (s) :-");

lb2.setBounds(100,80,100,20);

tf2 =new TextField();


tf2.setBounds(210,80,100,20);

lb3 =new Label("Speed is (m/s) :-");

lb3.setBounds(100,120,100,20);

tf3 =new TextField();

tf3.setBounds(210,120,100,20);

b1=new Button("speed");

Page 46 of 48

b1.setBounds(180,160,60,50);

add(lb1);

add(lb2);

add(lb3);

add(tf1);

add(tf2);

add(tf3);

add(b1);

b1.addActionListener(this);

setLayout(null);

public void actionPerformed(ActionEvent e)

int a = Integer.parseInt(tf1.getText());

int b = Integer.parseInt(tf2.getText());

float speed=0;

if(e.getSource() == b1)

speed=a/b;

tf3.setText(String.valueOf(speed));

OUTPUT

You might also like