Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 42

Q1- Write a program to print Hello world.

Code:

class Hello{
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

Output:

RISHABH GUPTA BCA IV(M2) 36013702021


Q2- Write a program to compute the area of a circle.

Code:

public class Circle {


public static void main(String[] args)
{
int radius;
double pi = 3.142, area;
radius = 5;
area = pi * radius * radius;
System.out.println("Area of circle is :" + area);
}
}

Output:

RISHABH GUPTA BCA IV(M2) 36013702021


Q3- Write a program based on type casting and conversions.

Code:
import java.io.*;

public class type {

public static void main(String[] args)

int a = 6;

double db = (double)a;

System.out.println(db);

int db1 = (int)db;

System.out.println(db1);

Output:

RISHABH GUPTA BCA IV(M2) 36013702021


Q4- Write a program to add, subtract, divide and multiply two numbers.

Code:
import java.util.Scanner;

public class Arth

public static void main(String args[])

int first, second, add, subtract, multiply;

float devide;

Scanner scanner = new Scanner(System.in);

System.out.print("Enter Two Numbers : ");

first = scanner.nextInt();

second = scanner.nextInt();

add = first + second;

subtract = first - second;

multiply = first * second;

divide = (float) first / second;

System.out.println("Sum = " + add);

System.out.println("Difference = " + subtract);

System.out.println("Multiplication = " + multiply);

System.out.println("Division = " + divide);

RISHABH GUPTA BCA IV(M2) 36013702021


Output:

RISHABH GUPTA BCA IV(M2) 36013702021


Q5. Write a program to print the grade of a student

CODE:-
import java.util.Scanner;

public class Grades


{
public static void main(String args[])
{
int marks[] = new int[6];
int i;
float total=0, avg;
Scanner scanner = new Scanner(System.in);

for(i=0; i<6; i++) {


System.out.print("Enter Marks of Subject"+(i+1)+":");
marks[i] = scanner.nextInt();
total = total + marks[i];
}
scanner.close();
avg = total/6;
System.out.print("The student Grade is: ");
if(avg>=80)
{
System.out.print("A");
}
else if(avg>=60 && avg<80)
{
System.out.print("B");
}
else if(avg>=40 && avg<60)
{
System.out.print("C");
}
else
{
System.out.print("D");
}

RISHABH GUPTA BCA IV(M2) 36013702021


}
}
OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q6. WAP that accepts number as Command line arguments.

CODE:-
class CMD {

public static void main(String[] args) {

for (String str: args) {

// convert into integer type

int argument = Integer.parseInt(str);

System.out.println("Argument in integer form: " + argument);

OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q7. WAP that generates a number and checks whether it is randomly prime
or not.

CODE:-
import java.util.Random;

public class GRN {

public static void main(String[] args) {


Random rand = new Random();
int num = rand.nextInt(1000) + 1;
System.out.println("Random number generated: " + num);
boolean isPrime = true;
if (num < 2) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println(num + " is a prime number");
} else {
System.out.println(num + " is not a prime number");
}
}
}

OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q8. Write program that randomly generates a number from a range 10-99
and checks whether it is Armstrong or not.

CODE:-
import java.util.Random;

public class AC {

public static void main(String[] args) {

// Generate a random number between 10 and 99


Random rand = new Random();
int num = rand.nextInt(90) + 10;
System.out.println("Random number generated: " + num);

// Check if the number is an Armstrong number


int sum = 0;
int originalNum = num;
while (num != 0) {
int digit = num % 10;
sum += Math.pow(digit, 3);
num /= 10;
}
if (sum == originalNum) {
System.out.println(originalNum + " is an Armstrong number");
} else {
System.out.println(originalNum + " is not an Armstrong number");
}
}
}

OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q9. Write a program to insert an array and print those elements using
command line arguments
CODE:-

public class Arr {


public static void main(String[] args) {
int[] array = new int[args.length];

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


array[i] = Integer.parseInt(args[i]);
}

System.out.println("The elements in the array are:");

for (int element : array) {


System.out.println(element);
}
}
}
OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q10. Write a program to initialize and print the elements of an array.

CODE:-

public class Arin {


public static void main(String[] args) {
int[] array = {8, 4, 5, 7, 6};

System.out.println("The elements in the array are:");

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


System.out.println(array[i]);
}
}
}

OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q11. Write a program to sort an array in ascending and descending order.

CODE:-
public class Sa {
public static void main(String[] args) {
int[] arr = {5, 2, 8, 7, 1};
int temp = 0;

//Displaying elements of original array


System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();

//Sort the array in descending order


for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if(arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

//Displaying elements of array after sorting in descending order


System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();

//Sort the array in ascending order


for (int i = 0; i < arr.length; i++) {
for (int j = i + 1; j < arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];

RISHABH GUPTA BCA IV(M2) 36013702021


arr[j] = temp;
}
}
}

//Displaying elements of array after sorting in ascending order


System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}

OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q12. WAP to perform linear search on an Array of 5 integers

CODE:-

import java.util.Scanner;

class Linear {
public static void main(String args[]) {
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter those " + n + " elements");
for (c = 0; c < n; c++) {
array[c] = in.nextInt();
}
System.out.println("Enter value to find");
search = in.nextInt();
for (c = 0; c < n; c++) {
if (array[c] == search) { /* Searching element is present */
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) { /* Element to search isn't present */
System.out.println(search + " isn't present in array.");
}
}
}
OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q13. WAP to perform binary search on an Array of 5 integers

CODE:-
import java.util.Arrays;
import java.util.Scanner;

public class Binary {


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

int[] arr = new int[5];


System.out.println("Enter 5 integers:");
for (int i = 0; i < arr.length; i++) {
arr[i] = sc.nextInt();
}

Arrays.sort(arr);

System.out.println("Enter the element to search:");


int searchElement = sc.nextInt();

int low = 0;
int high = arr.length - 1;
boolean found = false;

while (low <= high) {


int mid = (low + high) / 2;

if (arr[mid] == searchElement) {
System.out.println("Element " + searchElement + " found at index " + mid);
found = true;
break;
} else if (arr[mid] < searchElement) {
low = mid + 1;
} else {
high = mid - 1;
}
}

if (!found) {

RISHABH GUPTA BCA IV(M2) 36013702021


System.out.println("Element " + searchElement + " not found in the array");
}
}
}

OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q14. WAP to display smallest element of an Array of 5 integers

CODE:-
public class Small {
public static void main(String[] args) {
//Initialize array
int[] arr = new int[] {8, 59, 11 , 55, 56};

//Initialize min with first element of array.


int min = arr[0];

//Loop through the array


for (int i = 1; i < arr.length; i++) {
//Compare elements of array with min
if (arr[i] < min) {
min = arr[i];
}
}

System.out.println("Smallest element present in given array: " + min);


}
}

OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q15. WAP to display difference between smallest and largest elements of an
Array of 5 integers.

CODE:-
import java.util.Arrays;

class Diffrence {
public static void main(String[] args) {
int[] array_nums = {5, 9,1 , 4, 8};
System.out.println("Original Array: " + Arrays.toString(array_nums));

int max_val = array_nums[0];


int min_val = array_nums[0];

for (int i = 1; i < array_nums.length; i++) {


if (array_nums[i] > max_val) {
max_val = array_nums[i];
} else if (array_nums[i] < min_val) {
min_val = array_nums[i];
}
}

System.out.println("Difference between the largest and smallest values of the said array: "
+ (max_val - min_val));
}
}

OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q16.Write a program to perform following Matrix operations using arrays.
1. Addition

CODE:-

class Add {
public static void main(String[] args) {
int rows = 2, columns = 3;
int[][] firstMatrix = { {5, 9, 1}, {8, 5, 6} };
int[][] secondMatrix = { {-4, 2, 1}, {5, 6, 3} };

// Adding Two matrices


int[][] sum = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
sum[i][j] = firstMatrix[i][j] + secondMatrix[i][j];
}
}

// Displaying the result


System.out.println("Sum of two matrices is: ");
for (int[] row : sum) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}

OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


2. Multiplication

CODE:-

public class Multiply {


public static void main(String[] args) {
int r1 = 2, c1 = 3;
int r2 = 3, c2 = 2;
int[][] firstMatrix = { {3, -2, 5}, {3, 0, 4} };
int[][] secondMatrix = { {2, 3}, {-9, 0}, {0, 4} };

// Mutliplying Two matrices


int[][] product = new int[r1][c2];
for(int i = 0; i < r1; i++) {
for (int j = 0; j < c2; j++) {
for (int k = 0; k < c1; k++) {
product[i][j] += firstMatrix[i][k] * secondMatrix[k][j];
}
}
}

// Displaying the result


System.out.println("Multiplication of two matrices is: ");
for(int[] row : product) {
for (int column : row) {
System.out.print(column + " ");
}
System.out.println();
}
}
}
OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q17. Write a program to demonstrate the working of any Ten String class
functions.
CODE:-
import java.io.*;
import java.util.*;

class Fu{
public static void main(String[] args) {
String s = "SeeksforCakes";
// or String s= new String ("SeeksforCakes");

// Returns the number of characters in the String.


System.out.println("String length = " + s.length());

// Returns the character at ith index.


System.out.println("Character at 3rd position = " + s.charAt(3));

// Return the substring from the ith index character


// to end of string
System.out.println("Substring " + s.substring(3));

// Returns the substring from i to j-1 index.


System.out.println("Substring = " + s.substring(2, 5));

// Concatenates string2 to the end of string1.


String s1 = "seeks";
String s2 = "forcakes";
System.out.println("Concatenated string = " + s1.concat(s2));

// Returns the index within the string


// of the first occurrence of the specified string.
String s4 = "Learn Share Learn";
System.out.println("Index of Share " + s4.indexOf("Share"));

// Returns the index within the string of the


// first occurrence of the specified string,
// starting at the specified index.
System.out.println("Index of a = " + s4.indexOf('a', 3));

// Checking equality of Strings


Boolean out = "Seeks".equals("seeks");
System.out.println("Checking Equality " + out);
out = "Seeks".equals("Seeks");

RISHABH GUPTA BCA IV(M2) 36013702021


System.out.println("Checking Equality " + out);

out = "Seeks".equalsIgnoreCase("sEeks ");


System.out.println("Checking Equality " + out);

// If ASCII difference is zero then the two strings are similar


int out1 = s1.compareTo(s2);
System.out.println("the difference between ASCII value is=" + out1);

// Converting cases
String word1 = "SeeKyMe";
System.out.println("Changing to lower Case " + word1.toLowerCase());

// Converting cases
String word2 = "SeekyME";
System.out.println("Changing to UPPER Case " + word2.toUpperCase());

// Trimming the word


String word4 = " Learn Share Learn ";
System.out.println("Trim the word " + word4.trim());

// Replacing characters
String str1 = "feeksforfeeks";
System.out.println("Original String " + str1);
String str2 = "feeksforfeeks".replace('f', 's');
System.out.println("Replaced f with s -> " + str2);
}
}
OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q18. WAP to extract surname from complete name

CODE:-

import java.util.Scanner;

public class Surname {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your complete name: ");
String fullName = scanner.nextLine();

String[] nameParts = fullName.split("\\s+");


String lastName = nameParts[nameParts.length - 1];

System.out.println("Your surname is: " + lastName);


}
}
OUTPUT:-

