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

Java Internal Lab

important question which come in lab experiment
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Internal Lab

important question which come in lab experiment
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 42

Q1.

Write a separate java code to implement each of the following:

Class, Command Line Argument. How to enter value through keyboard


Class Implementation:
import java.util.Scanner;

class Celebrity {

private String name;

private String profession;

private String achievement;

// Constructor

public Celebrity(String name, String profession, String achievement) {

this.name = name;

this.profession = profession;

this.achievement = achievement;

// Method to display information

public void displayInfo() {

System.out.println(name + " is a famous " + profession + " known for " + achievement + ".");

public class CelebrityDemo {

public static void main(String[] args) {

// Creating Scanner object for input

Scanner scanner = new Scanner(System.in);


// Input for football player

System.out.println("The most famous football player:");

String footballPlayer = scanner.nextLine();

// Input for actor

System.out.println("The famous actor:");

String actor = scanner.nextLine();

// Creating Celebrity objects

Celebrity footballCelebrity = new Celebrity(footballPlayer, "football player", "goals");

Celebrity actorCelebrity = new Celebrity(actor, "actor", "movies");

// Displaying information

footballCelebrity.displayInfo();

actorCelebrity.displayInfo();

// Closing Scanner

scanner.close();

OUTPUTS:

The most famous football player:

Ronaldo

The famous actor:

Salman khan
Ronaldo is a famous football player known for goals.

Salman khan is a famous actor known for movies.

Command-Line Arguments:
import java.util.Scanner;

public class CommandLineArgumentsDemo {

public static void main(String[] args) {

// Creating Scanner object for input

Scanner scanner = new Scanner(System.in);

// Input for football player

System.out.println("Enter the name of the most famous football player:");

String footballPlayer = scanner.nextLine();

// Input for actor

System.out.println("Enter the name of the famous actor:");

String actor = scanner.nextLine();

// Displaying information

System.out.println(footballPlayer + " and " + actor + " are most famous in their respective fields.");

// Closing Scanner

scanner.close();

}
OUTPUT:
Enter the name of the most famous football player:

Messi

Enter the name of the famous actor:

Amir

Messi and Amir are most famous in their respective fields.

2.Write a separate java code to implement each of the following datatype:


variable, constant, arrays, strings, vectors, wrappers classes, typecasting.
 Variable:

public class VariableExample {

public static void main(String[] args) {

int num = 50;

System.out.println("Value of num: " + num);

Output:

Value of num: 50

 Constant:

public class ConstantExample {

public static final int CONSTANT_VALUE = 100;

public static void main(String[] args) {

System.out.println("Value of constant: " + CONSTANT_VALUE);

Output:

Value of constant: 100


 Arryas:

public class ArraysExample {

public static void main(String[] args) {

int[] numbers = {10, 20, 30, 40, 50};

System.out.println("Elements of array:");

for (int num : numbers) {

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

Output:

Elements of array:

10 20 30 40 50

 Strings:

public class StringsExample {

public static void main(String[] args) {

String name= "Dhruv Singh";

System.out.println(“My name is ” + name);

Output:

My name is Dhruv Singh

 Vectors:

import java.util.Vector;
public class VectorsExample {

public static void main(String[] args) {

Vector<String> names = new Vector<>();

names.add("Harsh");

names.add("chirag");

names.add("Jay");

System.out.println("Names in vector:");

for (String name : names) {

System.out.println(name);

Output:

Names in vector:

Harsh

chirag

Jay

 Wrapper Classes:

public class WrapperClassesExample {

public static void main(String[] args) {

Integer intNum = 1000;

Double doubleNum = 3.14;

Character charValue = 'A';


System.out.println("Wrapper class value: " + number);

System.out.println("Double Value: " + doubleNum);

System.out.println("Character Value: " + charValue);

Output:

Integer Value: 1000

Double Value: 3.14

Character Value: A

 Typecasting:

public class TypecastingExample {

public static void main(String[] args) {

double doubleNum = 10.5;

int intNum = (int) doubleNum;

System.out.println("After typecasting: " + intNum);

Output:

After typecasting: 10

Q3. Write a separate Java Code to implement each of the following operators:
Arithmetic operator, Relational operator, Logical operator, Assignment
operator, Increment& Decrement operator, Conditional operator, Bitwise
operator ?: Operator.

Arithmetic operator
public class ArithmeticOperatorExample {
public static void main(String[] args) {

int a = 25;

int b = 15;

int sum = a + b; // Addition

int difference = a - b; // Subtraction

int product = a * b; // Multiplication

int quotient = a / b; // Division

int remainder = a % b; // Modulus

System.out.println("Sum: " + sum);

System.out.println("Difference: " + difference);

System.out.println("Product: " + product);

System.out.println("Quotient: " + quotient);

System.out.println("Remainder: " + remainder);

Output:

Sum: 40

Difference: 10

Product: 375

Quotient: 1

Remainder: 10

Relational operator:
public class RelationalOperatorExample {
public static void main(String[] args) {

int a = 25;

int b = 15

System.out.println("a > b " + (a > b));

System.out.println("a < b " + (a < b));

System.out.println("a >= b " + (a >= b));

System.out.println("a <= b " + (a <= b));

System.out.println("a == b " + (a == b));

System.out.println("a != b " + (a != b));

Output:

a > b true

a < b false

a >= b true

a <= b false

a == b false

a != b true

Logical operator:
public class LogicalOperatorExample {

public static void main(String[] args) {

boolean a = true;

boolean b = false;

System.out.println("a AND b: " + (a && b));


System.out.println("a OR b: " + (a || b));

System.out.println("NOT a: " + (!a));

System.out.println("NOT b: " + (!b));

Output:
a AND b: false

a OR b: true

NOT a: false

NOT b: true

Assignment operator
public class AssignmentOperatorExample {

public static void main(String[] args) {

int a = 25;

int b = 15;

System.out.println("a: " + a);

a += b;

System.out.println("a += b: " + a);

a -= b;

System.out.println("a -= b: " + a);

a *= b;

System.out.println("a *= b: " + a);


a /= b;

System.out.println("a /= b: " + a);

a %= b;

System.out.println("a %= b: " + a);

Output:

a: 25

a += b: 40

a -= b: 25

a *= b: 375

a /= b: 25

a %= b: 10

Increment& Decrement operator


public class IncrementDecrementOperatorExample {

public static void main(String[] args) {

int x = 20;

System.out.println("Initial value of x: " + x);

x++; // Increment

System.out.println("Value of x after increment: " + x);


x--; // Decrement

System.out.println("Value of x after decrement: " + x);

}
Output:

Initial value of x: 20

Value of x after increment: 21

Value of x after decrement: 20

Conditional operator
public class ConditionalOperatorExample {

public static void main(String[] args) {

int a = 20;

int b = 15;

int max = (a > b) ? a : b

System.out.println("Maximum value: " + max);

Output:

Maximum value: 20

Bitwise operator
public class BitwiseOperatorExample {

public static void main(String[] args) {

int a = 25; // Binary: 101

int b = 15; // Binary: 011


System.out.println("a & b: " + (a & b)); //Bitwise AND

System.out.println("a | b: " + (a | b)); //Bitwise OR

System.out.println("a ^ b " + (a ^ b)); //Bitwise XOR:

System.out.println("~a: " + (~a)); //Bitwise Complement

System.out.println("a << 1: " + (a << 1)); //Left Shift:

System.out.println("a >> 1: " + (a >> 1)); //Right Shift

Output:

a & b: 9

a | b: 31

a ^ b 22

~a: -26

a << 1: 50

a >> 1: 12

Ternary Operator:
public class ConditionalOperatorExample {

public static void main(String[] args) {

int a = 25;

int b = 15;

int max = (a > b) ? a : b;

System.out.println("Maximum value: " + max);

}
}

Output:

Maximum value: 25

Q4. Write a separate Java code to implement each of the following control
statements.

If-Else Statement:
public class IfElseExample {

public static void main(String[] args) {

int number = 10;

if (number % 2 == 0) {

System.out.println(number + " is even.");

} else {

System.out.println(number + " is odd.");

Output:

10 is even.

Switch Statement:
public class SwitchExample {

public static void main(String[] args) {

int day = 3;

String dayName;
switch (day) {

case 1:

dayName = "Sunday";

break;

case 2:

dayName = "Monday";

break;

case 3:

dayName = "Tuesday";

break;

case 4:

dayName = "Wednesday";

break;

case 5:

dayName = "Thursday";

break;

case 6:

dayName = "Friday";

break;

case 7:

dayName = "Saturday";

break;

default:

dayName = "Invalid day";

}
System.out.println("Day is: " + dayName);

Output

Day is: Tuesday

Loops statement:

For loop:
public class ForLoopExample {

public static void main(String[] args) {

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

System.out.println("Iteration " + i);

Output:

Iteration 1

Iteration 2

Iteration 3

Iteration 4

Iteration 5

Do-while Loop:
public class DoWhileLoopExample {

public static void main(String[] args) {

int i = 1;
do {

System.out.println("Iteration " + i);

i++;

} while (i <= 5);

Output:

Iteration 1

Iteration 2

Iteration 3

Iteration 4

Iteration 5

Break statements
public class BreakStatementExample {

public static void main(String[] args) {

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

if (i == 5) {

break;

System.out.println("Iteration " + i);

Output:

Iteration 1
Iteration 2

Iteration 3

Iteration 4

Continue Statement:
public class ContinueStatementExample {

public static void main(String[] args) {

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

if (i == 3) {

continue;

System.out.println("Iteration " + i);

Output:

Iteration 1

Iteration 2

Iteration 4

Iteration 5

Q5. Write a separate Java Code to implement each of the following sorting:

Bubble Sort:
public class BubbleSortExample {

public static void main(String[] args) {

int[] arr = {64, 34, 25, 12, 22, 11, 90};


System.out.println("Array before sorting:");

printArray(arr);

bubbleSort(arr);

System.out.println("Array after sorting:");

printArray(arr);

public static void bubbleSort(int[] arr) {

int n = arr.length;

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - i - 1; j++) {

if (arr[j] > arr[j + 1]) {

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

public static void printArray(int[] arr) {

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

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


}

System.out.println();

Output:

Array before sorting:

64 34 25 12 22 11 90

Array after sorting:

11 12 22 25 34 64 90

Selection Sort:
public class SelectionSortExample {

public static void main(String[] args) {

int[] arr = {64, 25, 12, 22, 11};

System.out.println("Array before sorting:");

printArray(arr);

selectionSort(arr);

System.out.println("Array after sorting:");

printArray(arr);

public static void selectionSort(int[] arr) {

int n = arr.length;
for (int i = 0; i < n - 1; i++) {

int minIndex = i;

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

if (arr[j] < arr[minIndex]) {

minIndex = j;

int temp = arr[minIndex];

arr[minIndex] = arr[i];

arr[i] = temp;

public static void printArray(int[] arr) {

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

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

System.out.println();

Output:

Array before sorting:

64 25 12 22 11

Array after sorting:


11 12 22 25 64

Insertion Sort:
public class InsertionSortExample {

public static void main(String[] args) {

int[] arr = {64, 25, 12, 22, 11};

System.out.println("Array before sorting:");

printArray(arr);

insertionSort(arr);

System.out.println("Array after sorting:");

printArray(arr);

public static void insertionSort(int[] arr) {

int n = arr.length;

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

int key = arr[i];

int j = i - 1;

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

j = j - 1;
}

arr[j + 1] = key;

public static void printArray(int[] arr) {

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

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

System.out.println();

Output:

Array before sorting:

64 25 12 22 11

Array after sorting:

11 12 22 25 64

Merge sort:
public class MergeSortExample {

public static void main(String[] args) {

int[] arr = {38, 27, 43, 3, 9, 82, 10};

System.out.println("Array before sorting:");

printArray(arr);
mergeSort(arr, 0, arr.length - 1);

System.out.println("Array after sorting:");

printArray(arr);

public static void mergeSort(int[] arr, int left, int right) {

if (left < right) {

int mid = (left + right) / 2;

mergeSort(arr, left, mid);

mergeSort(arr, mid + 1, right);

merge(arr, left, mid, right);

public static void merge(int[] arr, int left, int mid, int right) {

int n1 = mid - left + 1;

int n2 = right - mid;

int[] leftArr = new int[n1];

int[] rightArr = new int[n2];

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


leftArr[i] = arr[left + i];

for (int j = 0; j < n2; ++j)

rightArr[j] = arr[mid + 1 + j];

int i = 0, j = 0;

int k = left;

while (i < n1 && j < n2) {

if (leftArr[i] <= rightArr[j]) {

arr[k] = leftArr[i];

i++;

} else {

arr[k] = rightArr[j];

j++;

k++;

while (i < n1) {

arr[k] = leftArr[i];

i++;

k++;

while (j < n2) {


arr[k] = rightArr[j];

j++;

k++;

public static void printArray(int[] arr) {

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

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

System.out.println();

Output:

Array before sorting:

38 27 43 3 9 82 10

Array after sorting:

3 9 10 27 38 43 82

Q6. Write a separate Java Code in implement each of the following:

Class, Object, Constructors Method, Method of overloading and Method


Overriding

Class, Object:

// Example: Creating a class named "FootballPlayer"


class FootballPlayer { public static void main(String[] args) {

// Create two football player objects

FootballPlayer ronaldo = new FootballPlayer("Ronaldo", 450);

FootballPlayer messi = new FootballPlayer("Messi", 600);

// Display player info

ronaldo.displayInfo();

messi.displayInfo();

String name;

int goalsScored;

// Constructor

public FootballPlayer(String name, int goalsScored) {

this.name = name;

this.goalsScored = goalsScored;

// Method to display player info

public void displayInfo() {

System.out.println("Player: " + name);

System.out.println("Goals Scored: " + goalsScored);

OUTPUTS:
Player: Ronaldo

Goals Scored: 450

Player: Messi

Goals Scored: 600

Constructors Method
public class MyClass {

private int value;

// Constructor

public MyClass() {

value = 90;

public int getValue() {

return value;

public static void main(String[] args) {

MyClass obj = new MyClass(); // Constructor is invoked

System.out.println("The value is " + obj.getValue());

OUTPUTS:

The value is 90

Method Overloading:
class Calculator { public static void main(String[] args) {
Calculator calc = new Calculator();

System.out.println("Sum of 10 and 30: " + calc.add(10, 30));

System.out.println("Sum of 40, 50, and 60: " + calc.add(40, 50, 60));

// Method to add two integers

public int add(int a, int b) {

return a + b;

// Method to add three integers (overloaded)

public int add(int a, int b, int c) {

return a + b + c;

OUTPUTS:

Sum of 10 and 30: 40

Sum of 40, 50, and 60: 150

class Bank {

int getRateOfInterest() {

return 0; // Default implementation (to be overridden)

Method Overriding:

class Player {

void speak() {
System.out.println("I am a player.");

public static void main(String[] args) {

Footballer ronaldo = new Footballer();

FilmStar salman = new FilmStar();

ronaldo.speak();

salman.speak();

class Footballer extends Player {

//@Override

void speak() {

System.out.println("I am a footballer.");

class FilmStar extends Player {

//@Override

void speak() {

System.out.println("I am a film star.");

OUTPUTS:

I am a footballer.
I am a film star.

Q7.Wite a separate Java code to implement each of the following:


Final Variable, final Class, Final method, Abstract class, Abstract method and
Concrete Method

Final Variable
public class FinalVariableExample {

public static void main(String[] args) {

final int MAX_VALUE = 100;

// MAX_VALUE = 200; // This will cause a compilation error

System.out.println("Maximum value: " + MAX_VALUE);

OUTPUT:

Maximum value: 100

Final Class
final class FinalClassExample {

// Class members and methods

Final method
public class Parent {

public final void display() {

System.out.println("This is a final method.");

public class FinalMethodExample extends Parent {

// Trying to override final method will result in a compilation error


/*public void display() {

System.out.println("This is an overridden method.");

}*/

Abstract class
abstract class OlympicGames {

abstract void hostCountry();

void participatingCountries() {

System.out.println("Number of participating countries: 200");

public class TokyoOlympics extends OlympicGames {

void hostCountry() {

System.out.println("Host country: Japan");

public static void main(String[] args) {

TokyoOlympics tokyoOlympics = new TokyoOlympics();

tokyoOlympics.hostCountry();

tokyoOlympics.participatingCountries();

OUTPUT:
Host country: Japan

Number of participating countries: 200

Abstract method
abstract class Sports {

abstract void typeOfGame();

public class Basketball extends Sports {

void typeOfGame() {

System.out.println("Type of game: Team sport");

public static void main(String[] args) {

Basketball basketball = new Basketball();

basketball.typeOfGame();

OUTPUT:

Type of game: Team sport

Concrete Method:
abstract class Sport {

abstract void typeOfGame();

void players() {

System.out.println("Number of players: 11");


}

public class Football extends Sport {

void typeOfGame() {

System.out.println("Type of game: Team sport");

public static void main(String[] args) {

Football football = new Football();

football.typeOfGame();

football.players();

OUTPUT:

Type of game: Team sport

Number of players: 11

Q8. . Write a separate Java Code to implement each of the following OOPs
concepts:

Abstraction, Polymorphism, Encapsulation, Inheritance

Abstraction:
abstract class OlympicGame {

abstract void hostCountry();

abstract void participatingCountries();


}

class TokyoOlympics extends OlympicGame {

void hostCountry() {

System.out.println("Host country: Japan");

void participatingCountries() {

System.out.println("Number of participating countries: 200");

public class AbstractionExample {

public static void main(String[] args) {

OlympicGame olympics = new TokyoOlympics();

olympics.hostCountry();

olympics.participatingCountries();

OUTPUT:

Host country: Japan

Number of participating countries: 200

Polymorphism
class OlympicGame {

void display() {
System.out.println("This is an Olympic game.");

class SummerOlympics extends OlympicGame {

void display() {

System.out.println("This is a Summer Olympic game.");

class WinterOlympics extends OlympicGame {

void display() {

System.out.println("This is a Winter Olympic game.");

public class PolymorphismExample {

public static void main(String[] args) {

OlympicGame summer = new SummerOlympics();

OlympicGame winter = new WinterOlympics();

summer.display();

winter.display();

OUTPUT:
This is a Summer Olympic game.

This is a Winter Olympic game.

Encapsulation
class Olympic {

private String hostCountry;

private int participatingCountries;

public String getHostCountry() {

return hostCountry;

public void setHostCountry(String hostCountry) {

this.hostCountry = hostCountry;

public int getParticipatingCountries() {

return participatingCountries;

public void setParticipatingCountries(int participatingCountries) {

this.participatingCountries = participatingCountries;

public class EncapsulationExample {


public static void main(String[] args) {

Olympic tokyo2020 = new Olympic();

tokyo2020.setHostCountry("Japan");

tokyo2020.setParticipatingCountries(200);

System.out.println("Host country: " + tokyo2020.getHostCountry());

System.out.println("Number of participating countries: " + tokyo2020.getParticipatingCountries());

OUTPUT:

Host country: Japan

Number of participating countries: 200

Inheritance
class Olympic {

void display() {

System.out.println("This is an Olympic game.");

class TokyoOlympics extends Olympic {

void hostCountry() {

System.out.println("Host country: Japan");

void participatingCountries() {
System.out.println("Number of participating countries: 200");

public class InheritanceExample {

public static void main(String[] args) {

TokyoOlympics tokyoOlympics = new TokyoOlympics();

tokyoOlympics.display();

tokyoOlympics.hostCountry();

tokyoOlympics.participatingCountries();

OUTPUT:

This is an Olympic game.

Host country: Japan

Number of participating countries: 200

Q9. Write a separate Java Code to implement each of the following:

Exception handling with Try, Catch, Throw, Throws, and Finally Multiple catch
statement with the following exceptions: Arithmetic Exception, Array Out Of
Bounds Exception and Array Store Exception
class ExceptionHandlingExample {

public static void main(String[] args) {

try {

int result = divide(15, 0);

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

} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e.getMessage());

} catch (ArrayIndexOutOfBoundsException e) {

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

} catch (ArrayStoreException e) {

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

} finally {

System.out.println("Finally ");

// Cause ArithmeticException

try {

int[] arr = new int[1];

System.out.println(arr[5]); // ArrayIndexOutOfBoundsException

} catch (ArrayIndexOutOfBoundsException e) {

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

} finally {

System.out.println("Finally ");

// Cause ArrayStoreException

try {

Object[] objArr = new Integer[10];

objArr[0] = "Line"; // ArrayStoreException

} catch (ArrayStoreException e) {

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


} finally {

System.out.println("Finally:");

static int divide(int a, int b) {

return a / b;

OUTPUT:

ArithmeticException caught: / by zero

Finally

ArrayIndexOutOfBoundsException caught: Index 5 out of bounds for length 1

Finally

ArrayStoreException caught: java.lang.String

Finally

10. Write a separate Java Code to implement the following:

a) Interface

b) Packages and how to import them


// Interface example

interface OlympicGames {

void hostedBy(String country);

void numberOfCountries(int count);

}
class TokyoOlympics implements OlympicGames {

public void hostedBy(String country) {

System.out.println("Tokyo Olympics was hosted by " + country);

public void numberOfCountries(int count) {

System.out.println("Number of countries participated: " + count);

public class Main {

public static void main(String[] args) {

// Interface example

OlympicGames olympics = new TokyoOlympics();

olympics.hostedBy("Japan");

olympics.numberOfCountries(206);

OUTPUT:

Tokyo Olympics was hosted by Japan

Number of countries participated: 206

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy