Header Ads Widget

Miscellaneous JAVA program

 1. Generate a Random number


import java.util.*;

public class JavaRandomNumber {
public static void main(String[] args) {
int counter;
Random randomNumber = new Random();

// Below code would generate 5 random numbers between 0 and 500.

System.out.println("Random Numbers:");
System.out.println("----------------");
for (counter = 1; counter <= 5; counter++) {
System.out.println(randomNumber.nextInt(500));
}
}
}


Output :-



Random Numbers:
----------------
417
200
368
304
228



2. Calculator in JAVA


import java.util.*;

public class JavaCalculatorExample {
public static void main(String []args){
         int a,b,choice;
         float result=0;

         Scanner scanner=new Scanner(System.in); 
          
         System.out.print("Enter first number: ");
         a=scanner.nextInt();
         System.out.print("Enter second number: ");
         b=scanner.nextInt();
          
         System.out.print("\n1: Addition.\n2: Subtraction.");
         System.out.print("\n3: Multiplication.\n4: Divide.");
         System.out.print("\n5: Remainder.\n6: Exit.");
          
         System.out.print("\nEnter your choice: ");
         choice=scanner.nextInt();
          
         switch(choice)
         {
             case 1:
                 result=(a+b); break;
             case 2:
                 result=(a-b); break;
             case 3:
                 result=(a*b); break;
             case 4:
                 result=(float)((float)a/(float)b); break;
             case 5:
                 result=(a%b); break;
             default:
                 System.out.println("An Invalid Choice!!!\n");
         }
         if(choice>=1 && choice<=5)
            System.out.println("Result is: " + result);
          
     }
}


Output :-


Enter first number: 20
Enter second number: 20

1: Addition.
2: Subtraction.
3: Multiplication.
4: Divide.
5: Remainder.
6: Exit.
Enter your choice: 3
Result is: 400.0



3. Binary Search in JAVA


import java.util.Scanner;

public class JavaBinarySearch {
public static void main(String args[]) {
int c, first, last, middle, n, search, array[];

Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];

System.out.println("Enter " + n + " integers");

for (c = 0; c < n; c++)
array[c] = in.nextInt();

System.out.println("Enter value to find");
search = in.nextInt();

first = 0;
last = n - 1;
middle = (first + last) / 2;

while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
} else
last = middle - 1;

middle = (first + last) / 2;
}
if (first > last)
System.out.println(search + " is not present in the list.\n");
}
}


Output :-


Enter number of elements:
5
Enter 5 integers
20
21
22
23
24
Enter value to find:
23
found at location 4.



4. Multiplication Table in JAVA


import java.util.Scanner;

public class JavaMultiplicationTable {
public static void main(String args[]) {
int n, c;
System.out.println("Enter an integer to print it's multiplication table");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.println("Multiplication table of " + n + " is :-");

for (c = 1; c <= 10; c++)
System.out.println(n + "*" + c + " = " + (n * c));
}
}


Output :-



Enter an integer to print it's multiplication table: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



5. Garbage Collection in JAVA


import java.util.*;
class GarbageCollection {
public static void main(String s[]) throws Exception {
Runtime rs =  Runtime.getRuntime();
System.out.println("Free memory in JVM before Garbage Collection = "+rs.freeMemory());
rs.gc();
System.out.println("Free memory in JVM after Garbage Collection = "+rs.freeMemory());
}
}


Output :-


Free memory in JVM before Garbage Collection = 15347864
Free memory in JVM after Garbage Collection = 15627664


Note :- This numbers are different in your pc, because it depends on pc information.



6. Heart Shape JAVA


public class Heart {

     public static void  main(String[] args) {
           int n = Integer.parseInt(args[0]);
           for ( int i = -3*n/2; i<= n; i++) {
                for (int j = -3*n/2; j <= 3*n/2; j++) {

                     if ((Math.abs(i) + Math.abs(j) < n)
                        || ((-n/2-i) * (-n/2-i) + ( n/2-j) * ( n/2-j) <= n*n/2)
                        || ((-n/2-i) * (-n/2-i) + (-n/2-j) * (-n/2-j) <= n*n/2)) {
                        System.out.print("*");
                    }
                    else {
                           System.out.print("*");
                    }
             }
             System.out.println();
       }
    }
}



Note :- This will print HEART SHAPE in your Java Compiler.



7. ASCII Value in JAVA


import java.util.Scanner;  

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

System.out.print("Enter a character: ");  
Scanner sc = new Scanner(System.in);  

char chr = sc.next().charAt(0);  
int asciiValue = chr;  
System.out.println("ASCII value of " +chr+ " is: "+asciiValue);  
}  
}  


Output :-


Enter a character: P
ASCII value of P is: 80



8. Fibonacci Series


import java.util.Scanner;

