Basic Programming Construct





1 :- Write a java program to print 'Hello World!' on Screen.

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

Output :-

javac fun.java
java one
Hello World




2 :- Write a java program to print the sum of two numbers

class sum
{
public static void main(String args[])
{
int num1 = 10;
int num2 = 50;
int sum;
sum = num1 + num2;
System.out.println("The First number: "+num1);
System.out.println("The Second number: "+num2);
System.out.println("Sum of two Numbers : "+sum);
}
}

Output :-

javac fun.java
java sum
The First number: 10
The Second number: 50
Sum of two Numbers : 60





3 :- Write a java program that takes two numbers and display the product of two number

import java.util.Scanner;
class NumbersProduct{
void Product(){
int num1, num2, product;
System.out.print("Enter first number : ");
Scanner scan = new Scanner(System.in);
num1 = scan.nextInt();
System.out.print("Enter second number : ");
num2 = scan.nextInt();
product = num1 * num2;
System.out.println("Product of two number is : " + product);
}
public static void main(String args[]){
NumbersProduct obj = new NumbersProduct();
obj.Product();
}
}

Output :-

javac fun.java
java NumbersProduct
Enter first number : 5
Enter second number : 4
Product of two number is : 20





4 :- Write a program to print the sum, multiply, subtract, divide and remainderof two numbers

import java.util.Scanner;
class NumbersProduct{
void Product(){
int num1, num2, product;
System.out.print("Enter first number : ");
Scanner scan = new Scanner(System.in);
num1 = scan.nextInt();
System.out.print("Enter second number : ");
num2 = scan.nextInt();
product = num1 * num2;
System.out.println("Product of two number is : " + product);
}
public static void main(String args[]){
NumbersProduct obj = new NumbersProduct();
obj.Product();
}
}

Output :-

javac fun.java
java NumbersProduct
Enter first number : 5
Enter second number : 4
Product of two number is : 20





5 :- Write a java program that takes five number as input to calculate and print the average of the numbers

import java.util.Scanner;
class NumbersAverage
{
void average()
{
int num, sum=0, i, average;
System.out.println("Program to calculate average of five numbers");
Scanner scan = new Scanner(System.in);
for(i=1; i<=5; i++){ System.out.print("Enter number " + i + " : ");
num = scan.nextInt();
sum += num;
}
average = sum/5;
System.out.println(" Average of Five Numbers is : " + average);
}
public static void main(String args[]){
NumbersAverage obj = new NumbersAverage();
obj.average();
}
}

Output :-

javac fun.java
java NumbersAverage
Program to calculate average of five numbers
Enter number 1 : 1
Enter number 2 : 2
Enter number 3 : 3
Enter number 4 : 4
Enter number 5 : 5
Average of Five Numbers is : 3





6 :- Write a Java program to swap two variables.

class Swap
{
void swap()
{
int num1 = 10;
int num2 = 20;
int temp;
System.out.println(" ");
System.out.println("Program to SWAP TWO NUMBERS");
System.out.println(" ");
System.out.println("Before Swapping first number is : " + num1);
System.out.println("Before Swapping Second number is : " + num2);
System.out.println(" ");
temp = num1;
num1 = num2;
num2 = temp;
System.out.println("After Swapping first number is : " + num1);
System.out.println("After Swapping Second number is : " + num2);
}
public static void main(String args[]){
Swap s = new Swap();
s.swap();
}
}

Output :-

javac fun.java

java Swap

Program to SWAP TWO NUMBERS

Before Swapping first number is : 10
Before Swapping Second number is : 20

After Swapping first number is : 20
After Swapping Second number is : 10





7 :- Write a Java program to convert a decimal number to binary numbers

import java.util.Scanner;
class DecimaltoB
{
String decimalToBinary(int decimalNumber)
{
if(decimalNumber == 0)
{
return "0";
}
StringBuilder binary = new StringBuilder();
while(decimalNumber > 0)
{
int rem = decimalNumber % 2;
binary.insert(0, rem);
decimalNumber/=2;
}
return binary.toString();
}
void dec2bin()
{
int num;
System.out.println(" ");
System.out.println("Program to convert decimal number to binary number");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a decimal number : ");
num = scan.nextInt();
String binary = decimalToBinary(num);
System.out.println("Binary Representation of number is : " + binary);
}
public static void main(String args[]){
DecimaltoB d = new DecimaltoB();
d.dec2bin();
}
}

Output :-

javac fun.java

java DecimaltoB

Program to convert decimal number to binary number
Enter a decimal number : 10
Binary Representation of number is : 1010





8 :- Write a Java program to convert a binary number to decimal number

import java.util.Scanner;
class BinaryToD
{
int binaryToDecimal(String binaryString)
{
int decimal = 0;
int binaryLength = binaryString.length();
for(int i = 0; i < binaryLength; i++){ char binaryDigit=binaryString.charAt(i); if
(binaryDigit !='0' &&
binaryDigit !='1' ) { System.out.println("Invalid Binary Input !!"); return -1; } int
power=binaryLength - 1 - i; int digit=binaryDigit=='1' ? 1 : 0; decimal +=digit *
Math.pow(2, power); } return decimal; } void binaryToDecimal() { System.out.println(" ");
System.out.println(" Program to convert binary number to decimal number");
Scanner scan=new Scanner(System.in); System.out.print("Enter a binary number : ");
String binaryString = scan.nextLine();
int decimal = binaryToDecimal(binaryString);
if(decimal != -1){
System.out.println(" Decimal Number is : " + decimal);
} }
public static void main(String args[])
{
BinaryToD b = new BinaryToD();
b.binaryToDecimal();
}
}

Output :-

javac fun.java

java BinaryToD

Program to convert binary number to decimal number
Enter a binary number : 1010
Decimal Number is : 10





9 :- Write a Java program to check whether Java is installed on your computer or not

class checkjavainstall
{
public static void main(String args[])
{
String javaVersion = System.getProperty("java.version");
if(javaVersion != null)
{
System.out.println(" ");
System.out.println("Java is installed, version : " + javaVersion);
}
else{
System.out.println("Java is not installed on your computer !!");
}
}
}

Output :-

javac fun.java

java checkjavainstall

Java is installed, version : 1.6.0_45





10 :- Write a Java program and compute the sum of the digits of an integer

import java.util.Scanner;
class SumOfD
{
void CalSum()
{
int num, sum = 0;
Scanner s = new Scanner(System.in);
System.out.println(" ");
System.out.println("Program to find sum of digits of a integer");
System.out.print("Enter a number : ");
num = s.nextInt();
int temp = num;
while(temp != 0)
{
int digit = temp % 10;
sum += digit;
temp /= 10;
}
System.out.println("Sum of Digits : " + sum);
}
public static void main(String args[]){
SumOfD obj = new SumOfD();
obj.CalSum();
}
}

Output :-

javac fun.java

java SumOfD

Program to find sum of digits of a integer
Enter a number : 12345
Sum of Digits : 15





11 :- Write a Java program to compare two numbers

import java.util.Scanner;
class CompareToN
{
void compareValue()
{ int num1, num2;
System.out.println(" ");
System.out.println("Program to compare two numbers");
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number : ");
num1 = scan.nextInt();
System.out.print("Enter second number : ");
num2 = scan.nextInt();
if(num1 == num2){
System.out.println("Both numbers are equal");
}
else{
System.out.println("Numbers are not equal");
}
}
public static void main(String args[]){
CompareToN c = new CompareToN();
c.compareValue();
}
}

Output :-

javac fun.java

java CompareToN

Program to compare two numbers
Enter first number : 10
Enter second number : 5
Numbers are not equal





12 :- Write a Java program to count the letters, spaces, numbers and other characters of an input string

import java.util.Scanner;
class CountCharacter
{
void Count()
{
String text;
int countLetters = 0;
int countSpaces = 0;
int countNumbers = 0;
int countCharacters = 0;
System.out.println(" ");
System.out.println("Program to count letter, spaces, numbers, characters in text");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string : ");
text = scan.nextLine();
for(char arr : text.toCharArray())
{
if(Character.isLetter(arr))
{
countLetters++;
}
else if(Character.isDigit(arr))
{
countNumbers++;
}
else if(Character.isWhitespace(arr))
{
countSpaces++;
}
else
{
countCharacters++;
}
}
System.out.println(" ");
System.out.println("Total Letters : " + countLetters);
System.out.println("Total Numbers : " + countNumbers);
System.out.println("Total Spaces : " + countSpaces);
System.out.println("Total Characters : " + countCharacters);
}
public static void main(String args[]){
CountCharacter c = new CountCharacter();
c.Count();
}
}

Output :-

javac fun.java

java CountCharacter

Program to count letter, spaces, numbers, characters in text
Enter a string : abcdfr@ 123 456

Total Letters : 6
Total Numbers : 6
Total Spaces : 2
Total Characters : 1





13 :- Write a Java program to print the ascii value of a given character

import java.util.Scanner;
class AsciiValue
{
void ascivalue()
{
System.out.println(" ");
System.out.println("Program to print Ascii value of a character");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a character : ");
char ch = scan.next().charAt(0);
int AsciiValue = (int)ch;
System.out.println("Ascii Value of " + ch + " is : " + AsciiValue);
}
public static void main(String args[]){
AsciiValue a = new AsciiValue();
a.ascivalue();
}
}

Output :-

javac fun.java

java CountCharacter

Program to count letter, spaces, numbers, characters in text
Enter a string : abcdfr@ 123 456

Total Letters : 6
Total Numbers : 6
Total Spaces : 2
Total Characters : 1





14 :- Write a Java program that accepts an integer (n) and computes the value of n+nn+nnn

import java.util.Scanner;
class sumofnnn
{
public static void main(String args[])
{
int n;
Scanner scan = new Scanner(System.in);
System.out.println(" ");
System.out.println("Program to compute value of n+nn+nnn");
System.out.print("Enter an integer : ");
n = scan.nextInt();
int nn = n * 10 + n; //110
int nnn = n * 100 + nn;//1110
int result = n + nn + nnn;
System.out.println("Sum n + nn + nnn is : " + result);
}
}

Output :-

javac fun.java

java sumofnnn

Program to compute value of n+nn+nnn
Enter an integer : 11
Sum n + nn + nnn is : 1353





15 :- Write a Java program to display the system time

import java.util.Date;
import java.text.SimpleDateFormat;
class SystemTime
{
public static void main(String args[])
{
Date currentDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String formattedDate = dateFormat.format(currentDate);
System.out.println(" ");
System.out.println("Current System Time is : " + formattedDate);
}
}

Output :-

javac fun.java

java SystemTime

Current System Time is : 2023-11-15 12:02:23




16 :- Write a Java program to print the odd numbers from 1 to 20

class OddN
{
public static void main(String args[])
{
System.out.println(" ");
System.out.println("Program to Print Odd Numbers between 1 to 20");
int i;
for(i = 1; i <=20; i++) { if(i % 2==0) { continue; } else { System.out.println("Odd Number is : " + i);
}
}
} }

Output :-

javac fun.java

java OddN

Program to Print Odd Numbers between 1 to 20
Odd Number is : 1
Odd Number is : 3
Odd Number is : 5
Odd Number is : 7
Odd Number is : 9
Odd Number is : 11
Odd Number is : 13
Odd Number is : 15
Odd Number is : 17
Odd Number is : 19




17 :- Write a Java program to print the even numbers from 1 to 20

class EvenN
{
public static void main(String args[])
{
System.out.println(" ");
System.out.println("Program to Print Even Numbers between 1 to 20");
int i;
for(i = 1; i <=20; i++) { if(i % 2==0) { System.out.println("Even Number is : " + i);
}
else
{
continue;
}
}
}
}

Output :-

javac fun.java

java EvenN

Program to Print Even Numbers between 1 to 20
Even Number is : 2
Even Number is : 4
Even Number is : 6 Even Number is : 8
Even Number is : 10
Even Number is : 12
Even Number is : 14
Even Number is : 16
Even Number is : 18
Even Number is : 20




18 :- Write a Java program to convert a string to an integer

class convertSToI
{
public static void main(String args[])
{
System.out.println(" ");
System.out.println("Program to convert string to integer");
String string1 = "10", string2 = "10";
System.out.println("First String is : " + string1);
System.out.println("Second String is : " + string2);
System.out.println("Before conversion sum of string is : " + string1 + string2);
int num1 = Integer.valueOf(string1);
int num2 = Integer.valueOf(string2);
System.out.println("After conversion sum of variables is : " + (num1 + num2));
}
}

Output :-

javac fun.java

java convertSToI

Program to convert string to integer
First String is : 10
Second String is : 10
Before conversion sum of string is : 1010
After conversion sum of variables is : 20




19 :- Write a Java program to convert seconds to hour, minute and seconds

import java.util.Scanner;
import java.util.Date;
class convertSToM
{
void TakeSeconds()
{
int num, hours, minutes, seconds;
System.out.println(" ");
System.out.println("Program to convert seconds to hours, minutes, seconds");
Scanner scan = new Scanner(System.in);
System.out.print("Enter value of seconds : ");
num = scan.nextInt();
hours = num/3600;
minutes = (num - (3600 * hours)) / 60;
seconds = (num - (3600 * hours) - (minutes * 60));
System.out.println("Hours : " + hours + "\nMinutes : " + minutes + "\nSeconds : " + seconds);
}
public static void main(String args[])
{
convertSToM c = new convertSToM();
c.TakeSeconds();
}
}

