Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
41 views

Java Programs XII 802

Uploaded by

rohandora854
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)
41 views

Java Programs XII 802

Uploaded by

rohandora854
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/ 25

Java Practice Programs

1. Write a program to find the sum of two numbers.


2. Program to check whether a number is prime.
3. Generate the Fibonacci series up to a given number.
4. Find the largest number in an array.
5. Implement a binary search algorithm.
6. Sort an array using bubble sort.
7. Write a program to check whether a string is a palindrome.
8. Count the number of vowels and consonants in a string.
9. Program to calculate the factorial of a number.
10. Implement a simple calculator using switch-case.
11. Write a program to reverse a string.
12. Find the GCD and LCM of two numbers.
13. Program to check whether a year is a leap year.
14. Write a program to find the sum of digits of a number.
15. Implement a program to swap two numbers without using a third variable.
16. Find the second largest number in an array.
17. Program to remove duplicate elements from an array.
18. Write a program to merge two arrays.
19. Implement matrix addition and subtraction.
20. Find the transpose of a matrix.
21. Check whether a matrix is symmetric.
22. Implement selection sort in Java.
23. Write a program to perform linear search.
24. Program to check if two strings are anagrams.
25. Write a program to find the frequency of characters in a string.
26. Convert a decimal number to binary.
27. Program to check if a number is an Armstrong number.
28. Implement a method to calculate the area of a rectangle.
29. Write a program to calculate the average of numbers in an array.
30. Find the sum of elements in an array.
31. Check whether a given number is positive, negative, or zero.
32. Implement a program to demonstrate inheritance.
33. Write a program to demonstrate polymorphism.
34. Create a program to demonstrate the use of abstract classes.
35. Write a program to implement an interface.
36. Program to demonstrate method overloading.
37. Implement method overriding in Java.
38. Write a program to handle ArrayIndexOutOfBoundsException.
39. Program to demonstrate the use of try-catch blocks.
40. Write a program to read and write data to a file.
41. Implement a stack using arrays.
42. Implement a queue using arrays.
43. Write a program to demonstrate the concept of static methods.
44. Program to display current date and time.
45. Write a program to calculate the area of a circle using a method.
46. Program to find the length of a string without using built-in methods.
47. Write a program to implement recursion for calculating factorial.
48. Program to create a thread by implementing the Runnable interface.
49. Demonstrate the use of the “this” keyword in Java.
50. Write a program to sort names in alphabetical order.
1. Find the sum of two numbers
import java.util.Scanner;

public class SumOfTwoNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
System.out.println(a + b);
}
}

2. Check whether a number is prime


import java.util.Scanner;

public class PrimeCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
boolean isPrime = true;
if (n <= 1) isPrime = false;
for (int i = 2; i <= Math.sqrt(n); i++) {
if (n % i == 0) {
isPrime = false;
break;
}
}
System.out.println(isPrime ? "Prime" : "Not Prime");
}
}

3. Generate the Fibonacci series up to a given number


import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int a = 0, b = 1;
while (a <= n) {
System.out.print(a + " ");
int next = a + b;
a = b;
b = next;
}
}
}

4. Find the largest number in an array


import java.util.Scanner;

public class LargestNumberInArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = scanner.nextInt();
int max = arr[0];
for (int num : arr) if (num > max) max = num;
System.out.println(max);
}
}

5. Implement a binary search algorithm


import java.util.Arrays;
import java.util.Scanner;

public class BinarySearch {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = scanner.nextInt();
Arrays.sort(arr);
int key = scanner.nextInt();
int left = 0, right = n - 1, mid, result = -1;
while (left <= right) {
mid = (left + right) / 2;
if (arr[mid] == key) {
result = mid;
break;
} else if (arr[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
System.out.println(result == -1 ? "Not Found" : "Found at index " + result);
}
}

6. Sort an array using bubble sort


import java.util.Scanner;

public class BubbleSort {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = scanner.nextInt();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int num : arr) System.out.print(num + " ");
}
}

7. Check whether a string is a palindrome


import java.util.Scanner;

public class PalindromeCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(str.equals(reversed) ? "Palindrome" : "Not Palindrome");
}
}

8. Count the number of vowels and consonants in a string


import java.util.Scanner;
public class VowelConsonantCount {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
int vowels = 0, consonants = 0;
for (char c : str.toCharArray()) {
if (Character.isLetter(c)) {
if ("AEIOUaeiou".indexOf(c) != -1) vowels++;
else consonants++;
}
}
System.out.println("Vowels: " + vowels + ", Consonants: " + consonants);
}
}

