0% found this document useful (0 votes)
31 views21 pages

Java Practical File for CSE Students

Uploaded by

jaydityashopy
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)
31 views21 pages

Java Practical File for CSE Students

Uploaded by

jaydityashopy
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

ENGINEERING COLLEGE BIKANER

JAVA PRACTICAL FILE

DATE OF SUBMISSION: 09-10-2023

SUBMITTED TO: SUBMITTED BY:


MR. RAHUL AGGARWAL NAME: NEHA PAREEK
(Assistant Professor) BRANCH: CSE ‘B’
ROLLNo: 21EEBCS074
INDEX
1. Print Hello World.
2. Sum of two numbers.
3. Print Prime number series.
4. Check weather the given number is Even OR Odd.
5. Print Square pa ern using for Loop.
6. Use of all Operators.
7. Print Fibonacci Series
8. Write program to execute the Control Statements.
9. Find the K th odd number from the series provided
by user without Using array.
10. Without using array find the 2 nd largest number f
from the inputs Provided by user (end of inputs
should be with -1). *without using array
11. Output the number of dis nct elements from the
shorted Sequence provided by user (end of inputs
should be with -1)
12. Write a program of 2D and 3D array
13. Write a java code to explain single and mul ple
inheritance
14. Write a program of excep on handeling (try catch
throw)
15. Write a program of Method overriding
1. Print Hello World.
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}

OUTPUT:
Hello, World!
2. Sum of two numbers.

import [Link];

public class SumOfTwoIntegers {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter the first integer: ");
int firstNumber = [Link]();

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


int secondNumber = [Link]();
int sum = firstNumber + secondNumber;

[Link]("The sum of " + firstNumber + " and " +


secondNumber + " is " + sum);
}
}

OUTPUT:
Enter the first integer: 5
Enter the second integer: 10
The sum of 5 and 10 is 15
3. Print Prime number series.

public class PrimeNumberSeries {


public static void main(String[] args) {
int limit = 100;
[Link]("Prime numbers up to " + limit + ":");
for (int num = 2; num <= limit; num++) {
boolean isPrime = true;
for (int i = 2; i * i <= num; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
if (isPrime) {
[Link](num + " ");
}
}
}
}

OUTPUT:
Prime numbers up to 20 : 2 3 5 7 11 13 17
4. Check weather the given number is Even OR Odd.

import [Link];

public class EvenOrOdd {


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

[Link]("Enter a number: ");


int number = [Link]();

if (isEven(number)) {
[Link](number + " is even.");
} else {
[Link](number + " is odd.");
}
}

public static boolean isEven(int number) {


return number % 2 == 0;
}
}

OUTPUT:
Enter a number: 17
number is odd
5. Print Square pattern using for Loop.

import [Link];

public class SquarePattern {


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

[Link]("Enter the size of the square: ");


int size = [Link]();

for (int i = 0; i < size; i++) {


for (int j = 0; j < size; j++) {
[Link]("* ");
}
[Link]();
}
}
}

OUTPUT:
Enter the size of the square: 5
*****
*****
*****
*****
*****
6. Use of all Operators.
public class OperatorExample {
public static void main(String[] args) {
int a = 10;
int b = 5;

int addition = a + b;
boolean greaterThan = (a > b);
boolean andOperator = (true && false);
int x = 10;
x += 5;
int counter = 5;
counter++;
int bitwiseAnd = a & b;
int max = (a > b) ? a : b;

[Link]("Addition: " + addition);


[Link]("Greater Than: " + greaterThan);
[Link]("And Operator: " + andOperator);
[Link]("Incremented Counter: " + counter);
[Link]("Bitwise AND: " + bitwiseAnd);
[Link]("Max: " + max);
}
}

OUTPUT:
Addition: 15
Greater Than: true
And Operator: false
Incremented Counter: 6
Bitwise AND: 0
Max: a
7. Print Fibonacci Series .
public class FibonacciSeries {
public static void main(String[] args) {
int numTerms = 10;
int prev = 0, current = 1;

[Link]("Fibonacci Series: ");

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


[Link](prev + " ");
int next = prev + current;
prev = current;
current = next;
}
}
}

OUTPUT:
Fibonacci Series: 0 1 1 2 3 5 8 13 21 34
8. Write program to execute the Control Statements.

import [Link];

public class ControlStatementsExample {


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

// If statement
[Link]("Enter a number: ");
int number = [Link]();
if (number > 0) {
[Link]("The number is positive.");
} else if (number < 0) {
[Link]("The number is negative.");
} else {
[Link]("The number is zero.");
}

// Switch statement
[Link]("Enter a day of the week (1-7): ");
int day = [Link]();
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day");
}

// While loop
[Link]("Enter a positive number: ");
int count = [Link]();
while (count > 0) {
[Link]("Countdown: " + count);
count--;
}

// For loop
[Link]("Enter a number for the multiplication table: ");
int tableNumber = [Link]();
[Link]("Multiplication table for " + tableNumber + ":");
for (int i = 1; i <= 10; i++) {
[Link](tableNumber * i + “ “);
}
}
}

OUTPUT:
Enter the number: 4
The number is positive.
Enter a day of the week (1-7): 3
Wednesday
Enter a positive number: 4
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Enter a number for the multiplication table: 2
Multiplication table for 2 :
2 4 6 8 10 12 14 16 18 20
9. Find the K th odd number from the series provided by
user without Using array.

import [Link];

public class KthOddNumberInUserSeries {


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

[Link]("Enter the series of numbers (space-separated): ");


String input = [Link]();

[Link]("Enter the value of K: ");


int k = [Link]();

int count = 0;
int kthOdd = -1;
int start = 0;

for (int i = 0; i < [Link](); i++) {


if ([Link](i) == ' ' || i == [Link]() - 1) {
int number;
if (i == [Link]() - 1) {
number = [Link]([Link](start));
} else {
number = [Link]([Link](start, i));
}

if (number % 2 != 0) {
count++;
if (count == k) {
kthOdd = number;
break;
}
}

start = i + 1;
}
}

if (kthOdd != -1) {
[Link]("The " + k + "th odd number in the series is: " +
kthOdd);
} else {
[Link]("There are less than " + k + " odd numbers in the
series.");
}
}
}

OUTPUT:
Enter the series of numbers (space-separated): 3 5 2 8 7 6 9
Enter the value of K: 3
The 3rd odd number in the series is: 7
10. Without using array find the 2 nd largest number
from the inputs Provided by user (end of inputs should be
with -1). *without using array.

import [Link];

public class SecondLargestNumber {


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

[Link]("Enter a series of numbers (-1 to end):");

int largest = Integer.MIN_VALUE;


int secondLargest = Integer.MIN_VALUE;
int input;

while (true) {
input = [Link]();

if (input == -1) {
break;
}
if (input > largest) {
secondLargest = largest;
largest = input;
} else if (input > secondLargest && input != largest) {
secondLargest = input;
}
}

if (secondLargest != Integer.MIN_VALUE) {
[Link]("The second largest number is: " + secondLargest);
} else {
[Link]("There is no second largest number.");
}
}
}

OUTPUT:
Enter a series of numbers (-1 to end): 7 4 9 2 6 -1
The second largest number is: 7
11. Output the number of distinct elements from the
shorted Sequence provided by user (end of inputs should
be with -1).

import [Link];
public class CountDistinctElements {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a sorted sequence of numbers (-1 to end):");

int prev = Integer.MIN_VALUE;


int distinctCount = 0;
while (true) {
int input = [Link]();

if (input == -1) {
break;
}

if (input != prev) {
distinctCount++;
}

prev = input;
}
[Link]("The number of distinct elements is: " +
distinctCount);
}
}

OUTPUT:
Enter a sorted sequence of numbers (-1 to end): 2 2 3 5 5 5 7 7 7 7 7 –1
The number of distinct elements is: 4
12. Write a program of 2D and 3D array .

// 2D ARRAY
public class TwoDArrayExample {
public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

int element = matrix[1][2];


[Link]("Element at (1, 2): " + element);
}
}

// 3D ARRAY
public class ThreeDArrayExample {
public static void main(String[] args) {
int[][][] cube = {
{
{1, 2, 3},
{4, 5, 6}
},
{
{7, 8, 9},
{10, 11, 12}
}
};

int element = cube[1][0][2];


[Link]("Element at (1, 0, 2): " + element);
}
}

OUTPUT:
Element at (1, 2): 6
Element at (1, 0, 2): 9
13. Write a java code to explain single and mulƟple
inheritance .

// single inheritance
class Parent {
void display() {
[Link]("This is the parent class.");
}
}

class Child extends Parent {


void show() {
[Link]("This is the child class.");
}
}

public class SingleInheritanceExample {


public static void main(String[] args) {
Child child = new Child();
[Link](); // Inherited from Parent
[Link](); // Defined in Child
}
}

// multiple inheritance (Using Interfaces)


interface A {
void methodA();
}
interface B {
void methodB();
}
class MyClass implements A, B {
public void methodA() {
[Link]("Method A implementation.");
}

public void methodB() {


[Link]("Method B implementation.");
}
}

public class MultipleInheritanceExample {


public static void main(String[] args) {
MyClass obj = new MyClass();
[Link](); // Implemented from interface A
[Link](); // Implemented from interface B
}
}

OUTPUT:
This is the parent class.
This is the child class.
Method A implementation.
Method B implementation.
14. Write a program of exception handeling (try catch
throw) .

public class ArithmeticExceptionExample {


public static void main(String[] args) {
try {
int result = 10 / 0; // Attempt to divide by zero
} catch (ArithmeticException ex) {
[Link]("An ArithmeticException occurred: " +
[Link]());
}
}
}

OUTPUT:
An ArithmeticException occurred : [Link]: / by
zero
15. Write a program of Method overriding .
class Animal {
void makeSound() {
[Link]("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void makeSound() {
[Link]("Dog barks");
}
}

public class MethodOverridingExample {


public static void main(String[] args) {
Animal animal = new Animal();
Animal dog = new Dog();
[Link]();
[Link]();
}
}

OUTPUT:
Animal makes a sound
Dog barks

Common questions

Powered by AI

In Java, to find the second largest number without using arrays, initialize two variables, `largest` and `secondLargest`, to hold the maximum and second maximum numbers found. Using a loop, read each input number. Update `largest` and `secondLargest` based on comparisons with the current input. If the input is greater than `largest`, update `secondLargest` with the value of `largest`, and `largest` with the new input. Cease input upon receiving -1 and print the second largest number unless no suitable second value was determined.

In Java, method overriding occurs when a subclass provides a specific implementation for a method declared in its superclass. This is achieved by defining a method in the subclass with the same name and parameter list as the superclass method and using the `@Override` annotation. It allows polymorphism, enabling method calls to resolve dynamically based on the object type at runtime. Applications include implementing specific behaviors in subclasses while maintaining a common interface, such as different animal sounds from a general `Animal` class.

A Java program can utilize various control statements like `if`, `switch`, and loops (`while` and `for`). For example, an `if` statement determines the positivity, negativity, or neutrality of a number, while a `switch` handles multi-way branching for fixed options like days of the week. A `while` loop shows counts down from a given positive number, and a `for` loop displays a multiplication table for the input number. This versatility allows the program to handle a variety of decisions and iterations, demonstrating crucial aspects of procedural logic and control flow in Java.

To find distinct elements in a sorted sequence, iterate through the numbers while maintaining a count of unique elements by comparing each number to the previous one (`prev`). Increment the distinct count only when the current number differs from `prev`. This works efficiently in sorted sequences because duplicates are adjacent, ensuring each transition signifies a distinct element, thereby minimizing the comparisons needed.

Logical operators like `&&` are used for conditional statements evaluating boolean expressions; the `&&` operator short-circuits, stopping evaluation once false is determined. Bitwise operators like `&` operate at the binary level on individual bits regardless of the overall expression outcome, suitable for low-level binary manipulations. For instance, `true && false` evaluates to false without further checks, while `10 & 5` computes bitwise and, yielding 0, representing unique applications in conditional checks and bit manipulations in data-processing scenarios.

Java achieves multiple inheritance via interfaces, allowing a class to implement multiple interfaces. An example involves defining interfaces `A` and `B`, each with a method declaration. A class `MyClass` implements both interfaces, providing concrete implementations of the specified methods. Thus, `MyClass` inherits behavior from multiple sources, unlike traditional class inheritance that permits only single inheritance due to the diamond problem. The design ensures that Java maintains simplicity and avoids ambiguity by enforcing explicit method implementation in the subclass.

Java can output distinct elements from a user-entered sorted sequence using a simple linear traversal and a single `prev` variable to track the last encountered distinct number. Increment a counter each time the current number differs from `prev`, denoting the emergence of a distinct element, while `prev` is updated to match the current number. This method avoids extra storage structures by directly leveraging sorted order properties, efficiently counting unique numbers through comparison.

Handling arithmetic exceptions in Java involves using try-catch blocks. Enclose code that might generate an exception, such as division by zero, within a 'try' block. Catch the specific `ArithmeticException` in the 'catch' block, allowing you to gracefully manage the error, such as logging or informing the user. Example: Attempt to divide by zero within a `try` block, catch the exception, and provide a meaningful message to the user. This ensures program stability by preventing crashes due to unhandled exceptions.

To write a Java program to find the Kth odd number in a sequence given by the user without using an array, use a `Scanner` to read the input string containing the numbers. Loop through each number, checking if it's odd by checking `number % 2 != 0`. Increment a count for each odd number found during the loop. Compare the count to K to identify the Kth odd number. If identified, break out of the loop and print the number; otherwise, indicate that less than K odd numbers exist in the input.

A 2D array in Java is declared as `int[][] array`, where each subarray represents a row. Access elements using `array[row][column]` syntax. Similarly, a 3D array is declared as `int[][][] array`, viewed as arrays of 2D arrays, accessed via `array[depth][row][column]`. For example, accessing `array[1][2]` in a 2D array and `cube[1][0][2]` in a 3D array retrieve specific sub-elements. This structure enables multidimensional data representation needed in complex application scenarios like matrices and simulations.

You might also like