Output :-

javac fun.java

java convertSToM

Program to convert seconds to hours, minutes, seconds
Enter value of seconds : 3600
Hours : 1
Minutes : 0
Seconds : 0




20 :- Write a Java program to compute the sum of the first 100 prime numbers

class SumOfPrimeN
{
public static void main(String args[])
{
System.out.println("program to sum of the first 100 prime numbers");
int i, j, sum = 0;
for(i = 2; i <=100; i++) { boolean isPrime=true; for(j=2; j <=Math.sqrt(i); j++) { if(i % j==0) {
isPrime=false; break; } } if(isPrime) { sum +=i; System.out.println("Prime number is : " + i) ;
} }
System.out.println(" Sum of Prime numbers is : " + sum);
}
}

Output :-

j javac fun.java

java SumOfPrimeN
program to sum of the first 100 prime numbers
Prime number is : 2
Prime number is : 3
Prime number is : 5
Prime number is : 7
Prime number is : 11
Prime number is : 13
Prime number is : 17
Prime number is : 19
Prime number is : 23
Prime number is : 29
Prime number is : 31
Prime number is : 37
Prime number is : 41
Prime number is : 43
Prime number is : 47
Prime number is : 53
Prime number is : 59
Prime number is : 61
Prime number is : 67
Prime number is : 71
Prime number is : 73
Prime number is : 79
Prime number is : 83
Prime number is : 89
Prime number is : 97
Sum of Prime numbers is : 1060




21 :- Write a Java program to swap the first and last elements of an array and create a new array

import java.util.Arrays;
class SwapArrayE
{
void SwapArray()
{
System.out.println(" ");
System.out.println("Program to swap first and last elements of an array and create a new array");
System.out.println(" ");
int[] arr = {35,60,10,20,30};
int[] newarr = new int[arr.length];
int temp, i;
System.out.println("Original Array : " + Arrays.toString(arr));
if(arr.length < 2) { System.out.println("Swapping is not possible"); } else { newarr[0]=arr[arr.length - 1]; for(i=1; i <=arr.length - 1; i++) { newarr[i]=arr[i]; } newarr[arr.length - 1]=arr[0];
System.out.println("Swapped Array : " + Arrays.toString(newarr));
}
}
public static void main(String args[])
{ SwapArrayE s = new SwapArrayE();
s.SwapArray();
}
}

Output :-

javac fun.java

java SwapArrayE

Program to swap first and last elements of an array and create a new array

Original Array : [35, 60, 10, 20, 30]
Swapped Array : [30, 60, 10, 20, 35]




22 :- Write a Java program to count the number of even and odd elements in a given array

import java.util.Arrays;
class CountOddEArr
{
void countElements()
{
int[] arr = {40,12,67,80,70,13,19};
int i, odd = 0, even = 0;
for(i = 0; i < arr.length; i++) { if(arr[i] % 2==0) { even++; } else { odd++; } } System.out.println(" ");
System.out.println(" program to count the number of even and odd elements in a given array");
System.out.println(" ");
System.out.println(" Elements of array : " + Arrays.toString(arr));
System.out.println(" Total Odd Elements in array : " + odd + " \nTotal Even Elements in array : " + even);
}
public static void main(String args[])
{
CountOddEArr c = new CountOddEArr();
c.countElements();
}
}

Output :-

javac fun.java

java CountOddEArr

program to count the number of even and odd elements in a given array

Elements of array : [40, 12, 67, 80, 70, 13, 19]
Total Odd Elements in array : 3
Total Even Elements in array : 4




23 :- Write a Java program to compute the square root of an given integer

import java.util.Scanner;
class CalSquareRI
{
void squareRoot()
{
int num, squareRoot;
System.out.println(" ");
System.out.println("Program to calculate Square Root of an integer");
System.out.println(" ");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number : ");
num = scan.nextInt();
squareRoot = num * num;
System.out.println("Square Root of " + num + " is : " + squareRoot);
}
public static void main(String args[])
{
CalSquareRI c = new CalSquareRI();
c.squareRoot();
}
}

Output :-

javac fun.java

java CalSquareRI

Program to calculate Square Root of an integer

Enter a number : 16
The square root of 16 is 4.0




24 :- Write a Java program to check if a positive number is a palindrome or not

import java.util.Scanner;
class CheckPositiveP
{
void checkPalindrome()
{
int num, rem, sum = 0, temp;
System.out.println(" ");
System.out.println("Program to check positive number palindrome number or not.");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number : ");
num = scan.nextInt();
temp = num;
while(num > 0)
{
rem = num % 10;
sum = (sum * 10) + rem;
num = num / 10;
}
if(temp == sum && temp % 2 == 0)
{
System.out.println("It is a Positive Palindrome Number");
}
else
{
System.out.println("It is not a Positive Palindrome Number");
}
}
public static void main(String args[])
{
CheckPositiveP c = new CheckPositiveP();
c. checkPalindrome();
}
}

Output :-

java Palindrome
Program to check positive number palindrome number or not.

Enter the number :- 12
12 is not a palindrome.

java Palindrome
Program to check positive number palindrome number or not.

Enter the number :- 121
121 is a palindrome.




25 :- Write a Java program to add two numbers without using any arithmetic operators

class SumWithoutA
{
void SumWithoutArithmetic()
{
int num1 = 20, num2 = 20 ;
System.out.println(" ");
System.out.println("program to add two numbers without using any arithmetic operators");
System.out.println("First number is : " + num1);
System.out.println("Second number is : " + num2);
while(num1 != 0)
{
int carry = (num1 & num2);
num2 = num2 ^ num1;
num1 = carry << 1; } System.out.println("Sum of two numbers is : " + num2);
}
public static void main(String args[])
{
SumWithoutA obj = new SumWithoutA();
obj.SumWithoutArithmetic();
}
}

Output :-

java Palindrome
Program to check positive number palindrome number or not.

Enter the number :- 12
12 is not a palindrome.

java Palindrome
Program to check positive number palindrome number or not.

Enter the number :- 121
121 is a palindrome.




26 :- Write a Java program to add all the digits of a given positive integer

class SumWithoutA
{
void SumWithoutArithmetic()
{
int num1 = 20, num2 = 20 ;
System.out.println(" ");
System.out.println("program to add two numbers without using any arithmetic operators");
System.out.println("First number is : " + num1);
System.out.println("Second number is : " + num2);
while(num1 != 0)
{
int carry = (num1 & num2);
num2 = num2 ^ num1;
num1 = carry << 1; } System.out.println("Sum of two numbers is : " + num2);
}
public static void main(String args[])
{
SumWithoutA obj = new SumWithoutA();
obj.SumWithoutArithmetic();
}
}

Output :-

javac fun.java

java PositiveIntegerDigits

program to add all the digits of a given positive integer
Enter a Number : 1234567
Sum of Digits : 28




27 :- Java program to find area of circle

import java.util.Scanner;
class AreaCircle
{
void CalcArea()
{
System.out.println(" ");
System.out.println("Program to calculate area of Circle");
double radius, area;
Scanner scan = new Scanner(System.in);
System.out.print("Enter radius value : ");
radius = scan.nextDouble();
area = Math.PI * Math.pow(radius, 2);
System.out.println("Area of Circle is : " + area);
}
public static void main(String args[])
{
AreaCircle obj = new AreaCircle();
obj.CalcArea();
}
}

Output :-

javac fun.java

java AreaCircle

Program to calculate area of Circle
Enter radius value : 3
Area of Circle is : 28.274333882308138




28 :- Java Program to find area of rectangle

import java.util.Scanner;
class AreaRectangle
{
void CalcArea()
{
double length, breadth, area;
System.out.println(" ");
System.out.println("Program to calculate area of Rectangle");
Scanner scan = new Scanner(System.in);
System.out.print("Enter length value : ");
length = scan.nextDouble();
System.out.print("Enter breadth value : ");
breadth = scan.nextDouble();
area = length * breadth;
System.out.println("Area of Rectangle is : " + area);
}
public static void main(String args[])
{
AreaRectangle obj = new AreaRectangle();
obj.CalcArea();
}
}

Output :-

javac fun.java

java AreaRectangle

Program to calculate area of Rectangle
Enter length value : 4
Enter breadth value : 5
Area of Rectangle is : 20.0




29 :- Java Program to find area of triangle

import java.util.Scanner;
class AreaTriangle
{
void CalcArea()
{
double base, height, area;
System.out.println(" ");
System.out.println("Program to calculate Area of Triangle");
Scanner scan = new Scanner(System.in);
System.out.print("Enter base value : ");
base = scan.nextDouble();
System.out.print("Enter height value : ");
height = scan.nextDouble();
area = (base * height) / 2;
System.out.println("Area of Triangle is : " + area);
}
public static void main(String args[])
{
AreaTriangle obj = new AreaTriangle();
obj.CalcArea();
}
}

Output :-

javac fun.java

java AreaTriangle

Program to calculate Area of Triangle
Enter base value : 20
Enter height value : 5
Area of Triangle is : 50.0




30 :- Java Program to find area of equilateral triangle

import java.util.Scanner;
class EquilateralTriangleArea
{
void CalcArea()
{
double side, area;
System.out.println(" ");
System.out.println("Program to calculate Area of Equilateral Triangle");
Scanner scan = new Scanner(System.in);
System.out.print("Enter value of side : ");
side = scan.nextDouble();
area = (Math.sqrt(3) / 4) * side * side;
System.out.println("Area of Equilateral Triangle is : " + area);
}
public static void main(String args[])
{
EquilateralTriangleArea obj = new EquilateralTriangleArea();
obj.CalcArea();
}
}

Output :-

javac fun.java

java EquilateralTriangleArea

Program to calculate Area of Equilateral Triangle
Enter value of side : 10
Area of Equilateral Triangle is : 43.301270189221924




31 :- Java Program to find area of rhombus

import java.util.Scanner;
class AreaRombus
{
void CalcArea()
{
double diagonal1, diagonal2, area;
System.out.println(" ");
System.out.println("Program to calculate Area of Rhombus");
Scanner scan = new Scanner(System.in);
System.out.print("Enter first diagonal value : ");
diagonal1 = scan.nextDouble();
System.out.print("Enter second diagonal value : ");
diagonal2 = scan.nextDouble();
area = (diagonal1 * diagonal2) / 2;
System.out.println("Area of Rhombus is : " + area);
}
public static void main(String args[]){
AreaRombus a = new AreaRombus();
a.CalcArea();
}
}

Output :-

javac fun.java

java AreaRombus

Program to calculate Area of Rhombus
Enter first diagonal value : 20
Enter second diagonal value : 10
Area of Rhombus is : 100.0




32 :- Java Program to find area of parallelogram

import java.util.Scanner;
class AreaParallogram
{
void CalcArea()
{
double base, height, area;
System.out.println(" ");
System.out.println("Program to calculate Area of Parallelogram");
Scanner scan = new Scanner(System.in);
System.out.print("Enter base value : ");
base = scan.nextDouble();
System.out.print("Enter height value : ");
height = scan.nextDouble();
area = base * height;
System.out.println("Area of Parallelogram is : " + area);
}
public static void main(String args[])
{
AreaParallogram a = new AreaParallogram();
a.CalcArea();
}
}

Output :-

javac fun.java

java AreaParallogram

Program to calculate Area of Parallelogram
Enter base value : 20
Enter height value : 4
Area of Parallelogram is : 80.0




33 :- Java Program to find area of Prism

import java.util.Scanner;
class PrismArea
{
void CalcArea()
{
double length, width, height, area;
System.out.println(" ");
System.out.println("Program to calculate Area of Prism");
Scanner scan = new Scanner(System.in);
System.out.print("Enter length value : ");
length = scan.nextDouble();
System.out.print("Enter width value : ");
width = scan.nextDouble();
System.out.print("Enter height value : ");
height = scan.nextDouble();
area = 2 * ((length * width) + (length * height) + (width * height));
System.out.println("Area of Prism is : " + area);
}
public static void main(String args[])
{
PrismArea obj = new PrismArea();
obj.CalcArea();
}
}

Output :-

javac fun.java

java PrismArea
Program to calculate Area of Prism
Enter length value : 20
Enter width value : 10
Enter height value : 10
Area of Prism is : 1000.0




34 :- Java Program to find volume of sphere

import java.util.Scanner;
class SphereVolume
{
void CalcVol()
{
double radius, volume;
System.out.println(" ");
System.out.println("Program to calculate Volume of Sphere");
Scanner scan = new Scanner(System.in);
System.out.print("Enter radius value : ");
radius = scan.nextDouble();
volume = (4.0 / 3.0) * Math.PI * Math.pow(radius, 3);
System.out.println("Volume of Sphere is : " + volume);
}
public static void main(String args[])
{
SphereVolume obj = new SphereVolume();
obj.CalcVol();
}
}

Output :-

javac fun.java

java SphereVolume

Program to calculate Volume of Sphere
Enter radius value : 5
Volume of Sphere is : 523.5987755982989




35 :- Java Program to find volume of cylinder

import java.util.Scanner;
class CylinderVolume
{
void CalcVol()
{
double radius, height, volume;
System.out.println(" ");
System.out.println("Program to calculate Volume of Cylinder");
Scanner scan = new Scanner(System.in);
System.out.print("Enter radius value : ");
radius = scan.nextDouble();
System.out.print("Enter height value : ");
height = scan.nextDouble();
volume = Math.PI * Math.pow(radius, 2) * height;
System.out.println("Volume of Cylinder is : " + volume);
}
public static void main(String args[])
{
CylinderVolume obj = new CylinderVolume();
obj.CalcVol();
}
}