9. Calculate the factorial of a number


import java.util.Scanner;

public class Factorial {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int factorial = 1;
for (int i = 1; i <= n; i++) factorial *= i;
System.out.println(factorial);
}
}

10. Implement a simple calculator using switch-case


import java.util.Scanner;

public class SimpleCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double a = scanner.nextDouble();
double b = scanner.nextDouble();
char operator = scanner.next().charAt(0);
double result = 0;
switch (operator) {
case '+' -> result = a + b;
case '-' -> result = a - b;
case '*' -> result = a * b;
case '/' -> result = a / b;
}
System.out.println(result);
}
}

11. Reverse a string


import java.util.Scanner;

public class ReverseString {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed);
}
}

12. Find the GCD and LCM of two numbers


import java.util.Scanner;

public class GCDAndLCM {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int gcd = 1, lcm;
for (int i = 1; i <= Math.min(a, b); i++) {
if (a % i == 0 && b % i == 0) gcd = i;
}
lcm = a * b / gcd;
System.out.println("GCD: " + gcd + ", LCM: " + lcm);
}
}

13. Check whether a year is a leap year


import java.util.Scanner;

public class LeapYearCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int year = scanner.nextInt();
boolean isLeap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
System.out.println(isLeap ? "Leap Year" : "Not a Leap Year");
}
}

14. Find the sum of digits of a number


import java.util.Scanner;

public class SumOfDigits {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
int sum = 0;
while (number != 0) {
sum += number % 10;
number /= 10;
}
System.out.println(sum);
}
}

15. Swap two numbers without using a third variable


import java.util.Scanner;

public class SwapNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
a = a + b;
b = a - b;
a = a - b;
System.out.println("a: " + a + ", b: " + b);
}
}

16. Find the second largest number in an array


import java.util.Scanner;

public class SecondLargestInArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = scanner.nextInt();
int largest = Integer.MIN_VALUE, secondLargest = Integer.MIN_VALUE;
for (int num : arr) {
if (num > largest) {
secondLargest = largest;
largest = num;
} else if (num > secondLargest && num != largest) {
secondLargest = num;
}
}
System.out.println(secondLargest);
}
}

17. Remove duplicate elements from an array


import java.util.Scanner;
import java.util.HashSet;

public class RemoveDuplicates {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = scanner.nextInt();
HashSet<Integer> set = new HashSet<>();
for (int num : arr) set.add(num);
for (int num : set) System.out.print(num + " ");
}
}

18. Merge two arrays


import java.util.Scanner;

public class MergeTwoArrays {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n1 = scanner.nextInt();
int[] arr1 = new int[n1];
for (int i = 0; i < n1; i++) arr1[i] = scanner.nextInt();
int n2 = scanner.nextInt();
int[] arr2 = new int[n2];
for (int i = 0; i < n2; i++) arr2[i] = scanner.nextInt();
int[] merged = new int[n1 + n2];
System.arraycopy(arr1, 0, merged, 0, n1);
System.arraycopy(arr2, 0, merged, n1, n2);
for (int num : merged) System.out.print(num + " ");
}
}

19. Implement matrix addition and subtraction


import java.util.Scanner;

public class MatrixAdditionSubtraction {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] a = new int[rows][cols];
int[][] b = new int[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
a[i][j] = scanner.nextInt();
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
b[i][j] = scanner.nextInt();
int[][] sum = new int[rows][cols];
int[][] diff = new int[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++) {
sum[i][j] = a[i][j] + b[i][j];
diff[i][j] = a[i][j] - b[i][j];
}
System.out.println("Sum:");
for (int[] row : sum) {
for (int val : row) System.out.print(val + " ");
System.out.println();
}
System.out.println("Difference:");
for (int[] row : diff) {
for (int val : row) System.out.print(val + " ");
System.out.println();
}
}
}
20. Find the transpose of a matrix
import java.util.Scanner;

public class MatrixTranspose {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int rows = scanner.nextInt();
int cols = scanner.nextInt();
int[][] matrix = new int[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
matrix[i][j] = scanner.nextInt();
int[][] transpose = new int[cols][rows];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
transpose[j][i] = matrix[i][j];
for (int[] row : transpose) {
for (int val : row) System.out.print(val + " ");
System.out.println();
}
}
}

