45 Java Programming Exercises With Solutions


If you have learned the basics of Java, it is the right time to solve some practice problems. Practicing and solving problems will help you master the Java programming language and take your skills to the next level.

In this post, I have put together some Java coding problems that you can use for practice. I have also provided the Java code solutions and the corresponding output for your reference.

Try to solve these problems by yourself and get better at Java. Let’s dive right in.

Java Programming Exercises With Solutions

1. Java program to check whether the given number is even or odd

import java.util.Scanner;

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

    System.out.println("Enter a number: ");
    Scanner sc = new Scanner(System.in);
    int number =Integer.parseInt(sc.nextLine());
    int x = number%2;
    
    if(x==0){
      System.out.println("The number is Even");
    }
    else{
      System.out.println("The number is Odd");
    }
    
  }
}

Output:

2. Java program to convert the temperature in Degree Centigrade to Fahrenheit

import java.util.Scanner;

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

    System.out.println("Enter temperature in Centigrade: ");
    Scanner sc = new Scanner(System.in);
    int c =Integer.parseInt(sc.nextLine());
    float f = ((9*c)/5)+32;
    
    System.out.println("Temperature in Fahrenheit is: "+f);
    
  }
}

Output:

3. Java program to find the area of a triangle whose three sides are given

import java.util.Scanner;

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

    Scanner sc= new Scanner(System.in);
        
         System.out.println("Enter the 1st side:");
         int a= sc.nextInt();
 
         System.out.println("Enter the 2nd side:");
          int b= sc.nextInt();
 
         System.out.println("Enter the 3rd side:");
         int c= sc.nextInt();
    
         if((a+b)>c && (a+c)>b && (b+c)>a)
          {
            double s=(a+b+c)/2.0;
            double area=Math.sqrt(s*(s-a)*(s-b)*(s-c));
            System.out.println("Area of Triangle is: " + area);    
           }
         else  
           System.out.println("Area of the triangle does not exist");
    
  }
}

Output:

4. Java program to find out the average of a set of integers

import java.util.Scanner;

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

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the count of numbers: ");
    float count = Integer.parseInt(sc.nextLine());
    int i = 0;
    float sum = 0;
    for(i=0;i<count;i++){
      System.out.println("Enter an integer: ");
      int x = Integer.parseInt(sc.nextLine());
      sum = sum + x;
    }
  
    float avg = sum/count;
    System.out.println("The average is: "+avg);
    
  }
}

Output:

5. Java program to find the product of a set of real numbers

import java.util.Scanner;

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

    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the number of real numbers: ");
    float count = Integer.parseInt(sc.nextLine());
    int i = 0;
    float product = 1.0f;
    for(i=0;i<count;i++){
      System.out.println("Enter a real number: ");
      float x = Float.parseFloat(sc.nextLine());
      product = product * x;
    }
  
    System.out.println("The product of the numbers is: "+product);
    
  }
}

Output:

6. Java program to find the circumference and area of a circle with a given radius

import java.util.Scanner;

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

    Scanner sc = new Scanner(System.in);
    System.out.println("Input the radius of the circle: ");
    double radius = Float.parseFloat(sc.nextLine());

    double c = 2 * Math.PI * radius;
    double area = Math.PI * radius * radius;
    
    System.out.println("The circumference of the circle is: "+c);
    System.out.println("The area of the circle is: "+area);
    
  }
}

7. Java program to check whether the given integer is a multiple of 5

import java.util.Scanner;

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

    System.out.println("Enter an integer: ");
    Scanner sc = new Scanner(System.in);
    int number =Integer.parseInt(sc.nextLine());
    
    if(number%5==0){
      System.out.println(number+" is a multiple of 5");
    }
    else{
      System.out.println(number+" is not a multiple of 5");
    }
    
  }
}

Output:

8. Java program to check whether the given integer is a multiple of both 5 and 7

import java.util.Scanner;

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

    System.out.println("Enter an integer: ");
    Scanner sc = new Scanner(System.in);
    int number =Integer.parseInt(sc.nextLine());
    
    if((number%5==0)&&(number%7==0)){
      System.out.println(number+" is a multiple of both 5 and 7");
    }
    else{
      System.out.println(number+" is not a multiple of both 5 and 7");
    }
    
  }
}