Output :-

javac fun.java

java CylinderVolume

Program to calculate Volume of Cylinder
Enter radius value : 10
Enter height value : 20
Volume of Cylinder is : 6283.185307179587




36 :- Java Program to find volume of cuboid

import java.util.Scanner;
class CuboidVolume
{
void CalcVol()
{
double length, width, height, volume;
System.out.println(" ");
System.out.println("Program to calculate Volume of Cuboid");
Scanner scan = new Scanner(System.in);
System.out.print("Enter length value : ");
length = scan.nextDouble();
System.out.print("Enter width value : ");
width = scan.nextDouble();
System.out.print("Enter height value : ");
height = scan.nextDouble();
volume = length * width * height;
System.out.println("Volume of Cuboid is : " + volume);
}
public static void main(String args[])
{
CuboidVolume obj = new CuboidVolume();
obj.CalcVol();
}
}

Output :-

javac fun.java

java CuboidVolume

Program to calculate Volume of Cuboid
Enter length value : 10
Enter width value : 10
Enter height value : 10
Volume of Cuboid is : 1000.0




37 :- Java Program to find volume of cone

import java.util.Scanner;
class ConeVolume
{
void CalcVol()
{
double radius, height, volume;
System.out.println(" ");
System.out.println("Program to calculate Volume of Cone");
Scanner scan = new Scanner(System.in);
System.out.print("Enter radius value : ");
radius = scan.nextDouble();
System.out.print("Enter height value : ");
height = scan.nextDouble();
volume = (1.0 / 3.0) * Math.PI * Math.pow(radius, 2) * height;
System.out.print("Volume of Cone is : " + volume);
}
public static void main(String args[])
{
ConeVolume obj = new ConeVolume();
obj.CalcVol();
}
}

Output :-

javac fun.java

java ConeVolume

Program to calculate Volume of Cone
Enter radius value : 2
Enter height value : 3
Volume of Cone is : 12.566370614359172




38 :- Java Program to find volume of cone

import java.util.Scanner;
class CuboidArea
{
void CalcArea()
{
double length, width, height, area;
System.out.println(" ");
System.out.println("Program to calculate Area of Cuboid");
Scanner scan = new Scanner(System.in);
System.out.print("Enter length value : ");
length = scan.nextDouble();
System.out.print("Enter width value : ");
width = scan.nextDouble();
System.out.print("Enter height value : ");
height = scan.nextDouble();
area = 2 * ((length * width) + (length * height) + (height * width));
System.out.println("Area of Cuboid is : " + area);
}
public static void main(String args[])
{
CuboidArea obj = new CuboidArea();
obj.CalcArea();
}
}

Output :-

javac fun.java

java CuboidArea

Program to calculate Area of Cuboid
Enter length value : 6
Enter width value : 4
Enter height value : 3
Area of Cuboid is : 108.0




39 :- Java Program to find volume of cone

import java.util.Scanner;
class CylinderArea
{
void CalcArea()
{
double radius, height, area;
System.out.println(" ");
System.out.println("Program to calculate Area of Cylinder");
Scanner scan = new Scanner(System.in);
System.out.print("Enter radius value : ");
radius = scan.nextDouble();
System.out.print("Enter height value : ");
height = scan.nextDouble();
area = 2 * Math.PI * radius * (radius + height);
System.out.println("Area of Cylinder is : " + area);
}
public static void main(String args[])
{
CylinderArea obj = new CylinderArea();
obj.CalcArea();
}
}

Output :-

javac fun.java

java CylinderArea

Program to calculate Area of Cylinder
Enter radius value : 5
Enter height value : 5
Area of Cylinder is : 314.1592653589793




40 :- Java program to find surface area of cube

import java.util.Scanner;
class CubeArea
{
void CalcArea()
{
double side, area;
System.out.println(" ");
System.out.println("Program to calculate Area of Cube");
Scanner scan = new Scanner(System.in);
System.out.print("Enter side value : ");
side = scan.nextDouble();
area = 6 * side * side;
System.out.println("Area of Cube is : " + area);
}
public static void main(String args[])
{
CubeArea obj = new CubeArea();
obj.CalcArea();
}
}

Output :-

javac fun.java

java CubeArea
Program to calculate Area of Cube
Enter side value : 8
Area of Cube is : 384.0




41 :- Java program to find surface area of cube

import java.util.Scanner;
class AverageMarks
{ void CalcAvg()
{
System.out.println(" ");
System.out.println("Program to calculate Average Marks");
int size, i, sum = 0;
double average = 0;
int[] marks;
Scanner scan = new Scanner(System.in);
System.out.print("How many marks you want to enter? : ");
size = scan.nextInt();
marks = new int[size];
for(i = 0; i < size; i++)
{
System.out.print("Enter value of marks : ");
marks[i] = scan.nextInt();
sum += marks[i];
}
if(size > 0)
{
average = (double) sum / size;
System.out.println(" ");
System.out.println("Average Marks are : " + average);
}
else
{
System.out.println("No Marks are entered. Cannot calculate average ");
}
}
public static void main(String args[])
{
AverageMarks obj = new AverageMarks();
obj.CalcAvg();
}
}

Output :-

javac fun.java

java AverageMarks

Program to calculate Average Marks
How many marks you want to enter? : 5
Enter value of marks : 10
Enter value of marks : 9
Enter value of marks : 8
Enter value of marks : 9
Enter value of marks : 10

Average Marks are : 9.2




42 :- Java program to check vowel or consonant

import java.util.Scanner;
class CheckVowelC
{
void CheckChar()
{
System.out.println(" ");
System.out.println("Program to check character is Vowel or Consonant");
char ch;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a character : ");
ch = scan.next().charAt(0);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
{
System.out.println("Entered character is Vowel");
}
else
{
System.out.println("Entered character is Consonant");
}
}
public static void main(String args[])
{
CheckVowelC obj = new CheckVowelC();
obj.CheckChar();
}
}

Output :-

javac fun.java

java CheckVowelC

Program to check character is Vowel or Consonant
Enter a character : r
Entered character is Consonant

java CheckVowelC

Program to check character is Vowel or Consonant
Enter a character : a
Entered character is Vowel




43 :- Java program to check vowel or consonant

import java.util.Scanner;
class SumOfNNum
{
void CalcSum()
{
System.out.println(" ");
System.out.println("Program to Print Sum of N Numbers");
int i, n, sum = 0;
Scanner scan = new Scanner(System.in);
System.out.print("Enter the value of N : ");
n = scan.nextInt();
int num[] = new int[n];
for(i = 0; i < n; i++)
{
System.out.print("Enter a number : ");
num[i] = scan.nextInt();
sum += num[i];
}
System.out.println(" ");
System.out.println("Sum of N Numbers is : " + sum);
}
public static void main(String args[])
{
SumOfNNum obj = new SumOfNNum();
obj.CalcSum();
}
}

Output :-

javac fun.java

java SumOfNNum

Program to Print Sum of N Numbers
Enter the value of N : 5
Enter a number : 5
Enter a number : 4
Enter a number : 2
Enter a number : 2
Enter a number : 1

Sum of N Numbers is : 14




44 :- Java program to find factorial of any number

import java.util.Scanner;
class Factorial
{
void factorial()
{
System.out.println(" ");
System.out.println("Program to Find Factorial of a Number");
Scanner scan = new Scanner(System.in);
int num, fact = 1, i;
System.out.print("Enter a number : ");
num = scan.nextInt();
for(i = 1; i <= num; i++)
{
fact *= i;
}
System.out.println("Factorial of " + num + " is : " + fact);
}
public static void main(String args[])
{
Factorial obj = new Factorial();
obj.factorial();
}
}

Output :-

javac fun.java

java Factorial

Program to Find Factorial of a Number
Enter a number : 4
Factorial of 4 is : 24




45 :- Java Program to calculate electricity bill

import java.util.Scanner;
class ElectricityBill
{
void CalcBill()
{
System.out.println(" ");
System.out.println("Program to calculate Electricity Bill");
Scanner scan = new Scanner(System.in);
double rate, unit, total;
System.out.print("Enter the rate per unit (in rupees) : ");
rate = scan.nextInt();
System.out.print("Enter the number of units consumed : ");
unit = scan.nextInt();
total = rate * unit;
System.out.println("Total Electricity Bill is : " + total);
}
public static void main(String args[])
{
ElectricityBill obj = new ElectricityBill();
obj.CalcBill();
}
}

Output :-

javac fun.java

java ElectricityBill

Program to calculate Electricity Bill
Enter the rate per unit (in rupees) : 9
Enter the number of units consumed : 230
Total Electricity Bill is : 2070.0




46 :- Java Program To Calculate CGPA Percentage

import java.util.Scanner;
class CGPAToPercentage
{
void CalcPer()
{
System.out.println(" ");
System.out.println("Program to calculate CGPA to Percentage");
Scanner scan = new Scanner(System.in);
System.out.print("Enter CGPA out of 10 : ");
double cgpa = scan.nextDouble();
double percentage = cgpa * 9.5; //formula can vary between institutions
System.out.println("Your percentage is : " + percentage + " % ");
}
public static void main(String args[])
{
CGPAToPercentage obj = new CGPAToPercentage();
obj.CalcPer();
}
}

Output :-

javac fun.java

java CGPAToPercentage

Program to calculate CGPA to Percentage
Enter CGPA out of 10 : 8.9
Your percentage is : 84.55 %




47 :- Java Program to calculate compound interest

import java.util.Scanner;
class CompoundI
{
void Calculate()
{
System.out.println(" ");
System.out.println("Program to calculate Compound Interest");
Scanner scan = new Scanner(System.in);
System.out.print("Enter Principal Amount : ");
double principal = scan.nextDouble();
System.out.print("Enter Annual Interest : ");
double interest = scan.nextDouble();
System.out.print("Enter Time Period : ");
double time = scan.nextDouble();
System.out.print("Enter Compound Frequency : ");
int frequency = scan.nextInt();
double calc = principal * Math.pow(1 + interest / frequency, frequency * time);
double com_interest = calc - principal;
System.out.println(" ");
System.out.print("Compound Interst is : " + com_interest);
System.out.println(" ");
}
public static void main(String args[])
{
CompoundI obj = new CompoundI();
obj.Calculate();
}
}

Output :-

javac fun.java

java CompoundI

Program to calculate Compound Interest
Enter Principal Amount : 10
Enter Annual Interest : 8
Enter Time Period : 2
Enter Compound Frequency : 4

Compound Interst is : 65600.0




48 :- Java Program To Calculate Batting Average

import java.util.Scanner;
class BattingA
{
void BattingAverage()
{
System.out.println(" ");
System.out.println("Program to calculate Batting Average");
Scanner scan = new Scanner(System.in);
System.out.print("Enter the total runs scored : ");
int score = scan.nextInt();
System.out.print("Enter the number of time dismissed : ");
int dismiss = scan.nextInt();
if(dismiss > 0)
{
double BattingAverage = score / dismiss;
System.out.println("Batting Average is : " + BattingAverage);
}
else
{
System.out.println("Batting Average N/A (Player has not been dismissed) ");
}
}
public static void main(String args[])
{
BattingA obj = new BattingA();
obj.BattingAverage();
}
}

Output :-

javac fun.java

java BattingA

Program to calculate Batting Average
Enter the total runs scored : 230
Enter the number of time dismissed : 4
Batting Average is : 57.0




49 :- Java Pogram to Calculate Commission Percentage

import java.util.Scanner;
class CommissionP
{
void CalcCommission()
{
System.out.println(" ");
System.out.println("Program to calculate Commission Percentage");
Scanner scan = new Scanner(System.in);
System.out.print("Enter Total Sale : ");
double sale = scan.nextDouble();
System.out.print("Enter Commission Rate : ");
double rate = scan.nextDouble();
double comm_amt = (sale * rate) / 100;
double comm_perc = (comm_amt / sale) * 100;
System.out.println("Commission Amount : " + comm_amt);
System.out.println("Commission Percentage : " + comm_perc);
}
public static void main(String args[])
{
CommissionP obj = new CommissionP();
obj.CalcCommission();
}
}

Output :-

javac fun.java

java CommissionP

Program to calculate Commission Percentage
Enter Total Sale : 60000
Enter Commission Rate : 5
Commission Amount : 3000.0
Commission Percentage : 5.0




50 :- Java Pogram To Find Distance Between Two Points

import java.util.Scanner; class PointsDistance
{
void CalcDist()
{
System.out.println(" ");
System.out.println("Program to calculate Distance between two Points");
Scanner scan = new Scanner(System.in);
System.out.print("Enter x-coordinate of first point : ");
double x1 = scan.nextDouble();
System.out.print("Enter y-coordinate of first point : ");
double y1 = scan.nextDouble();
System.out.print("Enter x-coordinate of second point : ");
double x2 = scan.nextDouble();
System.out.print("Enter y-coordinate of second point : ");
double y2 = scan.nextDouble();
double distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
System.out.println(" ");
System.out.print("Distance between two points is : " + distance);
System.out.println(" ");
}
public static void main(String args[])
{
PointsDistance obj = new PointsDistance();
obj.CalcDist();
}
}

Output :-

javac fun.java

java PointsDistance

Program to calculate Distance between two Points
Enter x-coordinate of first point : 10
Enter y-coordinate of first point : 5
Enter x-coordinate of second point : 10
Enter y-coordinate of second point : 8

Distance between two points is : 3.0




51 :- Java Program To Calculate Power Of Number

import java.util.Scanner;
class PowerOfN
{
void CalcPower()
{
System.out.println(" ");
System.out.println("Program to calculate Power of a Number");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = scan.nextInt();
System.out.print("Enter Power of a number : ");
int power = scan.nextInt();
int i, result = 1;
for(i = 0; i < power; i++)
{
result *= num;
}
System.out.println("Result is : " + result);
}
public static void main(String args[])
{
PowerOfN obj = new PowerOfN();
obj.CalcPower();
}
}

Output :-

javac pro51.java
java PowerOfN
Program to calculate Power of a Number
Enter a number : 41
Enter Power of a number : 2
Result is : 1681

52 :- Write a Java program to take three numbers from the user and print the greates number

import java.util.Scanner;
class GreatestNumber
{
void CalcGreater()
{
System.out.println(" ");
System.out.println("Program to check greatest number from three numbers");
Scanner scan = new Scanner(System.in);
System.out.print("Enter First Number : ");
int first = scan.nextInt();
System.out.print("Enter Second Number : ");
int second = scan.nextInt();
System.out.print("Enter Third Number : ");
int third = scan.nextInt();
if(first > second)
{
if(first > third)
{
System.out.println(" ");
System.out.print("First is greatest Number");
}
}
else if(second > third)
{
System.out.println(" ");
System.out.print("Second is greatest Number");
}
else
{
System.out.println(" ");
System.out.print("Third is greatest Number");
}
}
public static void main(String args[])
{
GreatestNumber obj = new GreatestNumber(); }}

Output :-

javac pro52.java
java GreatestNumber
Program to check greatest number from three numbers
Enter First Number : 3
Enter Second Number : 4
Enter Third Number : 5
Third is greatest Number




53 :- Java Program To Calculate Power Of Number

import java.util.Scanner;
class PowerOfN
{
void CalcPower()
{
System.out.println(" ");
System.out.println("Program to calculate Power of a Number");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = scan.nextInt();
System.out.print("Enter Power of a number : ");
int power = scan.nextInt();
int i, result = 1;
for(i = 0; i < power; i++)
{
result *= num;
}
System.out.println("Result is : " + result);
}
public static void main(String args[])
{
PowerOfN obj = new PowerOfN();
obj.CalcPower();
}
}

Output :-

javac pro51.java
java PowerOfN
Program to calculate Power of a Number
Enter a number : 41
Enter Power of a number : 2
Result is : 1681




54 :- Write a Java program to test a number is positive or negative

import java.util.Scanner;
class TestPositiveNegative
{
void CheckNumber()
{
System.out.println(" ");
System.out.println("Program to test a Number is Positive or Negative");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = scan.nextInt();
if(num > 0)
{
System.out.println("It is a Positive Number");
}
else if(num < 0)
{
System.out.println("It is a Negative Number");
}
else
{
System.out.println("Number is zero");
}
}
public static void main(String args[])
{
TestPositiveNegative t = new TestPositiveNegative();
t.CheckNumber();
}
}

Output :-

javac pro54.java
java TestPositiveNegative
Program to test a Number is Positive or Negative
Enter a number : 45
It is a Positive Number




55 :- Write a Java Program to accept number of week’s day (1-7) and print name of the day

import java.util.Scanner;
class WeekDay
{
void ShowDay()
{
System.out.println(" ");
System.out.println("Program to Print Day of Choice");
Scanner scan = new Scanner(System.in);
System.out.print("Enter Day number (1-7) :");
int num = scan.nextInt();
switch(num)
{
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Wrong input");
}
}
public static void main(String args[])
{
WeekDay obj = new WeekDay();
obj.ShowDay();
}
}

Output :-

javac pro55.java java WeekDay Program to Print Day of Choice Enter Day number (1-7) :4 Thursday




56 :- Write a Java program that takes a year from user and print whether that year is a leap year or not