RISHABH GUPTA BCA IV(M2) 36013702021


Q19. Write a program to create a class called String Demo and declare three
strings and use functions like lengthchar at and equals on them.

CODE:

public class StringDemo {


public static void main(String[] args) {
String str1 = "Hello";
String str2 = "World";
String str3 = "hello";

System.out.println("Length of str1: " + str1.length());


System.out.println("Character at index 2 of str2: " + str2.charAt(2));
System.out.println("str1 equals str3 (case sensitive): " + str1.equals(str3));
}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q20) Write a program to create a class called Box and calculate its volume by
calling its method.

CODE:
public class Box {

double length;

double width;

double height;

public Box(double l, double w, double h) {

length = l;

width = w;

height = h;

public double volume() {

return length * width * height;

public static void main(String[] args) {

Box box1 = new Box(3, 4, 5);

double vol = box1.volume();

System.out.println("Volume of box1 is " + vol);

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q21) Write a program to create a class called Test and pass its object to one of
its method to illustrate usage of reference variables.

CODE:

public class Test {


int x;

public static void main(String[] args) {


Test obj = new Test(); // create a Test object
obj.x = 5; // set the value of x to 5
obj.show(obj); // pass the object to the show method
}

public void show(Test t) {


System.out.println("The value of x is " + t.x);
}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q22) Write a program to create a class called Use Static and declare some
static variables, a static method that will print those variables and static block
which will perform some operation on that variable.

CODE:
public class Static {
static int staticVar1 = 10;
static String staticVar2 = "Hello, World!";

static {
// static block to perform some operation
staticVar1 += 5;
staticVar2 += " Welcome to Java!";
}

static void printStaticVariables() {


// static method to print static variables
System.out.println("Static Variable 1: " + staticVar1);
System.out.println("Static Variable 2: " + staticVar2);
}

public static void main(String[] args) {


// calling static method without creating object
Static.printStaticVariables();
}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q23) Write a program to create a class Add that will add to numbers by using
a default constructor.

CODE:
public class Add {
int num1, num2;

Add() {
num1 = 0;
num2 = 0;
}

int addNumbers() {
return num1 + num2;
}

public static void main(String[] args) {


Add obj = new Add();
obj.num1 = 10;
obj.num2 = 20;
int sum = obj.addNumbers();
System.out.println("Sum of two numbers is: " + sum);
}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q24) Write a program to create a class called triangle with base and height as
the attributes and calculate its area using parameterized constructor.

CODE:

public class Triangle {


private double base;
private double height;

public Triangle(double b, double h) {


base = b;
height = h;
}

public double getArea() {


return 0.5 * base * height;
}

public static void main(String[] args) {


Triangle t = new Triangle(5, 10);
System.out.println("Area of triangle with base " + t.base + " and height " + t.height + " is "
+ t.getArea());
}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q25) Write a program to create a class called Rectangle and calculate its area
using this keyword.

CODE:

class Rectangle {
int length;
int width;

Rectangle(int length, int width) {


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

int calculateArea() {
return this.length * this.width;
}

public static void main(String[] args) {


Rectangle rectangle = new Rectangle(5, 10);
int area = rectangle.calculateArea();
System.out.println("Area of rectangle: " + area);
}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q26) Write a program to create a class Area and calculate area of rectangle
and circle using method overloading.

CODE:

class Area {

public void calculateArea(int length, int breadth) {


int area = length * breadth;
System.out.println("Area of Rectangle: " + area);
}

public void calculateArea(double radius) {


double area = Math.PI * radius * radius;
System.out.println("Area of Circle: " + area);
}

public static void main(String[] args) {


Area obj = new Area();
obj.calculateArea(5, 10); // calling the method to calculate area of rectangle
obj.calculateArea(5.0); // calling the method to calculate area of circle
}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q27) Write a program to create a class called Box with instance variables
width, height and depth. Create another class BoxWeight which inherits class
Box with an additional instance variable weight. Compute the volume of the
box using inheritance.

CODE:

class Box {
double width;
double height;
double depth;

double volume() {
return width * height * depth;
}
}

class BoxWeight extends Box {


double weight;

BoxWeight(double w, double h, double d, double m) {


width = w;
height = h;
depth = d;
weight = m;
}
}

class Main {
public static void main(String[] args) {
BoxWeight myBox = new BoxWeight(10, 20, 30, 40);
double volume = myBox.volume();

System.out.println("Volume of Box: " + volume);


}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q28) Implement the above program using super keyword.

CODE:
class Box {
double width;
double height;
double depth;

double volume() {
return width * height * depth;
}
}

class BoxWeight extends Box {


double weight;

BoxWeight(double w, double h, double d, double m) {


super();
width = w;
height = h;
depth = d;
weight = m;
}

double getWeight() {
return weight;
}
}

class Main {
public static void main(String[] args) {
BoxWeight myBox = new BoxWeight(10, 20, 30, 40);
double volume = myBox.volume();

System.out.println("Volume of Box: " + volume);


}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q29) Create a class Figure and its 2 subclasses Rectangle and Triangle and
calculate its area using dynamic method dispatch

CODE:
class Figure {
double dim1;
double dim2;

Figure(double a, double b) {
dim1 = a;
dim2 = b;
}

double area() {
System.out.println("Area for Figure is undefined.");
return 0;
}
}

class Rectangle extends Figure {


Rectangle(double a, double b) {
super(a, b);
}

double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

class Triangle extends Figure {


Triangle(double a, double b) {
super(a, b);
}

double area() {
System.out.println("Inside Area for Triangle.");
return 0.5 * dim1 * dim2;
}
}

class Main {
public static void main(String[] args) {
Figure f = new Figure(10, 10);
Rectangle r = new Rectangle(9, 5);
Triangle t = new Triangle(8, 6);

RISHABH GUPTA BCA IV(M2) 36013702021


Figure figref;

figref = f;
System.out.println("Area is " + figref.area());

figref = r;
System.out.println("Area is " + figref.area());

figref = t;
System.out.println("Area is " + figref.area());
}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q30) Implement the above program using abstract classes by making Figure
class abstract

CODE:
abstract class Figure {
double dim1;
double dim2;

Figure(double a, double b) {
dim1 = a;
dim2 = b;
}

abstract double area();


}

class Rectangle extends Figure {


Rectangle(double a, double b) {
super(a, b);
}

double area() {
System.out.println("Inside Area for Rectangle.");
return dim1 * dim2;
}
}

class Triangle extends Figure {


Triangle(double a, double b) {
super(a, b);
}

double area() {
System.out.println("Inside Area for Triangle.");
return 0.5 * dim1 * dim2;
}
}

class Main {
public static void main(String[] args) {
Figure f = new Rectangle(10, 10);
Figure r = new Rectangle(9, 5);
Figure t = new Triangle(8, 6);

System.out.println("Area is " + f.area());

RISHABH GUPTA BCA IV(M2) 36013702021


System.out.println("Area is " + r.area());

System.out.println("Area is " + t.area());


}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q31) Write relevant programs to show the usage of final keyword with class,
variables and methods in java.

CODE:

1.Final Class

final class MyClass {


// class code
}

// This will give a compile error since the MyClass class is final and cannot be subclassed.
class MySubClass extends MyClass {
// subclass code
}

2.Final Variable

class MyClass {
final int myValue = 10;

void printValue() {
System.out.println("The value is: " + myValue);
}
}

class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.myValue = 20; // This will give a compile error since myValue is final
obj.printValue(); // This will output "The value is: 10"
}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


3.Final Method

class MyClass {
final void printMessage() {
System.out.println("Hello World");
}
}

class MySubClass extends MyClass {


void printMessage() { // This will give a compile error since printMessage is final
System.out.println("Hi there");
}
}

class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.printMessage(); // This will output "Hello World"
MySubClass subObj = new MySubClass();
subObj.printMessage(); // This will also output "Hello World"
}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q32) Write relevant programs showing the usage of package and access
protection in java.

CODE:
class ParentClass {
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

class ChildClass extends ParentClass {


void accessData() {
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}
}

public class Main {


public static void main(String[] args) {
ChildClass obj = new ChildClass();
obj.showData();
obj.accessData();
}
}
OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021


Q33) Write relevant programs to show the concept of importing a package

CODE:

import java.io.*;
public class MyFile {
public static void main(String[] args) {
// Create a new File object
File file = new File("myFile.txt");

try {
// Create a new FileWriter object
FileWriter writer = new FileWriter(file);

// Write some text to the file


writer.write("Hello, world!");

// Close the writer


writer.close();
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
String line = br.readLine();
System.out.println(line);

// Close the reader


reader.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}

OUTPUT:

RISHABH GUPTA BCA IV(M2) 36013702021

You might also like