Output:

9. Java program to find the average of 5 numbers using while loop

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    
    int count = 0;
    int sum = 0;
    Scanner sc = new Scanner(System.in);
    while(count<5){
      System.out.println("Enter an integer: ");
      int number =Integer.parseInt(sc.nextLine());
      sum = sum+number;
      count++;
      }
    
double avg = ((double) sum) / 5.0;
System.out.println("Average is :"+avg);
    
  }
}

10. Java program to display the given integer in reverse manner

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter an integer: ");
    int number =Integer.parseInt(sc.nextLine());
    int rev = 0;
    
    while(number!=0){
      int digit = number%10;
      rev = (rev*10)+digit;
      number = number/10;
      }
    
System.out.println(rev);
    
  }
}

Output:

11. Java program to find the geometric mean of n numbers

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    int c = 0;
    double p = 1.0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the number of values: ");
    int count =Integer.parseInt(sc.nextLine());
    
    while((c<count)){
      System.out.println("Enter a real number: ");
      double x =Double.parseDouble(sc.nextLine());
      c = c+1;
      p = p * x;
      }
    double gm = Math.pow(p,1.0/count);
    System.out.println("The geometric mean is: "+gm);
    
  }
}

Output:

12. Java program to find the sum of the digits of an integer using while loop

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    int sum = 0;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter an integer: ");
    int number =Integer.parseInt(sc.nextLine());
    
    while(number!=0){
      int digit = number%10;
      sum = sum+digit;
      number = number/10;
    }
    
    System.out.println(("Sum of digits is: "+ sum));
    
  }
}

Output:

13. Java program to display all the multiples of 3 within the range 10 to 50

import java.util.Scanner;

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

    for(int i=10;i<50;i++){
      if(i%3==0)
        System.out.println(i);
    }
    
  }
}

Output:

14. Java program to display all integers within the range 100-150 whose sum of digits is an even number

import java.util.Scanner;

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

    for(int i=100;i<150;i++){
      int num = i;
      int sum = 0;
      while(num!=0){
        int digit = num%10;
        sum = sum + digit;
        num = num/10;
      }
      if(sum%2==0){
          System.out.println(i);
        }
    }
    
  }
}

Output:

15. Java program to check whether the given integer is a prime number or not

import java.util.Scanner;

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

    System.out.println("Enter an integer greater than 1: ");
    Scanner sc = new Scanner(System.in);
    int number =Integer.parseInt(sc.nextLine());

    int isprime = 1;

    for(int i=2;i<(number/2);i++){
      if(number%i==0){
        isprime = 0;
        break;
      }
    }
    
    if(isprime==1){
      System.out.println(number+" is a prime number");
    }
    else{
      System.out.println(number+" is not a prime number");
    }
    
  }
}

Output:

16. Java program to generate the prime numbers from 1 to N

import java.util.Scanner;

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

    System.out.println("Enter the range: ");
    Scanner sc = new Scanner(System.in);
    int number =Integer.parseInt(sc.nextLine());

    for (int num = 2; num <= number; num++)
        {
            boolean isPrime = true;
            for (int i=2; i <= num/2; i++)
            {
                if ( num % i == 0)
                {
                    isPrime = false;
                    break;
                }
            }
 
            if ( isPrime == true )
                System.out.println(num);
        }
    
  }
}

Output:

17. Java program to find the roots of a quadratic equation

import java.util.Scanner;

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

    System.out.println("Enter the first coefficient: ");
    Scanner sc = new Scanner(System.in);
    double a = Integer.parseInt(sc.nextLine());
    System.out.println("Enter the second coefficient: ");
    double b = Integer.parseInt(sc.nextLine());
    System.out.println("Enter the third coefficient: ");
    double c = Integer.parseInt(sc.nextLine());

    if(a!=0.0){
      double d = (b*b)-(4*a*c);
      if (d==0.0){
        System.out.println("The roots are real and equal.");
        double r = -b/(2*a);
        System.out.println("The roots are "+ r+"and"+ r);
      }else if(d>0.0){
        System.out.println("The roots are real and distinct.");
        double r1 = (-b+(Math.sqrt(d)))/(2*a);
        double r2 = (-b-(Math.sqrt(d)))/(2*a);
        System.out.println("The root1 is: "+ r1);
        System.out.println("The root2 is: "+ r2);
      }else{
        System.out.println("The roots are imaginary.");
        double rp = -b/(2*a);
        double ip = Math.sqrt(-d)/(2*a);
        System.out.println("The root1 is: "+ rp+ "+ i"+ip);
        System.out.println("The root2 is: "+ rp+ "- i"+ip);
      }   
    }else{
      System.out.println("Not a quadratic equation.");
    }
  }
}

Output:

18. Java program to print the numbers from a given number n till 0 using recursion

class Main {
  public static void main(String[] args) {
    print_till_zero(8);
    
  }

  public static void print_till_zero(int n){
      if(n==0)
        return;
      System.out.println(n);
      n=n-1;
      print_till_zero(n);
    }
}

Output:

19. Java program to find the factorial of a number using recursion

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    
    System.out.println("Enter an integer:  ");
    Scanner sc = new Scanner(System.in);
    int a = Integer.parseInt(sc.nextLine());
    int result = fact(a);
    System.out.println("The factorial of"+ a + " is: "+ result);
    
  }

  public static int fact(int n){
    int f;
    if(n==1)
      f=1;
    else
      f = n * fact(n-1);
    return f;
    }
}

Output:

20. Java program to display the sum of n numbers using an array

import java.util.Scanner;

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

    System.out.println("How many numbers: ");
    Scanner sc = new Scanner(System.in);
    int num = Integer.parseInt(sc.nextLine());
    int[] numbers = new int[num];
    int sum=0;
    
    for(int n=0;n<num;n++){
      System.out.println("Enter number: ");
      int x = Integer.parseInt(sc.nextLine());
      numbers[n] = x;
    }

    for(int i = 0; i < numbers.length; i++) {  
        sum = sum + numbers[i];  
      }  
    System.out.println("Sum of all the elements of the array: " + sum);  
    
  }
}

21. Java program to implement linear search

import java.util.Scanner;

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

    int[] numbers = {4,2,7,1,8,3,6};
    int flag = 0;
    
    System.out.println("Enter the number to be found out: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());
    
    for(int i=0;i<numbers.length;i++){
      if (x==numbers[i]){
        System.out.println("Successful search, the element is found at position "+ i);
        flag = 1;
        break;
      }
    }

    if(flag==0){
      System.out.println("Oops! Search unsuccessful");
    }
    
  }
}

Output:

22. Java program to implement binary search

import java.util.Scanner;

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

    int[] numbers = {1,4,6,7,12,17,25}; //binary search requires sorted numbers
    System.out.println("Enter the number to be found out: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());

    int result = binarySearch(numbers, 0, numbers.length-1, x);
    if (result != -1)
      System.out.println("Search successful, element found at position "+result);
    else
      System.out.println("The given element is not present in the array");
    
  }

  public static int binarySearch(int[] numbers,int low,int high,int x){
    if (high >= low){
      int mid = low + (high - low)/2;
      if (numbers[mid] == x)
        return mid;
      else if (numbers[mid] > x)
        return binarySearch(numbers, low, mid-1, x);
      else
        return binarySearch(numbers, mid+1, high, x);
    }else{
      return -1;
    }
        
        
  }
}

Output:

23. Java program to find the number of odd numbers in an array

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

    int[] numbers = {8,3,1,6,2,4,5,9};
    int count = 0;

    for(int i=0;i<numbers.length;i++){
      if(numbers[i]%2!=0)
        count++;
    }
   System.out.println("The number of odd numbers in the list are: "+count);      
        
  }
}

Output:

24. Java program to find the largest number in an array without using built-in functions

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

    int[] numbers = {3,8,1,7,2,9,5,4};
    int largest = numbers[0];
    int position = 0;

    for(int i=0;i<numbers.length;i++){
      if(numbers[i]>largest){
        largest = numbers[i];
        position = i;
      }
    }

   System.out.println("The largest element is "+largest+" which is found at position "+position);      
        
  }
}

Output:

25. Java program to insert a number to any position in an array

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

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

    int[] numbers = {3,4,1,9,6,2,8};
    System.out.println(Arrays.toString(numbers));

    System.out.println("Enter the number to be inserted: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());
    System.out.println("Enter the position: ");
    int y = Integer.parseInt(sc.nextLine());

    for(int i=numbers.length-1;i>y;i--){
        numbers[i] = numbers[i-1];
    }
    numbers[y] = x;

   System.out.println(Arrays.toString(numbers));   
        
  }
}

Output:

26. Java program to delete an element from an array by index

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

import java.util.ArrayList; 

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

    ArrayList<Integer> numbers = new ArrayList<Integer>(5); 
    numbers.add(3);
    numbers.add(7);
    numbers.add(1);
    numbers.add(4);
    
    System.out.println(numbers);

    System.out.println("Enter the position of the element to be deleted: ");
    Scanner sc = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());

    numbers.remove(x);

   System.out.println(numbers);   
        
  }
}

Output:

27. Java program to check whether a string is palindrome or not

import java.util.Scanner;  

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

    String a, b = "";
    Scanner s = new Scanner(System.in);
    System.out.print("Enter the string you want to check: ");
    a = s.nextLine();
    
    int n = a.length();
    for(int i = n - 1; i >= 0; i--){
        b = b + a.charAt(i);
    }
    
    if(a.equalsIgnoreCase(b)){
      System.out.println("The string is palindrome.");
    }else{
      System.out.println("The string is not palindrome.");
    }
    
  }
}

Output:

28. Java program to implement matrix addition

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

    //creating two matrices    
    int a[][]={{8,5,1},{9,3,2},{4,6,3}};    
    int b[][]={{8,5,3},{9,5,7},{9,4,1}};    
    
    //matrix to store the sum of two matrices    
    int c[][]=new int[3][3];  //3 rows and 3 columns  
    
    //adding 2 matrices    
    for(int i=0;i<3;i++){    
      for(int j=0;j<3;j++){    
        c[i][j]=a[i][j]+b[i][j];
        System.out.print(c[i][j]+" ");    
      }
      System.out.print("\n"); 
    }    
    
  }
}

Output:

29. Java program to implement matrix multiplication

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

    //creating two matrices    
    int a[][]={{8,5,1},{9,3,2},{4,6,3}};    
    int b[][]={{8,5,3},{9,5,7},{9,4,1}};    
    
    //matrix to store the product of two matrices    
    int c[][]=new int[3][3];
    
    //multiplying 2 matrices
    for(int i=0;i<3;i++){    
      for(int j=0;j<3;j++){    
        c[i][j]=0;      
        for(int k=0;k<3;k++){      
          c[i][j]+=a[i][k]*b[k][j];      
        }
        System.out.print(c[i][j]+" ");
      }
      System.out.print("\n"); 
    }    
    
  }
}

Output:

30. Java program to check leap year

import java.util.Scanner;  

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

    Scanner sc = new Scanner(System.in);
    System.out.print("Enter the year you want to check: ");
    int year = Integer.parseInt(sc.nextLine()); 
    boolean leap = false;
    
    // if the year is divided by 4
    if (year % 4 == 0) {
      // if the year is century
      if (year % 100 == 0) {
        // if year is divided by 400, then it is a leap year
        if (year % 400 == 0)
          leap = true;
        else
          leap = false;
      }
      // if the year is not century
      else
        leap = true;
    }
    else
      leap = false;

    if (leap)
      System.out.println(year + " is a leap year.");
    else
      System.out.println(year + " is not a leap year.");
    
  }
}

Output:

31. Java program to find the Nth term in a Fibonacci series using recursion

import java.util.Scanner;  

class Main {
  public static void main(String[] args) {
    Scanner cs=new Scanner(System.in);
    int n;
		System.out.print("Enter the position(N): ");
		n=cs.nextInt();
		System.out.print("Nth Fibonacci Number is: "+NthFibonacciNumber(n));
  }

  static int NthFibonacciNumber(int n){
	    if(n==1)
	        return 0;
	    else if(n==2)
	        return 1;
	    else
	        return NthFibonacciNumber(n-1)+NthFibonacciNumber(n-2);
	}
  
}

Output:

32. Java program to print Fibonacci series using iteration

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    int n1=0,n2=1;
    Scanner cs=new Scanner(System.in);
		System.out.print("Enter the number of terms in the sequence: ");
		int count = cs.nextInt(); 
    int n3,i;
    
    System.out.print(n1+" "+n2);//printing 0 and 1
    //printing from 2 because 0 and 1 are already printed  
    for(i=2;i<count;++i){
      n3=n1+n2;    
      System.out.print(" "+n3);    
      n1=n2;    
      n2=n3;
      }    
	
    }
}