public class FibonacciSeries{
    public static void main(String args[]) {
        System.out.print("Enter the number : ");
Scanner in=new Scanner(System.in);
        int num=in.nextInt();
        System.out.println("\n\nFibonacci series upto " + num+" numbers : ");
        for(int i=1; i<=num; i++){
            System.out.print(fibonacciMethod(i) +" ");
        }
    } 
    public static int fibonacciMethod(int num){
        if(num== 1 || num== 2){
            return 1;
        }
        return fibonacciMethod(num-1) + fibonacciMethod(num-2);
    }
    public static int fibonacciLoop(int num){
        if(num == 1 || num == 2){
            return 1;
        }
        int num1=1, num2=1, fibonacci=1;
        for(int i= 3; i<= num; i++){
            fibonacci = num1 + num2;
            num1 = num2;
            num2 = fibonacci;
 
        }
        return fibonacci; 
    }     
}


Output :-


 
Enter the number : 7


Fibonacci series upto 7 numbers :
1 1 2 3 5 8 13



9. Sum of all digits between 0 to 1000


import java.util.Scanner;
public class Main {

    public static void main(String[] Strings) {

        Scanner input = new Scanner(System.in);

        System.out.print("Input an integer between 0 and 1000: ");
        int num = input.nextInt();

        int firstDigit = num % 10;
        int remainingNumber = num / 10;
        int SecondDigit = remainingNumber % 10;
        remainingNumber = remainingNumber / 10;
        int thirdDigit = remainingNumber % 10;
        remainingNumber = remainingNumber / 10;
        int fourthDigit = remainingNumber % 10;
        int sum = thirdDigit + SecondDigit + firstDigit + fourthDigit;
        System.out.println("The sum of all digits in " + num + " is " + sum);

    }
}


Output :-



Input an integer between 0 and 1000: 962
The sum of all digits in 962 is 17


10. Number of years and days for the minutes


import java.util.Scanner;
public class Exercise4 {

    public static void main(String[] Strings) {


        double minutesInYear = 60 * 24 * 365;

        Scanner input = new Scanner(System.in);

        System.out.print("Input the number of minutes: ");

        double min = input.nextDouble();

        long years = (long) (min / minutesInYear);
        int days = (int) (min / 60 / 24) % 365;

        System.out.println((int) min + " minutes is approximately " + years + " years and " + days + " days");
    }
}


Output :-



Input the number of minutes: 269413
minutes is approximately 0 years and 187 days



11. Calculate BMI of body


import java.util.Scanner;
public class Exercise6 {

    public static void main(String[] Strings) {

        Scanner input = new Scanner(System.in);

        System.out.print("Input weight in pounds: ");
        double weight = input.nextDouble();

        System.out.print("Input height in inches: ");
        double inches = input.nextDouble();

        double BMI = weight * 0.45359237 / (inches * 0.0254 * inches * 0.0254);
        System.out.print("Body Mass Index is " + BMI+"\n");
    }
}


Output :-


Input weight in pounds: 552
Input height in inches: 72
Body Mass Index is 74.86389042454012



12. Calculate speed in meter, kilometer and mile


import java.util.Scanner;
public class Exercise7 {

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

float timeSeconds;
float mps,kph, mph;

System.out.print("Input distance in meters: ");
float distance = scanner.nextFloat();

System.out.print("Input hour: ");
float hr = scanner.nextFloat();

System.out.print("Input minutes: ");
float min = scanner.nextFloat();

System.out.print("Input seconds: ");
float sec = scanner.nextFloat();

timeSeconds = (hr*3600) + (min*60) + sec;
mps = distance / timeSeconds;
kph = ( distance/1000.0f ) / ( timeSeconds/3600.0f );
mph = kph / 1.609f;

System.out.println("Your speed in meters/second is "+mps);
System.out.println("Your speed in km/h is "+kph);
System.out.println("Your speed in miles/h is "+mph);

scanner.close();
}
}


Output :-


Input distance in meters: 2500
Input hour: 4
Input minutes: 50
Input seconds: 25
Your speed in meters/second is 0.14347202
Your speed in km/h is 0.5164993
Your speed in miles/h is 0.3210064



13. Calculate different mathematical terms


import java.util.Scanner;
public class Exercise9 {

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Input 1st integer: ");
        int firstInt = in.nextInt();
        System.out.print("Input 2nd integer: ");
        int secondInt = in.nextInt();

        System.out.printf("Sum of two integers: %d%n", firstInt + secondInt);
        System.out.printf("Difference of two integers: %d%n", firstInt - secondInt);
        System.out.printf("Product of two integers: %d%n", firstInt * secondInt);
        System.out.printf("Average of two integers: %.2f%n", (double) (firstInt + secondInt) / 2);
        System.out.printf("Distance of two integers: %d%n", Math.abs(firstInt - secondInt));
        System.out.printf("Max integer: %d%n", Math.max(firstInt, secondInt));
        System.out.printf("Min integer: %d%n", Math.min(firstInt, secondInt));
    }
}


Output :-



Input 1st integer: 40
Input 2nd integer: 20
Sum of two integers: 60
Difference of two integers: 20
Product of two integers: 800
Average of two integers: 30.00
Distance of two integers: 20
Max integer: 40
Min integer: 20




Post a Comment

0 Comments