import java.util.Scanner;
class LeapYear
{
void LeapYear()
{
System.out.println(" ");
System.out.println("Program to Check Leap Year or not ");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a year : ");
int year = scan.nextInt();

if((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
{
System.out.println(year + " is a Leap Year");
}
else
{
System.out.println(year + " is not a Leap Year");
} }
public static void main(String args[])
{
LeapYear obj = new LeapYear();
obj.LeapYear();
}
}

Output :-

javac pro56.java
java LeapYear
Program to Check Leap Year or not
Enter a year : 2004
2004 is a Leap Year




57 :- Write a Java program to input 5 numbers from keyboard and find their sum and average

import java.util.Scanner;

class SumAverage
{
void CalcSumAvg(int num1, int num2, int num3, int num4, int num5)
{
int sum;
sum = num1 + num2 + num3 + num4 + n
um5; System.out.println(" "); System.out.println("Sum of Numbers is : " + sum); double average = (double) sum / 5;
System.out.println(" ");
System.out.println("Average of Numbers is : " + average);
}
public static void main(String args[])
{
System.out.println(" ");
System.out.println("Program to calculate Sum and Average of Five numbers");
Scanner scan = new Scanner(System.in);
System.out.print("Enter first number : ");
int num1 = scan.nextInt();
System.out.print("Enter second number : ");
int num2 = scan.nextInt();
System.out.print("Enter third number : ");
int num3 = scan.nextInt();
System.out.print("Enter fourth number : ");
int num4 = scan.nextInt();
System.out.print("Enter fifith number : ");
int num5 = scan.nextInt();

SumAverage obj = new SumAverage();
obj.CalcSumAvg(num1, num2, num3, num4, num5);
}
}

Output :-

javac pro57.java
java SumAverage
Program to calculate Sum and Average of Five numbers
Enter first number : 34
Enter second number : 53
Enter third number : 2
Enter fourth number : 5
Enter fifith number : 34
Sum of Numbers is : 128
Average of Numbers is : 25.6




58 :- Write a program in Java to display the first 5 natural numbers

class NaturalNumber
{
void PrintNaturalNumbers()
{
System.out.println(" ");
System.out.println("PROGRAM TO PRINT FIRST FIVE NATURAL NUMBERS");
System.out.print("First Five Natural Numbers are : ");
int i;
for(i = 1; i <= 5; i++)
{
System.out.println( " ");
System.out.print(i + " ");
}
}
public static void main(String args[])
{
NaturalNumber obj = new NaturalNumber();
obj.PrintNaturalNumbers();
}
}

Output :-

javac pro58.java
java NaturalNumber
PROGRAM TO PRINT FIRST FIVE NATURAL NUMBERS
First Five Natural Numbers are :
1
2
3
4
5




59 :- Write a java program to check vowel or consonant

import java.util.Scanner;
class CheckVowelConsonant
{
void CheckChar()
{
System.out.println(" ");
System.out.println("Program to check character is Vowel or Consonant");
char ch;
Scanner scan = new Scanner(System.in);
System.out.print("Enter a character : ");
ch = scan.next().charAt(0);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U')
{
System.out.println("Entered character is Vowel");
}
else
{
System.out.println("Entered character is Consonant");
}
}
public static void main(String args[])
{
CheckVowelConsonant obj = new CheckVowelConsonant();
obj.CheckChar();
}
}

Output :-

javac pro59.java
java CheckVowelConsonant
Program to check character is Vowel or Consonant
Enter a character : u
Entered character is Vowel




60 :- Write a Java program to display the cube of the number upto given an integer

import java.util.Scanner;

class IntegerCube
{
void CalcCube()
{
System.out.println(" ");
System.out.println("Program to calculate Cube of an integer upto some integer");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = scan.nextInt();
System.out.println("Cubes of Numbers from 1 to " + num + " : ");
int i;
for(i = 1; i <= num; i++)
{
int cube = i * i * i;
System.out.println("Cube of " + i + " is " + cube);
}
}
public static void main(String args[])
{
IntegerCube obj = new IntegerCube();
obj.CalcCube();
}
}

Output :-

javac pro60.java
java IntegerCube
Program to calculate Cube of an integer upto some integer
Enter a number : 4
Cubes of Numbers from 1 to 4 :
Cube of 1 is 1
Cube of 2 is 8
Cube of 3 is 27
Cube of 4 is 64




61 :- Write a Java program to display the n terms of odd natural number and their sum

import java.util.Scanner;
class OddNaturalNSum
{
void Calc()
{
System.out.println(" ");
System.out.println("Program to Print Odd Natural Number's and their Sum upto N");
Scanner scan = new Scanner(System.in);
System.out.print("Enter value of N : ");
int n = scan.nextInt();
int i, sum = 0, odd = 1;
System.out.print("First Odd " + n + " Natural Numbers are : ");
for(i = 1; i <= n; i++){
System.out.print(odd + " ");
sum += odd;
odd += 2;
if(odd > n){
break;
}
}
System.out.println("\nSum of all " + n + " Natural Numbers is : " + sum);
}
public static void main(String args[])
{
OddNaturalNSum obj = new OddNaturalNSum();
obj.Calc();
}
}

Output :-

javac pro61.java
java OddNaturalNSum
Program to Print Odd Natural Number's and
their Sum upto N
Enter value of N : 3
First Odd 3 Natural Numbers are : 1 3
Sum of all 3 Natural Numbers is : 4




62 :- Write a Java program to display the multiplication table of a given integer

import java.util.Scanner;
class MultiplicationT
{
void CalcTable()
{
System.out.println(" ");
System.out.println("Program to Print Multiplication Table of a Number");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = scan.nextInt();
System.out.println("Multiplication Table of " + num + " is : ");
int i;
for(i = 1; i <= 10; i++)
{
System.out.println(num + " * " + i + " = " + (num*i));
}
}
public static void main(String args[])
{
MultiplicationT obj = new MultiplicationT();
obj.CalcTable();
}
}

Output :-

javac pro62.java
java MultiplicationT
Program to Print Multiplication Table of a Number
Enter a number : 5
Multiplication Table of 5 is :
5 * 1 = 5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50




63 :- Write a Java program that reads an integer and check whether it is negative, zero, or positive

import java.util.Scanner;
class CheckPandNegative
{
void CheckNumber()
{
System.out.println(" ");
System.out.println("Program to Check Number is Positive or Negative");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = scan.nextInt();
if(num > 0)
{
System.out.println("It is a Positive Number");
}
else if(num < 0)
{
System.out.println("It is a Negative Number");
}
else
{
System.out.println("Number is zero");
}
}
public static void main(String args[])
{
CheckPandNegative obj = new CheckPandNegative();
obj.CheckNumber();
}
}

Output :-

javac pro63.java
java CheckPandNegative
Program to Check Number is Positive or Negative
Enter a number : -43
It is a Negative Number




64 :- Write a Java program that reads an positive integer and count the number of digits

import java.util.Scanner;
class CountPandIDigits
{
void Count()
{
System.out.println(" ");
System.out.println("Program to Count Sum of Positive Integer's Digits");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a Number : ");
int num = scan.nextInt();
if(num > 0)
{
int sum = 0;
int temp = num;
while(temp != 0)
{
int digit = temp % 10;
sum += digit;
temp /= 10;
}
System.out.println("Sum of Digits : " + sum);
}
else
{
System.out.println("It is a Negative Number");
}
}
public static void main(String args[])
{
CountPandIDigits obj = new CountPandIDigits();
obj.Count();
}
}

Output :-

javac pro64.java
java CountPandIDigits
Program to Count Sum of Positive Integer's Digits
Enter a Number : 5
Sum of Digits : 5




65 :- Write a Java program that accepts three numbers and check All numbers are equal or not

import java.util.Scanner;

class CheckEqualN
{
void CheckNumber()
{
System.out.println(" ");
System.out.println("Program to Check All Three Number are Equal or Not");
Scanner scan = new Scanner(System.in);
System.out.print("Enter First Number : ");
int first = scan.nextInt();
System.out.print("Enter Second Number : ");
int second = scan.nextInt();
System.out.print("Enter Third Number : ");
int third = scan.nextInt();

if(first == second && second == third)
{ System.out.println("All Three Numbers are Equal");
}
else
{
System.out.println("All Three Numbers are Not Equal");
}
}
public static void main(String args[])
{
CheckEqualN obj = new CheckEqualN();
obj.CheckNumber();
}
}

Output :-

javac pro65.java
java CheckEqualN
Program to Check All Three Number are Equal or Not
Enter First Number : 45
Enter Second Number : 54
Enter Third Number : 45
All Three Numbers are Not Equal




66 :- Write a java program that accepts three numbers from the user and check if numbers are in “increasing” or “decreasing” order.

import java.util.Scanner;
class NumberOrder
{
void CheckOrder()
{
System.out.println(" ");
System.out.println("Program to Check Order of Three Numbers");
Scanner scan = new Scanner(System.in);
System.out.print("Enter First Number : ");
int first = scan.nextInt();
System.out.print("Enter Second Number : ");
int second = scan.nextInt();
System.out.print("Enter Third Number : ");
int third = scan.nextInt();
if(first > second && second > third)
{
System.out.println("Numbers are in Decreasing Order");
}
else if(first < second && second < third)
{
System.out.println("Numbers are in Increasing Order");
}
else
{
System.out.println("Numbers are Not in Increasing and Nor in Decreasing Order");
}
}
public static void main(String args[])
{
NumberOrder obj = new NumberOrder();
obj.CheckOrder();
}
}

Output :-

javac pro66.java
java NumberOrder
Program to Check Order of Three Numbers
Enter First Number : 66
Enter Second Number : 676
Enter Third Number : 45
Numbers are Not in Increasing and Nor in Decreasing Order




67 :- Write a Java program that determines a student’s grade

import java.util.Scanner;
class StudentGrade
{
void CalcGrade()
{
System.out.println(" ");
System.out.println("Program to calculate Student Grade");
Scanner scan = new Scanner(System.in);
System.out.print("Enter Student's Marks : ");
int num = scan.nextInt();
if(num >= 90)
{
System.out.println("Student Grade is : A");
}
else if(num >=80)
{
System.out.println("Student Grade is : B");
}
else if(num >=70)
{
System.out.println("Student Grade is : C");
}
else if(num >=60)
{
System.out.println("Student Grade is : D");
}
else if(num >=50)
{
System.out.println("Student Grade is : E");
}
else{
System.out.println("Student Grade is : F");
}
}
public static void main(String args[])
{
StudentGrade obj = new StudentGrade();
obj.CalcGrade();
}
}

Output :-

javac pro67.java
java StudentGrade
Program to calculate Student Grade
Enter Student's Marks : 64
Student Grade is : D




68 :- Write a Java program to create a simple calculator

import java.util.Scanner; class Calculator
{
void Calculator()
{
System.out.println(" ");
System.out.println("Program to create a Simple Calculator");
Scanner scan = new Scanner(System.in);
System.out.println("Simple Calculator");
System.out.println("----------------------------");
while(true)
{
System.out.print("Enter First Number : ");
double first = scan.nextDouble();
System.out.print("Enter an Operator or enter q to exit : ");
char operator = scan.next().charAt(0);
if(operator == 'q')
{
System.out.println("Calculator Exiting ");
break;
}
System.out.print("Enter Second Number : ");
double second = scan.nextDouble();
double result;
switch(operator)
{
case '+':
result = first + second;
System.out.println("Addition is : " + result);
break;
case '-':
result = first - second;
System.out.println("Subtraction is : " + result);
break;
case '*':
result = first * second;
System.out.println("Multiplication is : " + result);
break;
case '/':
if(second != 0)
{
result = first / second;
System.out.println("Division is : " + result);
break;
}
else
{
System.out.println("Cannot divide by 0 !!");
continue;
}
default:
System.out.println("Please enter valid operator !!");
}
}
}
public static void main(String args[])
{
Calculator obj = new Calculator();
obj.Calculator();
}
}

Output :-

javac pro68.java
java Calculator
Program to create a Simple Calculator
Simple Calculator
----------------------------
Enter First Number : 534
Enter an Operator or enter q to exit : *
Enter Second Number : 2
Multiplication is : 1068.0
Enter First Number :




69 :- Write a Java program to concatenate two string

import java.util.Scanner;
class ConcatenateString
{
void Concatenate()
{
System.out.println(" ");
System.out.println("Program to Concatenate Two Strings");
Scanner scan = new Scanner(System.in);
System.out.print("Enter first string : ");
String first = scan.nextLine();
System.out.print("Enter second string : ");
String second = scan.nextLine();
String merged = first + second;
System.out.println("Concatenated String is : " + merged);
}
public static void main(String args[])
{
ConcatenateString obj = new ConcatenateString();
obj.Concatenate();
}
}

Output :-

javac pro69.java
java ConcatenateString
Program to Concatenate Two Strings
Enter first string : ja
Enter second string : va
Concatenated String is : java




70 :- Write a Java program to convert all characters in a string to lowercase

import java.util.Scanner;
class LowercaseString
{
void ConvertString()
{
System.out.println(" ");
System.out.println("Program to Convert String to Lowercase");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string : ");
String text = scan.nextLine();
String result = text.toLowerCase();
System.out.println("Lowercase String is : " + result);
}
public static void main(String args[])
{
LowercaseString obj = new LowercaseString();
obj.ConvertString();
}
}

Output :-

javac pro70.java
java LowercaseString
Program to Convert String to Lowercase
Enter a string : HELLO
Lowercase String is : hello




71 :- Write a Java program to convert all characters in a string to uppercase

import java.util.Scanner;
class UppercaseString
{
void ConvertString()
{
System.out.println(" ");
System.out.println("Program to Convert String to Uppercase");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string : ");
String text = scan.nextLine();
String result = text.toUpperCase();
System.out.println("Uppercase String is : " + result);
}
public static void main(String args[])
{
UppercaseString obj = new UppercaseString();
obj.ConvertString();
}
}

Output :-

javac pro71.java
java UppercaseString
Program to Convert String to Uppercase
Enter a string : hello
Uppercase String is : HELLO




72 :- Write a Java program to trim a string(remove whitespaces)

import java.util.Scanner;
class Trim
{
void RemoveSpace()
{
System.out.println(" ");
System.out.println("Program to Remove Whitespaces from a String");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a paragraph : ");
String para = scan.nextLine();
String result = para.replaceAll("\\s+","");
System.out.println(" ");
System.out.println("Original String is : " + para);
System.out.println("Trimmed String is : " + result);
}
public static void main(String args[])
{
Trim obj = new Trim();
obj.RemoveSpace();
}
}

Output :-

javac pro72.java
java Trim
Program to Remove Whitespaces from a String
Enter a paragraph : Welcome in the world of java programming
Original String is : Welcome in the world of java programming
Trimmed String is : Welcomeintheworldofjavaprogramming




73 :- Write a Java program to get a substring of a given string between two specified positions

import java.util.Scanner;

class Substring
{
void getSubstring()
{
System.out.println(" ");
System.out.println("Program to Print Substring from a String");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String : ");
String text = scan.nextLine();
System.out.print("Enter Starting Index : ");
int start = scan.nextInt();
System.out.print("Enter Ending Index : ");
int end = scan.nextInt();
int i;
if(start < 0 || end > text.length() || start > end)
{
System.out.println("Enter valid Index");
}
String substr = text.substring(start, end);
System.out.println(" ");
System.out.println("Original String is : " + text);
System.out.println("Substring is : " + substr);
}
public static void main(String args[])
{
Substring obj = new Substring();
obj.getSubstring();
}
}

Output :-

javac pro73.java
java Substring
Program to Print Substring from a String
Enter a String : Welcome in the world of java programming
Enter Starting Index : 16
Enter Ending Index : 20
Original String is : Welcome in the world of java programmingSubstring is : orld




74 :- Write a Java program to replace all the ‘d’ characters with ‘f’ characters

import java.util.Scanner;
class ReplaceCharacter
{
void Replace()
{
System.out.println(" ");
System.out.println("Program to Replace 'd' characters with 'f' characters");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string : ");
String text = scan.nextLine();
String replace = text.replaceAll("d","f");
System.out.println(" ");
System.out.println("Original String is : " + text);
System.out.println("Replaced String is : " + replace);
}
public static void main(String args[])
{
ReplaceCharacter obj = new ReplaceCharacter();
obj.Replace();
}
}

Output :-

javac pro74.java
java ReplaceCharacter
Program to Replace 'd' characters with 'f' characters
Enter a string : gold
Original String is : gold
Replaced String is : golf




75 :- Write a java program to get the length of a given string

import java.util.Scanner; class StringLength
{
void getLength()
{
System.out.println(" ");
System.out.println("Program to Count Length of a String");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a String : ");
String text = scan.nextLine();
int count = text.length();
System.out.println(" ");
System.out.println("String is : " + text);
System.out.println("String Length is : " + count);
}
public static void main(String args[])
{
StringLength obj = new StringLength();
obj.getLength();
}
}

Output :-

javac pro75.java
java StringLength
Program to Count Length of a String
Enter a String : hello world
String is : hello world
String Length is : 11




76 :- Write a java program to print current date and time in the specified format

class CurrentDateTime
{
public static void main(String a[])
{
java.util.Date Current_date= new java.util.Date();

System.out.println(" ");
System.out.println("program to print current Date and Time");
System.out.println("Current Date and Time : " );
System.out.println(Current_date);
}
}

Output :-

javac pro76.java
java CurrentDateTime
program to print current Date and Time
Current Date and Time :
Wed Nov 15 11:52:22 IST 2023




77 :- Write a Java program to get the character at the given index within the String

class CharIndex
{
public static void main(String args[])
{
System.out.println(" ");
System.out.println("Program to get the character at the given index within the String");
String str= "Good Morning";
System.out.println("Original string : "+str);
int index1 = str.charAt(0);
int index2 = str.charAt(5);
System.out.println("The Character at Index 0 : " +(char)index1);
System.out.println("The Character at Index 8 : " +(char)index2);
}
}

Output :-

javac pro77.java
java CharIndex
Program to get the character at the given index within the String
Original string : Good Morning
The Character at Index 0 : G
The Character at Index 8 : M




78 :- Write a java program to remove a particular character from a string

class RemoveCharacter
{
public static void main(String args[])
{
System.out.println(" ");
System.out.println("Program to remove a particular character from a string");
String str = "Morning";
String replace = str.replaceAll("M"," ");
System.out.println(" ");
System.out.println("Original String is : " + str);
System.out.println("Replaced String is : " + replace);
}
}

Output :-

javac pro78.java
java RemoveCharacter
Program to remove a particular character from a string
Original String is : Morning
Replaced String is : orning
7




79 :- Write a java program to reverse a String

import java.util.Scanner;
class StringReverse
{
public static void main(String[] args)
{
System.out.println(" ");
System.out.println("Program to reverse a String");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string : ");
String text = scan.nextLine();

StringBuilder reverseString = new StringBuilder();
reverseString.append(text);
reverseString.reverse();
System.out.println(" ");
System.out.println("Original string: "+text);
System.out.println("Reversed string: "+reverseString);
}
}

Output :-

javac pro79.java

java StringReverse
Program to reverse a String
Enter a string : strong
Original string: strong
Reversed string: gnorts




80 :- Write a java program to remove html tags from a string

import java.util.Scanner;
class RemoveHtmltags
{
public static void main(String args[])
{
System.out.println(" ");
System.out.println("Program to remove html tags from a string");
Scanner scan = new Scanner(System.in);
System.out.print("Enter a string with using Html tags : ");
String text = scan.nextLine();

String remove= text.replaceAll("\\<.*?\\>"," ");
System.out.println(" ");
System.out.println("Original String is : " + text);
System.out.println("Replaced String is : " + remove);
}

}

Output :-

javac pro80.java
java RemoveHtmltags
Program to remove html tags from a string Enter a string with using Html tags :

Let's get started


Original String is :

Let's get started


Replaced String is : Let's get started




81 :- Write a java program to count total number of lines from a string

class CountLineString
{
public static void main(String[] args) throws java.io.IOException
{
System.out.println("\nProgram to count total number of lines from a string");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
try {
System.out.println("Enter a multi-line string (type 'end' on a new line to finish input):"); String inputLine;
int lineCount = 0;
while (true)
{
inputLine = input.readLine();
if (inputLine.equals("end"))
{
break;
}
lineCount++;
}
System.out.println("Total number of lines: " + lineCount);
} catch (Exception e)
{
System.out.println("Something went wrong.");
}
}
}

Output :-

javac pro81.java
java CountLineString
Program to count total number of lines from a string
Enter a multi-line string (type 'end' on a new line to finish input): hello in world of programming end
Total number of lines: 1




69 82 :- Write a Java program to sum values of an array

import java.util.Scanner;
class SumOfArrayValues
{
void CalcSum()
{
System.out.println("Program to sum values of an array");
int i, n, sum = 0;
Scanner scan = new Scanner(System.in);
System.out.println(" ");
System.out.print("Enter the value of Number : ");
n = scan.nextInt();
int num[] = new int[n];
for(i = 0; i < n; i++)
{
System.out.print("Enter a array element : ");
num[i] = scan.nextInt();
sum += num[i];
}
System.out.println(" ");
System.out.println("Sum of all the element of an array is : " + sum);
}

public static void main(String args[])
{
SumOfArrayValues obj = new SumOfArrayValues();
obj.CalcSum();
}
}

Output :-

javac pro82.java
java SumOfArrayValues
Program to sum values of an array
Enter the value of Number : 3
Enter a array element : 34
Enter a array element : 54
Enter a array element : 65
Sum of all the element of an array is : 153




83 :- Write a Java program to find the index of an array element

import java.util.Arrays;
class findIndexArray
{
public static void main(String a[])
{
int[] number= {10,20,30,40,50,60};
System.out.println(" ");
System.out.println("Program to find the index of an array element");

int element = 30;
int index = -1;
for(int i = 0; i< number.length; i++)
{
if(number[i] == element)
{
index = i;
break;
}

}
System.out.println("Array : " +Arrays.toString(number));
System.out.println("Index of array " +element+" is : "+index);
}
}

Output :-

javac pro83.java
java findIndexArray
Program to find the index of an array element
Array : [10, 20, 30, 40, 50, 60]
Index of array 30 is : 2




84 :- Write a Java program to calculate the average value of array elements

import java.util.Arrays;
class ArrayAverage
{
public static void main(String[] args)
{
System.out.println(" ");
System.out.println("Program to calculate the average value of array elements");
int[] numbers = {20, 30, 25, 35, -16, 60, -100};
int sum = 0;
for(int i=0; i < numbers.length ; i++)
sum = sum + numbers[i];
double average = sum / numbers.length;
System.out.println("Arrays : "+ Arrays.toString(numbers));
System.out.println("Average value of the array elements is : " + average);
}
}

Output :-

javac pro84.java
java ArrayAverage
Program to calculate the average value of array elements
Arrays : [20, 30, 25, 35, -16, 60, -100]
Average value of the array elements is : 7.0




85 :- Write a Java program to test if an array contains a specific value

import java.util.Arrays;
class TestArrayValues
{
public static void main(String args[])
{
System.out.println(" ");
System.out.println("PROGRAM TO TEST IF AN ARRAY CONTAINS A SPECIFIC VALUE");
int[] arr = {55, 45, 69, 44, 12, 67, 34, 23, 78, 90};
int num = 67;

for(int i = 0; i< arr.length; i++)
{
if(num == arr[i])
{
System.out.println("Array : " +Arrays.toString(arr));
System.out.println(num+ " Array contains the given element");
}
}
}
}

Output :-

javac pro85.java
java TestArrayValues
PROGRAM TO TEST IF AN ARRAY CONTAINS A SPECIFIC VALUE
Array : [55, 45, 69, 44, 12, 67, 34, 23, 78, 90]
67 Array contains the given element




86 :- Write a Java program to find the maximum and minimum value of an array

import java.util.Scanner;

class ArraysMaxMin
{
public static void main(String a[])
{
System.out.println("\n program to find the maximum and minimum value of an array");
Scanner sc = new Scanner(System.in);
System.out.print("\n Enter Size of Array: ");
int n = sc.nextInt();
int i, sum = 0; int arr[] = new int[n];
for (i = 0; i < n; i++)
{
System.out.print( " Enter a number : ");
arr[i] = sc.nextInt();
}
int max_element = arr[0];
int min_element = arr[0];
for (i = 0; i < n; i++)
{
if (arr[i] > max_element)
{
max_element = arr[i];
}
if (arr[i] < min_element)
{
min_element = arr[i];
}
}
System.out.println("\n Maximum value of array is : " + max_element); System.out.println("\n Minimum value of array is : " + min_element); } }

Output :-

javac pro86.java
java ArraysMaxMin
program to find the maximum and minimum value of an array
Enter Size of Array: 5
Enter a number : 23
Enter a number : 34
Enter a number : 45
Enter a number : 56
Enter a number : 67
Maximum value of array is : 67
Minimum value of array is : 23




87 :- Write a Java program to insert an element (specific position) into an array

import java.util.Scanner;
class InsertArray
{
public static void main(String[] args)
{
System.out.println("\n program to insert an element (specific position) into an array");
int n, position, x;
Scanner s = new Scanner(System.in);
System.out.print("\n Enter no. of elements you want in array : ");
n = s.nextInt();
int arr[] = new int[n+1];
for(int i = 0; i < n; i++)
{
System.out.print(" Enter all the elements : ");
arr[i] = s.nextInt();
}
System.out.print("\n Enter the position where you want to insert element : ");
position = s.nextInt();
System.out.print("\n Enter the element you want to insert : ");
x = s.nextInt();
for(int i = (n-1); i >= (position-1); i--)
{
arr[i+1] = arr[i];
}
arr[position-1] = x;
System.out.print("\n After inserting : ");
for(int i = 0; i < n; i++)
{
System.out.print(arr[i] +" ");
}
System.out.println(arr[n]);
}
}

Output :-

javac pro87.java
java InsertArray
program to insert an element (specific position) into an array
Enter no. of elements you want in array : 4
Enter all the elements : 345
Enter all the elements : 53
Enter all the elements : 346
Enter all the elements : 234
Enter the position where you want to insert element : 2
Enter the element you want to insert : 345345
After inserting : 345 345345 53 346 234




88 :- Write a Java program to reverse an array of integer values

import java.util.Arrays;
class ReverseArray
{
public static void main(String[] args)
{
System.out.println("\n Program to reverse an array of integer values.");
int [] arr = {11, 12, 13, 14, 15, 16, 17};
System.out.print("\n Original array: ");

for (int i = 0; i < arr.length; i++)
{
System.out.print( arr[i] + " ");
}
System.out.print("\n Reverse a Array values : ");

for (int i = arr.length-1; i >= 0; i--)
{
System.out.print( arr[i] + " ");
}
}
}

Output :-

javac pro88.java
java ReverseArray
Program to reverse an array of integer values.
Original array: 11 12 13 14 15 16 17
Reverse a Array values : 17 16 15 14 13 12 11




89 :- Write a Java program to find the common elements between two arrays

import java.util.Arrays;
class CommonElementOfArr
{
public static void main(String[] args)
{
System.out.println("\n Program to find the common elements between two arrays");
int[] arr1 = {11, 34, 66, 78, 23, 60};
int[] arr2 = {66, 60, 70, 80, 11, 90};

System.out.println("\n Original Array1 : "+Arrays.toString(arr1));
System.out.println("\n Original Array2 : "+Arrays.toString(arr2));
System.out.println(" ");

System.out.print(" Array1 and Array2 are Common element is : ");
for (int i = 0; i < arr1.length; i++)
{
for (int j = 0; j < arr2.length; j++)
{
if(arr1[i] == (arr2[j]))
{
System.out.print(arr1[i] + " ");
}
}
}System.out.println(" ");
}
}

Output :-

javac pro89.java
java CommonElementOfArr
Program to find the common elements between two arrays
Original Array1 : [11, 34, 66, 78, 23, 60]
Original Array2 : [66, 60, 70, 80, 11, 90]
Array1 and Array2 are Common element is : 11 66 60




90 :- Write a Java program to find the duplicate values of an array of integer values

import java.util.Arrays;
class DuplicateValues
{
public static void main(String[] args)
{ System.out.println("\n Program to find the duplicate values of an array of integer values");
int [] arr = {11, 12, 13, 23, 11, 23, 90, 12};
System.out.println("\n Original Array : "+Arrays.toString(arr));
System.out.print(" Duplicate elements in given array: ");
for(int i = 0; i < arr.length; i++)
{
for(int j = i + 1; j < arr.length; j++)
{
if(arr[i] == arr[j])
{
System.out.print(arr[j] + " ");
}
}
} System.out.println(" ");
}
}

Output :-

javac pro90.java
java DuplicateValues
Program to find the duplicate values of an array of integer
values
Original Array : [11, 12, 13, 23, 11, 23, 90, 12]
Duplicate elements in given array: 11 12 23




91 :- Write a Java program to convert an array to ArrayList

import java.util.Arrays;
import java.util.List;
class ConvertArrayToArrList
{
public static void main (String[] args)
{
System.out.println("\n Program to convert an array to ArrayList.");
String[] fruits = {"Apple", "Mango", "Grapes", "Watermelon"};
List str = Arrays.asList(fruits);
System.out.println(" Array List is : "+str);
}
}

Output :-

javac pro91.java
java ConvertArrayToArrList
Program to convert an array to ArrayList.
Array List is : [Apple, Mango, Grapes, Watermelon]




92 :- Write a Java program to add two matrices of the same size

class TwoMaterics
{ public static void main(String arg[])throws java.io.IOException
{
System.out.println("\n Program to add two matrices of the same size");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
try{
System.out.println("\n Enter the Size of matrices");
System.out.print(" Enter number of rows : ");
int rows = Integer.parseInt(input.readLine());
System.out.print(" Enter number of columns : ");
int cols = Integer.parseInt(input.readLine());
int[][] arr1,arr2;
arr1= new int[rows][cols];
arr2= new int[rows][cols];

System.out.println("\n Enter the elements of first matrix :");
for(int i=0; i < rows;i++){
for(int j=0; j < cols;j++)
{
System.out.print(" Enter for position "+i+" "+j+" : ");
arr1[i][j]=Integer.parseInt(input.readLine());
}
}
System.out.println("\n Enter the elements of second matrix :");
for(int i=0;i < rows;i++)
{
for(int j=0;j < cols;j++)
{
System.out.print(" Enter for position "+i+" "+j+" : ");
arr2[i][j]=Integer.parseInt(input.readLine());
}
}
System.out.println("\nGiven matrices are : ");
System.out.println("Matrix-1");
for(int i=0;i < rows;i++)
{
for(int j=0;j< cols;j++)
System.out.print(arr1[i][j]+" ");
System.out.println();
}
System.out.println("\nMatrix-2");
for(int i=0;i< rows;i++)
{
for(int j=0;j< cols;j++)
System.out.print(arr2[i][j]+" ");
System.out.println();
}
System.out.println("\nSum of the matrices : ");
for(int i=0;i< rows;i++)
{
for(int j=0;j< cols;j++)
{
arr1[i][j] += arr2[i][j];
System.out.print(arr1[i][j]+" ");
}
System.out.println();
}
}
catch(java.lang.NumberFormatException e){
System.out.println("Invalid input. Please enter a valid number.");
}
}
}

Output :-

javac pro92.java
ava TwoMaterics
Program to add two matrices of the same size
Enter the Size of matrices
Enter number of rows : 3
Enter number of columns : 3
Enter the elements of first matrix :
Enter for position 0 0 : 1
Enter for position 0 1 : 2
Enter for position 0 2 : 3
Enter for position 1 0 : 4
Enter for position 1 1 : 5
Enter for position 1 2 : 6
Enter for position 2 0 : 7
Enter for position 2 1 : 8
Enter for position 2 2 : 9
Enter the elements of second matrix :
Enter for position 0 0 : 9
Enter for position 0 1 : 8
Enter for position 0 2 : 7
Enter for position 1 0 : 6
Enter for position 1 1 : 5
Enter for position 1 2 : 4
Enter for position 2 0 : 3
Enter for position 2 1 : 2
Enter for position 2 2 : 1
Given matrices are :
Matrix-1
1 2 3
4 5 6
7 8 9
Matrix-2
9 8 7
6 5 4
3 2 1
Sum of the matrices :
10 10 10
10 10 10
10 10 10




93 :- Write a Java program to find second largest number from the array

import java.util.Arrays;
class SecondLargestNumber
{
public static void main(String args[])
{
System.out.println("\n Program to find second largest number from the array");
int temp;
int array[] = {10, 20, 25, 63, 96, 57};

for(int i = 0; i< array.length; i++ )
{
for(int j = i+1; j< array.length; j++)
{
if(array[i]>array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("\n Arrays : "+Arrays.toString(array));
System.out.println(" Second largest number is : "+array[array.length-2]);
}
}

Output :-

javac pro93.java
java SecondLargestNumber
Program to find second largest number from the array
Arrays : [10, 20, 25, 57, 63, 96]
Second largest number is : 63




94 :- Write a Java program to find second lowest number from the array

import java.util.Arrays;
class SecondlowestNumber
{
public static void main(String args[])
{
System.out.println("\n Program to find second lowest number from the array");
int temp, size;
int array[] = {10, 20, 25, 63, 96, 57};
size = array.length;

for(int i = 0; i< size; i++ )
{ for(int j = i+1; j< size; j++)
{
if(array[i]>array[j]){
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("\n Arrays : "+Arrays.toString(array));
System.out.println(" Second Smallest element of the array is:: "+array[0]);
}
}

Output :-

javac pro94.java
java SecondlowestNumber
Program to find second lowest number from the array
Arrays : [10, 20, 25, 57, 63, 96]
Second Smallest element of the array is:: 10




95 :- Write a Java program to find the number of even and odd integers in a given array of integers

import java.util.Arrays;
class EvenOddNumber
{
public static void main(String a[])
{
System.out.println("\n Program to find the number of even and odd integers in a given array of integers");
int arr[]={1,2,5,6,3,2};
System.out.println("\n Arrays : "+Arrays.toString(arr));
System.out.println(" ");
System.out.print(" Odd Numbers : ");
for(int i=0;i< arr.length;i++)
{
if(arr[i] % 2 != 0)
{
System.out.print(arr[i] + " ");
}
}
System.out.print("\n Even Numbers : ");
for(int i=0;i < arr.length;i++)
{
if(arr[i] % 2 == 0)
{
System.out.print(arr[i] + " ");
}
}
}
}

Output :-

javac pro95.java
java EvenOddNumber
Program to find the number of even and odd integers in a given array of integers
Arrays : [1, 2, 5, 6, 3, 2]
Odd Numbers : 1 5 3
Even Numbers : 2 6 2




96 :- Write a Java program to get the difference between the largest and smallest values in an array of integers

import java.util.Arrays;
class LargestSmallestNumber
{

public static void main(String[] args)
{
System.out.println("\n Program to get the difference between the largest and smallest values in an array of integers");
int numbers[] = new int[]{55,32,45,98,82,11,9,39,50};
System.out.println("\n Arrays : "+Arrays.toString(numbers));
int smallest = numbers[0];
int largetst = numbers[0];
for (int i = 1; i < numbers.length; i++)
{
if (numbers[i] > largetst)
{
largetst = numbers[i];
}
else if (numbers[i] < smallest)
{
smallest = numbers[i];
}
}
System.out.println(" Largest Number is : " + largetst);
System.out.println(" Smallest Number is : " + smallest);
}
}

Output :-

javac pro96.java
java LargestSmallestNumber
Program to get the difference between the largest and smallest values in an array of integers
Arrays : [55, 32, 45, 98, 82, 11, 9, 39, 50]
Largest Number is : 98
Smallest Number is : 9




97 :- Write a Java program to segregate all 0s on left side and all 1s on right side of a given array of 0s and 1s

import java.util.Arrays;
class SecondLargestNumber
{
public static void main(String args[])
{
System.out.println("\n Program to find second largest number from the array");
int temp;
int array[] = {10, 20, 25, 63, 96, 57};

for(int i = 0; i< array.length; i++ )
{
for(int j = i+1; j< array.length; j++)
{
if(array[i]>array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("\n Arrays : "+Arrays.toString(array));
System.out.println(" Second largest number is : "+array[array.length-2]);
}
}

Output :-

javac pro93.java
java SecondLargestNumber
Program to find second largest number from the array
Arrays : [10, 20, 25, 57, 63, 96]
Second largest number is : 63




98 :- Write a Java program to cyclically rotate a given array clockwise by one

import java.util.Arrays;
class RotateArrayvalues
{
public static void main(String[] args)
{
System.out.println("\n Program to cyclically rotate a given array clockwise by one");
int [] arr = {10, 20, 30, 40, 50, 60, 70};
System.out.print("\n Original array: ");
for (int i = 0; i < arr.length; i++)
{
System.out.print( arr[i] + " ");
}
System.out.print("\n Rotate a Array values : ");

for (int i = arr.length-1; i >= 0; i--)
{
System.out.print( arr[i] + " "); }
}
}

Output :-

javac pro98.java
java RotateArrayvalues
Program to cyclically rotate a given array clockwise by one
Original array: 10 20 30 40 50 60 70
Rotate a Array values : 70 60 50 40 30 20 10




99 :- java program to print all unique element in an array

import java.util.Arrays;
class SecondLargestNumber
{
public static void main(String args[])
{
System.out.println("\n Program to find second largest number from the array");
int temp;
int array[] = {10, 20, 25, 63, 96, 57};

for(int i = 0; i< array.length; i++ )
{
for(int j = i+1; j< array.length; j++)
{
if(array[i]>array[j])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
System.out.println("\n Arrays : "+Arrays.toString(array));
System.out.println(" Second largest number is : "+array[array.length-2]);
}
}

Output :-

javac pro93.java
java SecondLargestNumber
Program to find second largest number from the array
Arrays : [10, 20, 25, 57, 63, 96]
Second largest number is : 63




100 :- Write a Java Program to Sort the Array in an Ascending Order

class SortArrayAscOrder
{
public static void main(String args[])
{
System.out.println("\nProgram To sort the array In an Ascending Order.");
int[] arr = {3, 2, 9, 7, 1};
int temp=0;
System.out.println("\nOriginal Array : ");
for(int i = 0; i < arr.length; i++)
{
System.out.print(arr[i]+" ");
}
// sort 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];
arr[j]=temp;
}
}
}
System.out.println("\nSorted Array in Ascending Order : ");
for(int i=0;i < arr.length ;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println(" ");
}
}

Output :-

javac pro100.java
java SortArrayAscOrder
Program To sort the array In an Ascending Order.
Original Array :
3 2 9 7 1
Sorted Array in Ascending Order :
1 2 3 7 9




101 :- Write a Java Program to Sort the Array in an Descending Order

import java.util.Arrays;
import java.util.Collections;

class DescendingOrder
{

public static void main(String[] args)
{
System.out.println("\nProgram to Sort the Array in an Descending Order.\n");
Integer[] arr = {10, 4, 7, 9, 2, 6, 3, 8, 5, 1};
System.out.println("Orginal Array : "+Arrays.toString(arr));
Arrays.sort(arr, Collections.reverseOrder());
System.out.print("Sorted array in descending order is : ");
for (int element : arr) {
System.out.print(element + " ");
}
System.out.println(" ");
}
}

Output :-





102 :- Write a Java Program to Sort Names in an Alphabetical Order

class oneHundredTwo
{
public static void main(String[] args) throws java.io.IOException
{
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.println("\nProgram to Sort Names in an Alphabetical Order.\n ");
System.out.print("Enter the elements of the array : ");
String[] names = input.readLine().toLowerCase().split(" ");

java.util.Arrays.sort(names);

System.out.print("Sorted array in ascending order: ");
for (String name : names)
System.out.print(name + " ");
System.out.println();

} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter valid numbers.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :-





103 :- Write a Java Program to Display Transpose Matrix

class oneHundredThree
{
public static void main(String[] args)
{
System.out.println("\nProgram to Display Transpose Matrix.\n");
int[][] matrix = {{1, 2, 3}, {4, 5, 6}};
int[][] transpose = new int[3][2];
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
transpose[j][i] = matrix[i][j];
}
}
System.out.println("The original matrix is:");
for (int[] row : matrix) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
System.out.println("The transpose matrix is:");
for (int[] row : transpose) {
for (int element : row) {
System.out.print(element + " ");
}
System.out.println();
}
}
}

Output :-





104 :- Write a Java Program to Search Key Elements in an Array

import java.util.Scanner;

class onehunderedFour
{
public static void main(String[] args)
{
System.out.println("\nProgram to Search Key Elements in an Array\n");
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array : ");
int n = sc.nextInt();
int[] arr = new int[n];
System.out.print("Enter the elements of the array : ");
for(int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
System.out.print("Enter the element you want to search : ");
int key = sc.nextInt();
int index = linearSearch(arr, key);
if(index == -1) {
System.out.println("Element not found in the array.");
}
else {
System.out.println("Element found at index " + index + ".");
}
}

public static int linearSearch(int[] arr, int key) {
for(int i = 0; i < arr.length; i++) {
if(arr[i] == key) {
return i;
}
}
return -1;
}
}

Output :-





105 :- Write a Java Program to Accept the Marks of a Student and find Total Marks and Percentage

class oneHundredFive
{
public static void main(String[] args) throws java.io.IOException {
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("\nProgram to Accept the Marks of a Student and find Total Marks and Percentage\n");
System.out.print("\nEnter the number of subjects: ");
int n = Integer.parseInt(input.readLine());

int[] marks = new int[n];
int totalMarks = 0;

for (int i = 0; i < n; i++) {
System.out.print("Enter marks for subject " + (i + 1) + ": ");
marks[i] = Integer.parseInt(input.readLine());
totalMarks += marks[i];
}

double percentage = (double) totalMarks / (n * 100) * 100;

System.out.println("\nTotal Marks: " + totalMarks);
System.out.println("Percentage: " + percentage + "%");
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter valid numbers.");
} catch (Exception e) {
System.out.println("Something went wrong.");
} } }

Output :-





106 :- Write a java program to print numbers from 1 to 10 using loop

class oneHundredSix
{
public static void main(String[] args)
{
System.out.println("\nprint numbers from 1 to 10 using loop\n");
for (int i = 1; i <= 10; i++)
//System.out.println(i + " ");
System.out.println(i);
}
}

Output :-





107 :- Write a java program to calculate the sum of first 10 natural number using loop

class pro107
{
public static void main(String[] args)
{
System.out.println("\nProgram to calculate the sum of first 10 natural number using loop.\n");
int sum = 0;
for (int i = 1; i <= 10; i++) sum += i;
System.out.println("Sum of the first 10 natural numbers: " + sum);
}
}

Output :-





108 :- Write a Java program to print multiplication table of given number

class pro108
{
public static void main(String[] args) throws java.io.IOException {
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("\nProgram to print multiplication table of given number.\n");
System.out.print("Enter a number : ");
int number = Integer.parseInt(input.readLine());

System.out.println("Multiplication table for " + number + ":");
for (int i = 1; i <= 10; i++)
System.out.println(number + " x " + i + " = " + (number * i));

} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :-





109 :- Write a Java program to find the factorial value of any number entered through the keyboard

class pro109
{
public static void main(String[] args) throws java.io.IOException {
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.println("\nProgram to find the factorial value of any number entered through the keyboard.\n");
System.out.print("Enter a number to find its factorial: ");
int number = Integer.parseInt(input.readLine());

if(number >=0){
long factorial = 1;
for(int i = 2; i <= number; i++)
factorial *= i;

System.out.println("Factorial of " + number + " is: " + factorial);
} else {
System.out.println("Cannot calculate factorial for negative number");
}
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :-





110 :- Write a Java program that prompts the user to input an integer and then outputs the number with the digits reversed order

class pro110
{
public static void main(String[] args) throws java.io.IOException {
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.println("\nProgram that prompts the user to input an integer and then outputs the number with the digits reversed order.\n");

System.out.print("Enter an integer: ");
int n = Integer.parseInt(input.readLine());
int reversed = 0;
while (n != 0) {
reversed = (reversed * 10) + (n % 10);
n /= 10;
}
System.out.println("Number with reversed digits: " + reversed);
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid integer.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :-





111 :- Write a Java program that reads a set of integers, and then prints the sum of the even and odd integers using loop

class pro111
{
public static void main(String[] args) throws java.io.IOException
{
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.println("\nProgram that reads a set of integers, and then prints the sum of the even and odd integers using loop.\n");
System.out.print("Enter a set of integers : ");
String[] elements = input.readLine().split(" ");
int evenSum = 0, oddSum = 0;

for (String element : elements) {
int num = Integer.parseInt(element);
if (num % 2 == 0) evenSum += num;
else oddSum += num;
}

System.out.println("Sum of even integers: " + evenSum);
System.out.println("Sum of odd integers: " + oddSum);

} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter valid integers separated by spaces.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :-





112 :- Write a Java program to check whether the number is a prime number or not

class pro112
{
public static void main(String[] args) throws java.io.IOException {
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.println("\nProgram to check whether the number is a prime number or not.\n");
System.out.print("Enter a number to check if it's prime: ");
int number = Integer.parseInt(input.readLine());

if (checkPrime(number)) {
System.out.println(number + " is a prime number.");
} else {
System.out.println(number + " is not a prime number.");
}
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}

public static boolean checkPrime(int n) {
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0) return false;

for (int i = 5; i * i <= n; i += 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
}

Output :-





113 :- Write a Java program to calculate HCF of Two given numbers using loop

class pro113
{
public static void main(String[] args) throws java.io.IOException {
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.println("\nProgram to calculate HCF of Two given numbers using loop.\n"); System.out.print("Enter the first number: ");
int num1 = Integer.parseInt(input.readLine());

System.out.print("Enter the second number: ");
int num2 = Integer.parseInt(input.readLine());

int hcf = calculateHCF(num1, num2);

System.out.println("HCF of " + num1 + " and " + num2 + " is: " + hcf);
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter valid numbers.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}

public static int calculateHCF(int a, int b) {
while (b != 0) {
int temp = b;
b = a % b;
a = temp;
}
return a;
}
}

Output :-





114 :- Write a Java program to enter the numbers till the user wants and at the end it should display the count of positive, negative and zeros

class pro114
{
public static void main(String arg[])throws java.io.IOException
{
System.out.println("\nProgram to enter the numbers till the user wants and at the end it should display the count of positive, negative and zeros.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
int positive=0, negative=0, zeros=0;

Double num;
String a="";
System.out.print("Enter numbers, to quit enter q : ");
a=input.readLine();
String[] numbers = a.split(" ");
for (String numberStr : numbers){
if (numberStr.equals("q")) break;

try{
num= Double.parseDouble(numberStr);
}
catch(java.lang.NumberFormatException e){
continue;
}

if(num< 0) negative++;
else if (num>0) positive++;
else zeros++;
}

System.out.println("The number of positive numbers were = "+positive);
System.out.println("The number of negative numbers were = "+negative);
System.out.println("The number of zeros were = "+zeros);
}
}

Output :-





115 :- Write a Java program to enter the numbers till the user wants and at the end the program should display the largest and smallest numbers entered

class pro115
{
public static void main(String arg[]) throws java.io.IOException
{
System.out.println("\nProgram to enter the numbers till the user wants and at the end the program should display the largest and smallest numbers entered.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
double max = Double.MIN_VALUE, min = Double.MAX_VALUE;

Double num;
String a = "";
System.out.println("Enter numbers, to quit enter q : ");
a = input.readLine();
String[] numbers = a.split(" ");
for (String numberStr : numbers) {
if (numberStr.equals("q"))
break;

try {
num = Double.parseDouble(numberStr);
} catch (java.lang.NumberFormatException e) {
continue;
}

if (num > max) max = num;
if (num < min) min = num;
}

System.out.println("The maximum number was = " + max);
System.out.println("The minimum number was = " + min);
}
}

Output :-





116:- Write a Java program to print out all Armstrong numbers between 1 to 600 using loop

class pro116
{
public static void main(String[] args)
{
System.out.println("\nProgram to print out all Armstrong numbers between 1 to 600 using loop.\n");
System.out.println("Armstrong numbers 1 upto to 600 : ");
for (int number = 1; number <= 600; number++) {
if (isArmstrong(number)) {
System.out.print(number + " ");
}
}
System.out.println();
}

public static boolean isArmstrong(int number) {
int originalNumber, remainder, result = 0;
originalNumber = number;

while (originalNumber != 0) {
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}

return result == number;
}
}

Output :-





117:- Write a java program to count total number of notes in entered amount using loop

class pro117
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram to count total number of notes in entered amount using loop.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter the amount: ");
int amount = Integer.parseInt(input.readLine());

int[] notes = { 2000, 500, 200, 100, 50, 20, 10, 5, 2, 1 };
int[] noteCount = new int[10];
int remainingAmount = amount, index = 0;

while (remainingAmount > 0) {
int currentNote = notes[index];
if (remainingAmount >= currentNote) {
int count = remainingAmount / currentNote;
noteCount[index] = count;
remainingAmount -= count * currentNote;
}
index++;
}

System.out.println("Total number of notes:");
for (int i = 0; i < notes.length; i++) {
if (noteCount[i] > 0) {
System.out.println(notes[i] + " rupees notes: " + noteCount[i]);
}
}
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid amount.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :-





118 :- Write a Java program to print Fibonacci series of n terms where n is input by user using loop

class pro118
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram to print Fibonacci series of n terms where n is input by user using loop.\n");
int num = 0, first = 0, second = 1, next = 0;
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
System.out.print("Enter a number: ");
try {
num = java.lang.Integer.parseInt(reader.readLine());
System.out.println("Fibonnaci series of " + num + " terms is : ");
for (int i = 1; i <= num; i++) {
if(i==1) System.out.print(first + " ");
else if(i==2) System.out.print(second + " ");
else{
next = first + second;
System.out.print(next + " ");
first = second;
second = next;
}
}
System.out.println();
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number.");
}
}
}

Output :-





119 :- Write a java program to calculate the sum of following series where n is input by user

class pro119
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram to calculate the sum of following series where n is input by user.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try{
System.out.print("Enter a number : ");
int n = Integer.parseInt(input.readLine());

int sum = 0;
for(int i=1; i<=n; i++)
sum += i;
System.out.println("Sum of sequence is : " + sum);
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid year.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :-





120 :- Write a Java method to compute the average of three numbers

class pro120
{
public static void main(String[] args)
{
System.out.println("\nProgram method to compute the average of three numbers.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
double sum = 0;
for (int i = 1; i <= 3; i++) {
System.out.print("Enter number " + i + ": ");
double num = Double.parseDouble(input.readLine());
sum += num;
}
System.out.println("Average of 3 numbers : " + sum/3);

} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid year.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :-





121 :- Write a Java method to find the smallest number among three numbers

class pro121
{
public static void main(String[] args)
{
System.out.println("\nProgram method to find the smallest number among three numbers.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter first number : ");
double num1 = Double.parseDouble(input.readLine());
System.out.print("Enter second number : ");
double num2 = Double.parseDouble(input.readLine());
System.out.print("Enter third number : ");
double num3 = Double.parseDouble(input.readLine());
double small = 0;

if(num1 < num2){
if(num1 < num3) small = num1;
else small = num3;
} else {
if(num2 < num3) small = num2;
else small = num3;
}

System.out.println("Smallest number : " + small);

} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid year.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
} }

Output :-





122 :- Write a Java method to count all words in a string

class pro122
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram method to count all words in a string.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter a string: ");
String text = input.readLine();

int wordCount = countWords(text);

System.out.println("Total words in the string: " + wordCount);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}

public static int countWords(String text) {
if (text == null || text.isEmpty()) {
return 0;
}
String[] words = text.split("\\s+");
return words.length;
}
}

Output :-





123 :- Write a Java method to count all vowels in a string

class pro123
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram method to count all vowels in a string.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter a string: ");
String text = input.readLine().toLowerCase();

int vowelCount = countVowels(text);

System.out.println("Total vowels in the string: " + vowelCount);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}

public static int countVowels(String text) {
if (text == null || text.isEmpty()) {
return 0;
}
int count = 0;
for (char c : text.toCharArray()) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
count++;
}
}
return count;
}
}

Output :-





124 :- Write a Java method to compute the sum of the digits in an integer

class pro124
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram method to compute the sum of the digits in an integer.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
int number;

try {
System.out.print("Enter an integer: ");
number = Integer.parseInt(input.readLine());

int sum = 0;
while (number != 0) {
sum += number % 10;
number /= 10;
}
System.out.println("Sum of digits: " + sum);

} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input, please enter a valid binary number.");
} catch (Exception e) {
System.out.println("Something is wrong ");
}
}
}

Output :-





125 :- Write a Java method to check whether an year entered by the user is a leap year or not

class pro125
{
public static void main(String[] args)
{
System.out.println("\nProgram method to check whether an year entered by the user is a leap year or not.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter a year: ");
int year = Integer.parseInt(input.readLine());

if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid year.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :-





126 :- Write a Java method to calculate the area of a triangle

class pro126
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram method to calculate the area of a triangle.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter base of triangle: ");
double base = Double.parseDouble(input.readLine());
System.out.print("Enter height of triangle: ");
double height = Double.parseDouble(input.readLine());

if (base < 0 || height < 0) {
System.out.println("Please enter non-negative values for base and height.");
} else {
double area = 0.5 * base * height;
System.out.println("Area of triangle: " + area);
}
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input, please enter a valid binary number.");
} catch (Exception e) {
System.out.println("Something is wrong ");
}
}
}

Output :-





127 :- Write a Java method to find the area of a pentagon

class pro127
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram method to find the area of a pentagon.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter the side length of the pentagon: ");
double sideLength = Double.parseDouble(input.readLine());

double area = (5.0 / 4.0) * (sideLength * sideLength) / (Math.tan(Math.PI / 5));

System.out.println("Area of the pentagon: " + area);
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number."); } catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :-





128 :- Write a Java method to find number is even number or not

class pro128
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram method to find number is even number or not.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter base of triangle: ");
int num = Integer.parseInt(input.readLine());

if (num%2 == 0) {
System.out.println("Number is even");
} else {
System.out.println("Number is odd");
}
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input, please enter a valid binary number.");
} catch (Exception e) {
System.out.println("Something is wrong ");
}
}
}

Output :-





129 :- Write a Java method to check numbers is palindrome number or not .

import java.io.BufferedReader;
import java.io.InputStreamReader;

class pro129
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram method to check numbers is palindrome number or not.\n");
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

try {
System.out.print("Enter a positive number: ");
int num = Integer.parseInt(input.readLine());

if (num < 0) {
System.out.println("Please enter a positive number.");
} else {
int originalNum = num;
int reversedNum = 0;

while (num != 0) {
int digit = num % 10;
reversedNum = reversedNum * 10 + digit;
num /= 10;
}

if (originalNum == reversedNum) {
System.out.println(originalNum + " is a palindrome.");
} else {
System.out.println(originalNum + " is not a palindrome.");
}
}
} catch (NumberFormatException e) {
System.out.println("Invalid input, please enter valid numbers.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}

Output :-





130 :- Write a Java method to displays prime numbers between 1 to 20

class pro130
{
public static void main(String[] args)
{
System.out.println("\nProgram method to displays prime numbers between 1 to 20.\n");
System.out.println("Prime numbers between 1 and 20:");
for (int i = 2; i <= 20; i++)
if (isPrime(i))
System.out.print(i + " ");
System.out.println();
}

public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}

Output :-





131 :- Write a Java method to find GCD and LCM of Two Numbers

class a
{
public static void hcf(int a ,int b )
{
int i;
i=a>b?a:b;
for(;i>0;--i)
{
if(a%i==0&&b%i==0)
{
System.out.print("\nthe hcf of "+a+" and "+b+" is :- "+i);
break;
}
}

}
public static void lcm(int a,int b)
{
int i;
for(i=(a< b ?b:a);i<=(a*b);i=i+(a< b?b:a))
{
if(i%a==0&&i%b==0)
{
break;
}
}
if(i%a==0&&i%b==0)
{
System.out.print("\nthe lcm of "+a+" and "+b+" is :- "+i);
}
}
public static void main(String arr[])
{
int x,y;
java.util.Scanner s1=new java.util.Scanner(System.in);
System.out.print("\nEnter 1st number :- ");
x=s1.nextInt();
System.out.print("\nEnter 2nd number :- ");
y=s1.nextInt();
hcf(x,y);
lcm(x,y);
}
}

Output :-





132 :- Write a Java method to find factorial using recursion in java

class pro132
{
private static java.util.HashMap track = new java.util.HashMap();

static long fact(int n){
if(track.containsKey(n)) return track.get(n);
long result = n*fact(n-1);
track.put(n, result);
return result;
}
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram method to find factorial using recursion in java.\n");
int num = 0;
track.put(0, (long)1);
track.put(1, (long)1);
java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
System.out.print("Enter a number: ");
try {
num = java.lang.Integer.parseInt(reader.readLine());
long ans = fact(num);
System.out.println("Factorial of " + num + " is " + ans);
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid number.");
}
} }

Output :-





133 :- Write a Java program to reverse an integer number

class pro133
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram to reverse an integer number.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter an integer number: ");
int number = Integer.parseInt(input.readLine());
int reversedNumber = reverseNumber(number);
System.out.println("Reversed number: " + reversedNumber);

} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid integer.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}

public static int reverseNumber(int number) {
int reversedNumber = 0;
while (number != 0) {
int digit = number % 10;
reversedNumber = reversedNumber * 10 + digit;
number /= 10;
}
return reversedNumber;
}
}

Output :-





134 :- Write a Java program to round a float number to specified decimals

class pro134
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nprogram to round a float number to specified decimals.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter a float number: ");
float number = Float.parseFloat(input.readLine());

System.out.print("Enter the number of decimals to round to: ");
int decimals = Integer.parseInt(input.readLine());

float roundedNumber = roundFloat(number, decimals);

System.out.println("Rounded number: " + roundedNumber);
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter valid numbers.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}

public static float roundFloat(float number, int decimals) {
double powerOfTen = Math.pow(10, decimals);
return (float) Math.round(number * powerOfTen) / (float) powerOfTen;
}
}

Output :-





135 :- Write a Java program to test if a double number is an integer

class pro135
{
public static void main(String arg[])throws java.io.IOException
{
System.out.println("\nProgram to test if a double number is an integer.\n");
double a;
int b;
java.io.BufferedReader input = new java.io.BufferedReader (new java.io.InputStreamReader(System.in));
System.out.print("Enter a number ");

try{
a = Double.parseDouble(input.readLine());
b = (int)a;
if(a != b) System.out.println(a + " is not an integer");
else System.out.println(a + " is a integer");
} catch(java.lang.NumberFormatException e){
System.out.println("Invalid input. Please enter a valid number.");
}
}
}

Output :-





136 :- Write a Java program to round up the result of integer division

class pro136
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram to round up the result of integer division.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter the numerator: ");
int numerator = Integer.parseInt(input.readLine());

System.out.print("Enter the denominator: ");
int denominator = Integer.parseInt(input.readLine());

int result = roundUpIntegerDivision(numerator, denominator);

System.out.println("Rounded up result of integer division: " + result);
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter valid integers.");
} catch(java.lang.ArithmeticException e){
System.out.println("Division by zero is not allowed.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}

public static int roundUpIntegerDivision(int numerator, int denominator) {
if (denominator == 0)
throw new java.lang.ArithmeticException();

int result = numerator / denominator;
int remainder = numerator % denominator;

if (remainder != 0)
result++;

return result;
}
}

Output :-





137 :- Write a Java program to convert Roman number to an integer number

class pro137
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram to convert Roman number to an integer number.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter a Roman numeral: ");
String romanNumeral = input.readLine();

int result = romanToInteger(romanNumeral);

System.out.println("Integer value of Roman numeral: " + result);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}

public static int romanToInteger(String romanNumeral) {
int result = 0;

if (romanNumeral == null || romanNumeral.isEmpty()) {
return result;
}

java.util.HashMap < Character, Integer> romanValues = new java.util.HashMap< Character, Integer>();
romanValues.put('I', 1);
romanValues.put('V', 5);
romanValues.put('X', 10);
romanValues.put('L', 50);
romanValues.put('C', 100);
romanValues.put('D', 500);
romanValues.put('M', 1000);

int prevValue = 0;

for (int i = romanNumeral.length() - 1; i >= 0; i--) {
char currentChar = romanNumeral.charAt(i);
int currentValue = romanValues.get(currentChar);

if (currentValue < prevValue) {
result -= currentValue;
} else {
result += currentValue;
}

prevValue = currentValue;
}
return result;
}
}

Output :-





138 :- Write a Java program to convert a float value to absolute value

class pro138
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram to convert a float value to absolute value.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter a float value: ");
float floatValue = Float.parseFloat(input.readLine());

float absoluteValue = convertToAbsoluteValue(floatValue);

System.out.println("Absolute value of the float: " + absoluteValue);
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter a valid float value.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}

public static float convertToAbsoluteValue(float value) {
return Math.abs(value);
}
}

Output :-





139 :- Write a Java program to accept a float value of number and return a rounded float value

class pro139
{
public static void main(String[] args) throws java.io.IOException {
System.out.println("\nProgram to accept a float value of number and return a rounded float value.\n");
java.io.BufferedReader input = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));

try {
System.out.print("Enter a float value: ");
float floatValue = Float.parseFloat(input.readLine());

System.out.print("Enter the number of decimals to round to: ");
int decimals = Integer.parseInt(input.readLine());

float roundedValue = roundFloatValue(floatValue, decimals);

System.out.println("Rounded float value: " + roundedValue);
} catch (java.lang.NumberFormatException e) {
System.out.println("Invalid input. Please enter valid numbers.");
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}

public static float roundFloatValue(float value, int decimals) {
double powerOfTen = Math.pow(10, decimals);
return (float) Math.round(value * powerOfTen) / (float) powerOfTen;
}
}

Output :-