Output:

33. Java program to implement a calculator to do basic operations

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
      int firstNumber, secondNumber, opt, add, sub, mul;
      double div;
      Scanner s = new Scanner(System.in);
      System.out.print("Enter first number: ");
      firstNumber = s.nextInt();
      System.out.print("Enter second number: ");
      secondNumber = s.nextInt();
      
      while(true){
        System.out.println("Enter 1 for addition");
        System.out.println("Enter 2 for subtraction");
        System.out.println("Enter 3 for multiplication");
        System.out.println("Enter 4 for division");
        System.out.println("Enter 5 to Exit");
        int option = s.nextInt();
        switch(option){
          case 1:
            add = firstNumber + secondNumber;
            System.out.println("Result:"+add);
            break;
 
          case 2:
            sub = firstNumber - secondNumber;
            System.out.println("Result:"+sub);
            break;
 
          case 3:
            mul = firstNumber * secondNumber;
            System.out.println("Result:"+mul);
            break;
 
          case 4:
            div = (double)firstNumber / secondNumber;
            System.out.println("Result:"+div);
            break;    
 
          case 5:
            System.exit(0);
            
            }
        }
	
    }
}

Output:

34. Java Program to Find Your Weight on Mars

Mars’ gravity is about 38% of Earth’s. Write a program that will calculate your weight on Mars.

  • Declare all variables at the top of the class.
  • Initial variables are to be of float type.
  • After making the calculations, assign the result to a new variable, this time of the double type.
  • After assigning the assignment, write the variable double to the console, limiting its length to 4 decimal places.
  • Cast the above variable of double type to a new variable of int type.
  • Cast the above variable of type int to a new variable of type char.
  • Do any math operation on this variable char type and assign the value of this activity to the new variable int type.
  • Each of the above actions should be written to the console, adding some text explaining what has been done.
import java.util.Scanner;  

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

  Scanner input = new Scanner(System.in);
  System.out.print("How many pounds (lbs) do you weigh? ") ;
  float weight = input.nextFloat();

  // computing the weight on mars
  double weightOnMars = (weight * .38);

  // displaying results with 4 decimal places
  System.out.println("Your weight is "+String.format("%.4f",weightOnMars)+" lbs on Mars");

    System.out.println("Converting the variable into integer");
    int weightOnMarsInt = (int)weightOnMars;
    System.out.println(weightOnMarsInt);

    System.out.println("Converting the variable into char");
    char weightOnMarsChar = (char)weightOnMars;
    System.out.println(weightOnMarsChar);

    System.out.println("Converting the variable into Int and doing an operation on it");
    int newIntVariable = weightOnMarsChar * 2;
    System.out.println(newIntVariable);
    
  }
}

Output:

35. Java Program to Check Whether the Generated Random Number Is Even or Odd

Write a program that generates a random number between 1 and 100 (you can use the Random () method from the Math class.

In the next step check whether it is an even or an odd number. Each of the above actions should be written to the console.

import java.util.Random;

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

    int min = 1;
    int max = 100;

    //Generating a random number
    Random r = new Random();
    int randomNumber = min + r.nextInt(max);
    System.out.println("Generated random number is: "+randomNumber);

    //Checking whether the number is odd or even

    if(randomNumber%2==0){
      System.out.println("The generated random number is even.");
    }else{
      System.out.println("The generated random number is odd.");
    }
        
  }
}

Output:

36. Java Program to Find the Number of Containers You Need

Choose an odd number between 50 and 100 and save it as an int variable telling us how many Lego bricks we have (e.g. amountOfBricks ), then select an even number between 5 and 10 stating how many Lego blocks fit in one container (e.g.: containerCapacity ) and save it as an int variable as well.

Write a program that will calculate how many full containers we have, how many containers, in general, are full and not full, and how many blocks are in the container that is not completely full (use the modulo operator for this).

import java.util.Scanner;

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

    Scanner sc = new Scanner(System.in);
    System.out.println("How many Lego bricks do we have? Choose an odd number between 50 and 100: ");
    int amountOfBricks = Integer.parseInt(sc.nextLine());

    System.out.println("How many Lego blocks fit in one container? Choose an even number between 5 and 10: ");
    int containerCapacity = Integer.parseInt(sc.nextLine());

    int noOfFullContainers = amountOfBricks/containerCapacity;
    int noOfTotalContainers;

    int noOfBlocksInNotFullContainers = amountOfBricks%containerCapacity;

    if(noOfBlocksInNotFullContainers!=0){
      noOfTotalContainers = noOfFullContainers + 1;
    }else{
      noOfTotalContainers = noOfFullContainers;
    }
    
    System.out.println("No of full containers we have: "+noOfFullContainers);
    System.out.println("No of total containers we have: "+noOfTotalContainers);
    System.out.println("No of blocks in the container that is not completely full: "+noOfBlocksInNotFullContainers);
        
  }
}

37. Java Program to Calculate Taxes

Using the double types, implement the following: Suppose a product costs 9.99 net, calculate its gross value (we assume VAT of 23%). Then multiply it by 10,000 (i.e., we sold 10,000 pcs of this product), and calculate this value excluding VAT.

Implement the above actions using the Big Decimal class. Print on the console all computed values and compare their values. What conclusions do you have?

import java.math.BigDecimal;    

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

    double netValue = 9.99;
    double VAT = 23.0;

    //calculating grossValue
    double grossValue = netValue + (VAT*netValue/100);
    System.out.println("The gross value is: "+grossValue);

    // multiplying the value by 10000
    double grossValue10000 = grossValue * 10000;
    System.out.println("The gross value for 10000 units is: "+grossValue10000);

    // calculating price excluding VAT 23%
    double excludingVAT = grossValue10000 - (VAT*grossValue10000/100);
    System.out.println("The value for 10000 units excluding VAT is: "+excludingVAT);

    // doing the same operations using BigDecimal instead of double
     System.out.println("\n----Using BigDecimal instead of double----\n");
       
    BigDecimal netValue_big = new BigDecimal("9.99");
    BigDecimal VAT_big = new BigDecimal("23.0");
    BigDecimal HUNDRED = new BigDecimal("100");
    BigDecimal TenThousand = new BigDecimal("10000");

    //calculating grossValue
    BigDecimal grossValue_big = netValue_big.add(VAT_big.multiply(netValue_big.divide(HUNDRED)));
    System.out.println("The gross value is: "+grossValue_big);
    
    // multiplying the value by 10000
    BigDecimal grossValue10000_big = grossValue_big.multiply(TenThousand);
    System.out.println("The gross value for 10000 units is: "+grossValue10000_big);
    
    // calculating price excluding VAT 23%
    BigDecimal excludingVAT_big = grossValue10000_big.subtract(VAT_big.multiply(grossValue10000_big.divide(HUNDRED)));
    System.out.println("The value for 10000 units excluding VAT is: "+excludingVAT_big);


  System.out.println("\nThe accuracy is higher when we use BigDecimal instead of double");
    
  }
}

Output:

38. Calculate BMI Using Java

The user enters his height and weight. The variables passed by the user are assigned to the float type. After calculating the BMI value, the value will be assigned to the appropriate range and the correct message will appear on the console. You can use the if-else-if ladder for printing the message on the console.

Intervals of BMI index:

  • 16.00 or less = starvation
  • 16.00-16.99 = emaciation
  • 17.00-18.49 = underweight
  • 18.50-22.99 = normal, low range
  • 23.00-24.99 = normal high range
  • 25.00-27.49 = overweight low range
  • 27.50-29.99 = overweight high range
  • 30.00-34.90 = 1st degree obesity
  • 35.00-39.99 = 2nd degree obesity
  • 40.00 or above = 3rd degree obesity
import java.util.Scanner;

class Main {
  public static void main(String[] args) {
    float height, weight, bmi;
    Scanner s = new Scanner(System.in);
    System.out.println("Enter the height (in inches): ");
    height = s.nextFloat();
    System.out.println("Enter the weight (in pounds): ");
    weight = s.nextFloat();
    bmi = (float)(weight / Math.pow(height, 2) * 703);

    System.out.println("The BMI is: "+bmi);

    if(bmi<16.00)
      System.out.println("starvation");
    else if(bmi>=16.00 && bmi <= 16.99)
      System.out.println("emaciation");
    else if(bmi>=17.00 && bmi <= 18.49)
      System.out.println("underweight");
    else if(bmi>=18.50 && bmi<=22.99)
      System.out.println("normal, low range");
    else if(bmi>=23.00 && bmi<=24.99)
      System.out.println("normal, high range");
    else if(bmi>=25.00 && bmi<=27.49)
      System.out.println("overweight, low range");
    else if(bmi>=27.50 && bmi<=29.99)
      System.out.println("overweight, high range");
    else if(bmi>=30.00 && bmi<=34.9)
      System.out.println("1st degree obesity");
    else if(bmi>=35.00 && bmi<=39.90)
      System.out.println("2nd degree obesity");
    else
      System.out.println("3rd degree obesity");
  
    }
}

Output:

39. Java Program to Find the Sum of Even Numbers

Write a program that sums even numbers from 1 to 100 using for loop.

class Main {
  public static void main(String[] args) {
      int sum=0;
    
      for(int i=1;i<=100;i++){
        if(i%2==0){
          sum = sum + i;
        }
      }

      System.out.println("The sum of even numbers from 1-100 is: "+sum);
    
    }
}

Output:

40. Java Program to Find the Largest and Smallest Numbers From Random Numbers

Write a program that will use the while loop to find the largest and smallest number from the set of 10 randomly drawn integers from 1 to 100. In this task, do not use arrays or other collections.

import java.util.Random;

class Main {
  public static void main(String[] args) {
    int min = 1, max=100;
    int largest=0;
    int smallest=100;
    int i = 1;
    
    while(i<=10){
      //Generating a random number
      Random r = new Random();
      int randomNumber = min + r.nextInt(max);
      System.out.println("Generated random number is: "+randomNumber);
      if(randomNumber>largest){
        largest = randomNumber;
      }
      if(randomNumber<smallest){
        smallest = randomNumber;
      }
      i++;
    }
    
    System.out.println("\n");
    System.out.println("The smallest number is: "+smallest);
    System.out.println("The largest number is: "+largest);
    
  }
}

Output:

41. Java Program to Calculate the Area of a Rectangle

Write a program that follows the rules of object-oriented programming and will calculate the area of the rectangle.

You need to create two classes, one RectangleArea for the logic of your program and the Main class. In the Main class, we create the RectangleArea object and call three methods on it.

The methods you should create are:

  • getData(), gets side lengths from the
  • computeField(), performs
  • fieldDisplay(), displays info and result.
import java.util.Scanner;

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

    RectangleArea r = new RectangleArea();
    r.getData();
    r.computeField();
    r.fieldDisplay();
    
    }
}

class RectangleArea{
  public double length, width, area;

  public void getData(){
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the length of the rectangle: ");
    length = sc.nextDouble();
    System.out.println("Enter the width of the rectangle: ");
    width = sc.nextDouble();
  }
  public void computeField(){
    area = length * width;
  }
  public void fieldDisplay(){
    System.out.println("The area of the rectangle is: "+area);
  }
  
}

Output:

42. Returning Information About an Object in Java

Declare the class Car and define the following fields of this class (with the access modifier private): model, brand, year, price, color, and quantity.

Create a constructor of this class consisting of the previously mentioned fields. Create methods to return each of the fields and methods to set values for each of the fields. Additionally, create the sell() method (simulating car sales) which will change the value of the quantity field when called.

The last method to create is the toString() method that returns an object of type String and prints the names of all fields of a given object and values.

Create another class with the main() method in it. Create an object of the Car class by using the constructor. Call the toString() method and print the details.

Call the sell() method. Print all fields (using the previously declared getter methods of the object field).

Using the setter methods, change some fields of the object. Call the toString() method and print the details to notice the changes.

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

    Car c1 = new Car("Model S","Tesla",2021,94990,"White",5);
    String result = c1.toString();
    System.out.println(result);

    c1.sell();
    System.out.println("\n1 car is sold.\n");

    System.out.println(c1.getModel());
    System.out.println(c1.getBrand());
    System.out.println(c1.getYear());
    System.out.println(c1.getPrice());
    System.out.println(c1.getColor());
    System.out.println(c1.getQuantity());

    c1.setYear(2022);
    c1.setPrice(110000);
    c1.setColor("Black");
    c1.setQuantity(10);

    System.out.println("\nUpdated some values for the car.\n");

    result = c1.toString();
    System.out.println(result);
    
    }
}

class Car{
  private String model, brand, color;
  private int year, price, quantity;
  //constructor
  Car(String model, String brand, int year, int price, String color, int quantity){
    this.model = model;
    this.brand = brand;
    this.year = year;
    this.price = price;
    this.color = color;
    this.quantity = quantity;
  }
  //getters
  public String getModel(){
    return model;
  }
  public String getBrand(){
    return brand;
  }
  public String getColor(){
    return color;
  }
  public int getYear(){
    return year;
  }
  public int getPrice(){
    return price;
  }
  public int getQuantity(){
    return quantity;
  }
  //setters
  public void setModel(String model){
    this.model = model;
  }
  public void setBrand(String brand){
    this.brand = brand;
  }
  public void setColor(String color){
    this.color = color;
  }
  public void setYear(int year){
    this.year = year;
  }
  public void setPrice(int price){
    this.price = price;
  }
  public void setQuantity(int quantity){
    this.quantity = quantity;
  }

  //sell method

  public void sell(){
    this.quantity = this.quantity - 1;
  }

  // toString method
  public String toString(){
    String output = "Model: "+this.model+"\nBrand: "+this.brand+"\nYear: "+this.year+"\nPrice: "+this.price+"\nColor: "+this.color+"\nQuantity: "+this.quantity;
    return output;
  }
  
  
}

Output:

43. Filling an Array Using For Loops in Java

Write a program that creates a 10-element array and puts the numbers from 9 to 0 in it.

Use the classic for loop to fill the array, and in the condition, use the array.length method. Use for-each loop as a second loop to display the value of the array.

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

    int[] numbers = new int[10];
    int value = 9;
    
    for(int i=0;i<numbers.length;i++){
      numbers[i] = value;
      value--;
    }

    for (int i : numbers){ 
        System.out.println(i);
      }
    
    }
}

Output:

44. Java Program to Find the Largest and Smallest Numbers From an Array of Random Numbers

Write a program that will create a one-dimensional array with 10 elements that are chosen randomly from 1 to 100. Then use a loop to find the smallest and largest element in the array.

import java.util.Random;

class Main {
  public static void main(String[] args) {
    
    int min = 1, max=100;
    int largest=0;
    int smallest=100;
    int[] numbers = new int[10];
    
    for(int i=0;i<numbers.length;i++){
      Random r = new Random();
      int randomNumber = min + r.nextInt(max);
      numbers[i] = randomNumber;
    }

    for (int i : numbers){
        System.out.println(i);
        if(i>largest)
          largest = i;
        if(i<smallest)
          smallest = i;
      }

    System.out.println("The largest number is: "+largest);
    System.out.println("The smallest number is: "+smallest);
    
    }
}

Output:

45. Two-dimensional Array in Java

Write a program that creates a two-dimensional array with dimensions of 10×10 and named matrix. On the diagonal of this matrix, put the numbers from 0 to 9 and the number 0 everywhere else. Additionally, the program should calculate the sum of the elements on the diagonal.

class Main {
  public static void main(String[] args) {
    
    int[][] matrix = new int[10][10];
    int number = 0;
    int sum = 0;
    
    for(int i=0; i<matrix.length;i++){
      for(int j=0; j<matrix[i].length;j++){
        if(i==j){
          matrix[i][j] = number;
          number++;
        }else{
          matrix[i][j] = 0;
        }        
      }
    }

    for(int i=0; i<matrix.length;i++){
      for(int j=0; j<matrix[i].length;j++){
         System.out.print(matrix[i][j]+" ");
        if(i==j){
          sum = sum + matrix[i][j];
        }
      }
      System.out.println();
    }

    System.out.println("The sum of diagonal numbers is: "+sum);
    
    }
}

Output:

Ashwin Joy

I'm the face behind Pythonista Planet. I learned my first programming language back in 2015. Ever since then, I've been learning programming and immersing myself in technology. On this site, I share everything that I've learned about computer programming.

Leave a Reply

Your email address will not be published.

Recent Posts