21. Check whether a matrix is symmetric


import java.util.Scanner;

public class MatrixSymmetryCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[][] matrix = new int[n][n];
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
matrix[i][j] = scanner.nextInt();
boolean isSymmetric = true;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++) {
if (matrix[i][j] != matrix[j][i]) {
isSymmetric = false;
break;
}
}
System.out.println(isSymmetric ? "Symmetric" : "Not Symmetric");
}
}

22. Implement selection sort in Java


import java.util.Scanner;

public class SelectionSort {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = scanner.nextInt();
for (int i = 0; i < n - 1; i++) {
int minIdx = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIdx]) minIdx = j;
}
int temp = arr[minIdx];
arr[minIdx] = arr[i];
arr[i] = temp;
}
for (int num : arr) System.out.print(num + " ");
}
}

23. Perform linear search


import java.util.Scanner;

public class LinearSearch {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) arr[i] = scanner.nextInt();
int key = scanner.nextInt();
int index = -1;
for (int i = 0; i < n; i++) {
if (arr[i] == key) {
index = i;
break;
}
}
System.out.println(index == -1 ? "Not Found" : "Found at index " + index);
}
}

24. Check if two strings are anagrams


import java.util.Arrays;
import java.util.Scanner;

public class AnagramCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str1 = scanner.nextLine();
String str2 = scanner.nextLine();
boolean isAnagram = Arrays.equals(str1.toCharArray(), str2.toCharArray());
System.out.println(isAnagram ? "Anagram" : "Not Anagram");
}
}
25. Find the frequency of characters in a string
import java.util.Scanner;
import java.util.HashMap;

public class CharacterFrequency {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
HashMap<Character, Integer> freqMap = new HashMap<>();
for (char c : str.toCharArray()) {
freqMap.put(c, freqMap.getOrDefault(c, 0) + 1);
}
for (var entry : freqMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}

26. Convert a decimal number to binary


import java.util.Scanner;

public class DecimalToBinary {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
StringBuilder binary = new StringBuilder();
while (number > 0) {
binary.insert(0, number % 2);
number /= 2;
}
System.out.println(binary);
}
}

27. Check if a number is an Armstrong number


import java.util.Scanner;

public class ArmstrongNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
int sum = 0, original = num;
while (num > 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
System.out.println(original == sum ? "Armstrong" : "Not Armstrong");
}
}

28. Calculate the area of a rectangle


import java.util.Scanner;

public class AreaOfRectangle {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double length = scanner.nextDouble();
double width = scanner.nextDouble();
System.out.println(length * width);
}
}

29. Calculate the average of numbers in an array


import java.util.Scanner;

public class AverageOfArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
double sum = 0;
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
sum += arr[i];
}
System.out.println(sum / n);
}
}

30. Find the sum of elements in an array


import java.util.Scanner;

public class SumOfArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int[] arr = new int[n];
int sum = 0;
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
sum += arr[i];
}
System.out.println(sum);
}
}

31. Check if a number is positive, negative, or zero


import java.util.Scanner;

public class NumberCheck {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
if (number > 0) System.out.println("Positive");
else if (number < 0) System.out.println("Negative");
else System.out.println("Zero");
}
}

32. Demonstrate inheritance


class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}

public class InheritanceDemo {


public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
}
}

33. Demonstrate polymorphism


class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Cat extends Animal {


void sound() {
System.out.println("Cat meows");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}

public class PolymorphismDemo {


public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();
myDog.sound();
myCat.sound();
}
}

34. Demonstrate the use of abstract classes


abstract class Shape {
abstract void draw();
}

class Circle extends Shape {


void draw() {
System.out.println("Drawing Circle");
}
}

public class AbstractClassDemo {


public static void main(String[] args) {
Circle circle = new Circle();
circle.draw();
}
}

35. Implement an interface


interface Drawable {
void draw();
}

class Rectangle implements Drawable {


public void draw() {
System.out.println("Drawing Rectangle");
}
}

public class InterfaceDemo {


public static void main(String[] args) {
Drawable rect = new Rectangle();
rect.draw();
}
}

36. Demonstrate method overloading


class Overload {
void display(int a) {
System.out.println("Integer: " + a);
}

void display(String b) {
System.out.println("String: " + b);
}
}

public class MethodOverloadingDemo {


public static void main(String[] args) {
Overload obj = new Overload();
obj.display(10);
obj.display("Hello");
}
}
37. Implement method overriding in Java
class Parent {
void show() {
System.out.println("Parent class");
}
}

class Child extends Parent {


void show() {
System.out.println("Child class");
}
}

public class MethodOverridingDemo {


public static void main(String[] args) {
Parent obj = new Child();
obj.show();
}
}

38. Handle ArrayIndexOutOfBoundsException


import java.util.Scanner;

public class ArrayExceptionHandling {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] arr = new int[5];
try {
for (int i = 0; i <= 5; i++) {
arr[i] = i;
}
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds");
}
}
}

39. Demonstrate the use of try-catch blocks


import java.util.Scanner;

public class TryCatchDemo {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
int number = scanner.nextInt();
System.out.println("You entered: " + number);
} catch (Exception e) {
System.out.println("Invalid input");
}
}
}

40. Read and write data to a file


import java.io.*;

public class FileReadWrite {


public static void main(String[] args) {
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("data.txt"));
writer.write("Hello, World!");
writer.close();

BufferedReader reader = new BufferedReader(new FileReader("data.txt"));


System.out.println(reader.readLine());
reader.close();
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
}
}

41. Implement a stack using arrays


class Stack {
int[] arr;
int top;
int capacity;

Stack(int size) {
arr = new int[size];
capacity = size;
top = -1;
}

void push(int x) {
if (top == capacity - 1) {
System.out.println("Stack Overflow");
return;
}
arr[++top] = x;
}

void pop() {
if (top == -1) {
System.out.println("Stack Underflow");
return;
}
top--;
}

int peek() {
return arr[top];
}
}

public class StackDemo {


public static void main(String[] args) {
Stack stack = new Stack(5);
stack.push(1);
stack.push(2);
System.out.println(stack.peek());
stack.pop();
System.out.println(stack.peek());
}
}

42. Implement a queue using arrays


class Queue {
int[] arr;
int front, rear, capacity;

Queue(int size) {
arr = new int[size];
capacity = size;
front = rear = 0;
}

void enqueue(int x) {
if (rear == capacity) {
System.out.println("Queue Overflow");
return;
}
arr[rear++] = x;
}

void dequeue() {
if (front == rear) {
System.out.println("Queue Underflow");
return;
}
front++;
}

int peek() {
return arr[front];
}
}

public class QueueDemo {


public static void main(String[] args) {
Queue queue = new Queue(5);
queue.enqueue(1);
queue.enqueue(2);
System.out.println(queue.peek());
queue.dequeue();
System.out.println(queue.peek());
}
}

43. Demonstrate the concept of static methods


class StaticDemo {
static int count = 0;

static void increment() {


count++;
}

static void display() {


System.out.println(count);
}
}

public class StaticMethodDemo {


public static void main(String[] args) {
StaticDemo.increment();
StaticDemo.increment();
StaticDemo.display();
}
}

44. Display current date and time


import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class DisplayDateTime {


public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(now.format(formatter));
}
}

45. Calculate the area of a circle using a method


java
import java.util.Scanner;

public class AreaOfCircle {


static double calculateArea(double radius) {
return Math.PI * radius * radius;
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
double radius = scanner.nextDouble();
System.out.println(calculateArea(radius));
}
}

46. Find the length of a string without using built-in methods


import java.util.Scanner;

public class LengthWithoutBuiltIn {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
int length = 0;
for (char c : str.toCharArray()) length++;
System.out.println(length);
}
}

47. Implement recursion for calculating factorial


import java.util.Scanner;

public class RecursiveFactorial {


static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
int number = scanner.nextInt();
System.out.println(factorial(number));
}
}

48. Create a thread by implementing the Runnable interface


class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running");
}
}

public class ThreadDemo {


public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}

49. Demonstrate the use of the “this” keyword in Java


class MyClass {
int value;

MyClass(int value) {
this.value = value;
}
void display() {
System.out.println(value);
}
}

public class ThisKeywordDemo {


public static void main(String[] args) {
MyClass obj = new MyClass(5);
obj.display();
}
}

50. Sort names in alphabetical order


import java.util.Arrays;
import java.util.Scanner;

public class SortNames {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
String[] names = new String[n];
scanner.nextLine();
for (int i = 0; i < n; i++) names[i] = scanner.nextLine();
Arrays.sort(names);
for (String name : names) System.out.println(name);
}
}

You might also like