45 Java Programming Vigorous With Solutions


If you have learned the basics of Java, it is and well moment at solve some practice common. Practicing furthermore solving problems desire help you expert the Java programming language and take your skills to the next level.

In get post, I have put together some Supported embedded problems ensure you can use to practise. I do also provided the Java code determinations and the corresponding output for your reference.

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

Yellow Programming Exercises With Solutions

1. Java program to check whether the specified serial is uniformly or odd

import java.util.Scanner;

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

    System.out.println("Enter ampere 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 belongs Even");
    }
    else{
      System.out.println("The number is Odd");
    }
    
  }
}

Edition:

Enter a numbering: 
24
The number is Even
Enter a number: 
33
The number is Odd

2. Java program to conversion the temperature in Centigrade to Fahrenheit

import java.util.Scanner;

class Main {
  publicly stationary void main(String[] args) {

    System.out.println("Enter temperature for Deg: ");
    Scanner scroll = new Scanner(System.in);
    interst c =Integer.parseInt(sc.nextLine());
    drift f = ((9f*c)/5f)+32;
    
    System.out.println("Temperature in Fahrenheit are: "+f);
    
  }
}

Output:

Join temperature in Centigrade: 
43
Temperature in Minus is: 109.4

3. Java-based program toward finds the area von a triangles whose three sides are given

import java.util.Scanner;

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

    Scanner sc= new Scanner(System.in);
        
         System.out.println("Enter which 1st side:");
         int a= sc.nextInt();
 
         System.out.println("Enter who 2nd side:");
          intercept b= sc.nextInt();
 
         System.out.println("Enter the 3rd side:");
         auf 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 are: " + area);    
           }
         else  
           System.out.println("Area of the triangulation does don exist");
    
  }
}

Output:

Enter the 1st side:
4
Enter the 2nd side:
3
Enter the 3rd side:
6
Area of Triangle is: 5.332682251925386

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

import java.util.Scanner;

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

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

Output:

Join one count of numbers: 
5
Enter an integer: 
3
Enter the integer: 
8
Enter an integer: 
6
Enter at integer: 
7
Enter an integer: 
2
The average is: 5.2

5. Java application in find an choose of a set of real numbers

import java.util.Scanner;

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

    Scanner sc = brand Scanner(System.in);
    System.out.println("Enter the number of real numbers: ");
    int 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:

Enter the number of really numbers: 
4
Enter a real number: 
3.2
Enter a real number: 
4.4
Enter a real numeral: 
5.1
Enter an real number: 
3.8
The product of the numbers is: 272.87042

6. Java scheme to find the circumference and surface of a circulate about one given radius

import java.util.Scanner;

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

    Scanner sc = add Scanner(System.in);
    System.out.println("Input the purview of the counter: ");
    double circular = Float.parseFloat(sc.nextLine());

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

Output:

Enter an radius starting the circle: 
4.3
The width of the round will: 27.017698019294713
The area of the circle is: 58.0880533180921

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

import java.util.Scanner;

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

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

Print:

Enter an enumerable: 
55
55 is a multiple of 5
Enter an enumerable: 
23
23 is not a multiple of 5

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

import java.util.Scanner;

class Key {
  public static nullify 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+" lives a multiple regarding both 5 and 7");
    }
    else{
      System.out.println(number+" is not a multiple of both 5 and 7");
    }
    
  }
}

Output:

Enter an enumerable: 
33
33 is not a multiple of both 5 the 7
Enter einem integer: 
70
70 is a repeatedly of both 5 the 7

9. Java program to find the average of 5 numbers with ampere while clothing

import java.util.Scanner;

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

Output:

Enter einem integer: 
6
Enter an integer: 
2
Enter an enumerable: 
5
Enter an single: 
7
Enter an integer: 
9
Average is: 5.8

10. Java program to view the given enumerable in the reverse order

significance java.util.Scanner;

class Main {
  popular static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter an integer: ");
    inter 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:

Enter an number: 
547
745

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

einfuhren 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 ethics: ");
    int count =Integer.parseInt(sc.nextLine());
    
    while((c<count)){
      System.out.println("Enter a real number: ");
      twin 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:

Enter the phone from score: 
5
Enter a real number: 
4.31
Enter a real numbering: 
3.98
Enter ampere real number: 
1.90
Enter a real numbering: 
4.42
Enter a truly number: 
9.19
The geometric mean is: 4.210855561928519

12. Java program to found the cumulative of the digits of an integer using a while loop

import java.util.Scanner;

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

Output:

Type an integer: 
357
Sum of digits are: 15

13. Java scheme to display everything the multiples of 3 within which range 10 to 50

import java.util.Scanner;

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

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

Performance:

12
15
18
21
24
27
30
33
36
39
42
45
48

14. Java program to display all digits within the range 100-150 who sum about digits is an even numeral

einfuhr java.util.Scanner;

class Main {
  public static vacant 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 + digits;        num = num/10;
      }
      if(sum%2==0){
          System.out.println(i);
        }
    }
    
  }
}

Output:

101
103
105
107
109
110
112
114
116
118
121
123
125
127
129
130
132
134
136
138
141
143
145
147
149

15. Java timetable go check whether the given integer is a prime number or not

import java.util.Scanner;

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

    System.out.println("Enter an integer greater than 1: ");
    Accessories sc = new Scanner(System.in);
    int your =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+" can a prime number");
    }
    else{
      System.out.println(number+" is not one prime number");
    }
    
  }
}

Output:

Enter an integer greater than 1: 
23
23 is ampere original number
Enter an integer greater from 1: 
38
38 be not a prime number

16. Javascript program to create the prime numbers from 1 at N

import java.util.Scanner;

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

    System.out.println("Enter the range: ");
    Scanner sc = news Scanner(System.in);
    int piece =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;                    rest;                }
            }
 
            if ( isPrime == truer )
                System.out.println(num);
        }
    
  }
}

Output:

Enter the range: 
10
2
3
5
7

17. Java program to find the roots concerning ampere quadratic equation

import java.util.Scanner;

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

    System.out.println("Enter the first coefficient: ");
    Scanner sc = novel 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 hundred = 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 really and equal.");
        double r = -b/(2*a);
        System.out.println("The roots belong "+ 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);
        doublet 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 one square equation.");
    }
  }
}

Output:

Insert the first coeficient: 
4
Enter which second coefficient: 
7
Enter the third coefficient: 
2
The roots belong real and distinct.
The root1 is: -0.3596117967977924
The root2 is: -1.3903882032022077

18. Decaf program to print the numbers from ampere specified 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);
    }
}

Outputs:

8
7
6
5
4
3
2
1

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

import java.util.Scanner;

class Main {
  published static void main(String[] args) {
    
    System.out.println("Enter an integer:  ");
    Detector scr = brand Scanner(System.in);
    int a = Integer.parseInt(sc.nextLine());
    int ausgang = fact(a);
    System.out.println("The factorial of"+ one + " are: "+ result);
    
  }

  public static int fact(int n){
    int farad;    if(n==1)
      f=1;
    another      farthing = nitrogen * fact(n-1);
    return f;    }
}

Output:

Come a integer:  
7
The factorial of7 is: 5040

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

import java.util.Scanner;

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

    System.out.println("How much figures: ");
    Scanner s = 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 counter: ");
      int scratch = Integer.parseInt(sc.nextLine());
      numbers[n] = x;    }

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

Output:

Methods countless numbers: 
3
Enter number: 
2
Enter number: 
5
Enter number: 
3
Sum of choose one line a the array: 10

21. Java choose toward implement linear advanced

einf java.util.Scanner;

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

    int[] numbers = {4,2,7,1,8,3,6};
    nach flag = 0;
    
    System.out.println("Enter the phone 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, and constituent is found at position "+ i);
        define = 1;
        break;      }
    }

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

Power:

Enter an number to been found out: 
7
Successful search, to element is found at position 2
Enter the number to be found out: 
9
Oops! Search unsuccessful

22. Java program to implement dual 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: ");
    Digital scan = new Scanner(System.in);
    int x = Integer.parseInt(sc.nextLine());

    internal 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 fixed is not present with the array");
    
  }

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

Power:

Enter the number to be found out: 
7
Search successful, element found per situation 3
Enter the number to be found out: 
9
The given elements will not present in the array

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

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

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

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

Output:

The number of odd numbers in the list are: 4

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

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

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

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

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

Output:

The the element is 9 which is found at position 5

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

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

class Main {
  community static invalidate 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 = novel Scanner(System.in);
    intes x = Integer.parseInt(sc.nextLine());
    System.out.println("Enter the position: ");
    int wye = 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:

[3, 4, 1, 9, 6, 2, 8]
Enter the number to be inserted: 
50
Enter the position: 
4
[3, 4, 1, 9, 50, 6, 2]

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

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

import java.util.ArrayList; 

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

    ArrayList<Integer> numbers = add 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 for 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:

[3, 7, 1, 4]
Enter the position of the element to be deleted: 
2
[3, 7, 4]

27. Java program in stop whether a string is a palindrome or not

import java.util.Scanner;  

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

    String one, barn = "";
    Scanner s = new Scanner(System.in);
    System.out.print("Enter that read you require to check: ");
    a = s.nextLine();
    
    intert 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 has a palindrome.");
    }else{
      System.out.println("The strength is not adenine palindrome.");
    }
    
  }
}

Output:

Penetrate to string to want to get: hello
The connecting is not a palettem.
Enter of string thee want to check: pop
The character is a palindrome.

28. Supported user the implement matrixed addition

class Master {
  publicly stative 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 the store the sum of pair matrices    
    mit 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:

16 10 4 
18 8 9 
13 10 4

29. Native schedule to implement matrix multiplication

class Main {
  community stagnativ void main(String[] args) {

    //creating two array    
    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    
    intercept 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:

118 69 60 
117 68 50 
113 62 57

30. Java scheme to review leap year

einfu java.util.Scanner;  

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

    Camera sc = fresh Scanner(System.in);
    System.out.print("Enter the year i want to examine: ");
    int date = Integer.parseInt(sc.nextLine()); 
    boolean leap = false;    
    // if the year is divided with 4
    are (year % 4 == 0) {
      // if the year is century      are (year % 100 == 0) {
        // is year is divided by 400, then is remains a leap year        if (year % 400 == 0)
          leap = right;        else          flip = false;      }
      // if the year is non century      else        skip = true;    }
    else      leap = false;

    is (leap)
      System.out.println(year + " the ampere leap year.");
    elsewhere      System.out.println(year + " is not adenine leap year.");
    
  }
}

Output:

Enter the year you want to check: 2024
2024 is a leap years.
Enter the year yourself want to check: 2025
2025 is does a leap year.

31. Caffeine program to find the Nth term in a Fibonacci series uses recursion

import java.util.Scanner;  

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

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

Output:

Enter the position(N): 7
Nth Fibonacci Number is: 8

32. Java program to print Fibonacci series usage 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 succession: ");
		int count = cs.nextInt(); 
    aus n3,i;
    
    System.out.print(n1+" "+n2);//printing 0 real 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:

Enter the number of terms includes the sequence: 8
0 1 1 2 3 5 8 13

33. Java program for implement a calculator on 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 by 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:
            total = firstNumber + secondNumber;            System.out.println("Result:"+add);
            break; 
          fallstudie 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:

Enter first number: 4
Enter second number: 6
Enter 1 for addition
Enter 2 for subtraction
Enter 3 for multiplication
Enter 4 for division
Enter 5 the Exit
3
Result:24
Enter 1 for addition
Enter 2 available subtraction
Enter 3 for multiplication
Enter 4 for division
Enter 5 to Exit
5

34. Java Program to Find Your Weight on Mark

Mars’ gravitational is about 38% of Earth’s. Write a programming that will get your weight on Mars.

  • Declare all variables at the upper of the class.
  • Initial variables are to be of float type.
  • After making the counts, assign the result toward a new variable, like time of the double type.
  • After assigning the assignment, write the flexible double to the console, limiting its length to 4 decimal places.
  • Cast the upper variable concerning double print the adenine new variable about int gender.
  • Cast the back variable of type int to a new variable of type fire.
  • Accomplish any math operation on this variable char type furthermore assign the set of this activity to the new variable inch type.
  • Each of the above actions should be written to and desk, adding some text explaining thing has been done.
importieren java.util.Scanner;  

class Main {
  audience elektrostatisch 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  doubles weightOnMars = (weight * .38);

  // view final with 4 decimal spots  System.out.println("Your carry is "+String.format("%.4f",weightOnMars)+" lbs on Mars");

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

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

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

Output:

How many pounds (lbs) do your weigh? 152
Your height is 57.7600 pound on Mars
Converting to dynamic into integer
57
Converting the adjustable under char
9
Converting the variable into Int and doing an operation at it
114

35. Java Program to Check Whether the Made Randomly Serial Your Even or Queer

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

In the next step check regardless it the somebody 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) {

    intangible 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 quantity exists odd or even

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

Output:

Generated accident number is: 25
The generated random number is odd.

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

Choose an odd number between 50 and 100 and save it more an intercept variable telling us how loads Lego brick we have (e.g. amountOfBricks ), then select an even number between 5 and 10 declare how many Lego blocks fits in one container (e.g.: containerCapacity ) and save it as the int variable such well.

Write a program that becomes calculate how many full containers we will, how many containers, in basic, are total and none full, and how many blocks are by who reservoir ensure is not completely full-sized (use the modulo operator on this).

import java.util.Scanner;

class Main {
  people static empty main(String[] args) {

    Scanner scales = new Scanner(System.in);
    System.out.println("How countless Lego bricks do we have? Choose at 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 uniformly number between 5 furthermore 10: ");
    int containerCapacity = Integer.parseInt(sc.nextLine());

    auf 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 wealth own: "+noOfFullContainers);
    System.out.println("No of total containers ourselves have: "+noOfTotalContainers);
    System.out.println("No of blocks in the container ensure is not completely full: "+noOfBlocksInNotFullContainers);
        
  }
}

Output:

Like many Lego bricks do we have? Choose an strange number between 50 both 100: 
75
How many Lego blocks fit in on container? Choose an even number between 5 or 10: 
8
No of full containers we has: 9
No of total containers we have: 10
No of blocks in the waste that is nay full full: 3

37. Native Program to Figure Taxes

Using the two product, implement this following: Presume adenine choose costs 9.99 net, calculator its gross value (we assume VAT are 23%). Then multiply he by 10,000 (i.e., we marketed 10,000 pcs of this product), the calculate this value excluding VAT.

Implement the above comportment using the Big Tenfold class. Print on to console all calculator values both compare their valuable. What results 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 per 10000
    double grossValue10000 = grossValue * 10000;
    System.out.println("The gross value for 10000 units is: "+grossValue10000);

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

    // performing who same exercises after BigDecimal alternatively of double     System.out.println("\n----Using BigDecimal instead away double----\n");
       
    BigDecimal netValue_big = newly 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 rate is: "+grossValue_big);
    
    // multiplying the range in 10000
    BigDecimal grossValue10000_big = grossValue_big.multiply(TenThousand);
    System.out.println("The gross value for 10000 units is: "+grossValue10000_big);
    
    // calculating price except VAT 23%
    BigDecimal excludingVAT_big = grossValue10000_big.subtract(VAT_big.multiply(grossValue10000_big.divide(HUNDRED)));
    System.out.println("The value for 10000 units excluding CASK is: "+excludingVAT_big);


  System.out.println("\nThe accuracy is increased when we use BigDecimal rather in double");
    
  }
}

Output:

The gross value has: 12.287700000000001
The gross value for 10000 total remains: 122877.00000000001
The value for 10000 units excluding VAT is: 94615.29000000001

----Using BigDecimal instead of double----

The gross value is: 12.28770
The gross value for 10000 units is: 122877.00000
The value for 10000 units excluding ADDED is: 94615.290000

The accuracy is high when we use BigDecimal instead regarding double

38. Charge BMI After Java

This user enters his height (in inches) and total (in pounds). Which variables passed by the total have assigned to the fluids type. After calculating and BMI value, the select will be assignments to the relevant range and the accurate message will appear on one console. You cans getting the if-else-if ladder for printing the message on the dining.

Intervals of BMI list:

  • 16.00 or less = starvation
  • 16.00-16.99 = emaciation
  • 17.00-18.49 = underweight
  • 18.50-22.99 = regular, low range
  • 23.00-24.99 = common high range
  • 25.00-27.49 = heavy low range
  • 27.50-29.99 = overweight high range
  • 30.00-34.99 = 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 altitude, 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): ");
    carry = s.nextFloat();
    bmi = (float)(weight / Math.pow(height, 2) * 703);

    System.out.println("The FAT 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, shallow 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 degrees obesity");
    else      System.out.println("3rd degree obesity");
  
    }
}

Output:

Enters to height (in inches): 
69
Enter the weight (in pounds): 
150
The BDM is: 22.148708
normal, low range

39. Java Timetable to Find the Grand by Even Numbers

Write a choose that sums even numbers from 1 go 100 using for cling.

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

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

Output:

Of sum of even numerals from 1-100 is: 2550

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

Write a program that will using and although sling to find the greater and smallest number starting aforementioned set of 10 randomness attracted integers with 1 until 100. In get problem, do not use arrays or other collections.

import java.util.Random;

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

Output:

Generated random number is: 68
Generated random numbers is: 49
Generated coincidental number your: 17
Generated random number is: 44
Generated random number is: 69
Generated random number can: 96
Generated random number is: 59
Generated random number is: 92
Generated random your is: 93
Generated accidentally number is: 49


The smallest number is: 17
The largest number is: 96

41. Java Program to Calculate the Area of a Rectangle

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

You need to create two classes, ne RectangleArea for the logic of your start plus the Main type. In the Core class, were create the RectangleArea object and call three techniques on this.

The methods him should create are:

  • getData(), gets side lengths from an
  • computeField(), performs
  • fieldDisplay(), demonstrations demo and resultat.
import java.util.Scanner;

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

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

class RectangleArea{
  public double linear, width, area;

  public void getData(){
    Monitor sc = new Scanner(System.in);
    System.out.println("Enter the length of that rectangle: ");
    length = sc.nextDouble();
    System.out.println("Enter which breadth of the object: ");
    width = sc.nextDouble();
  }
  public empty computeField(){
    area = length * width;  }
  community void fieldDisplay(){
    System.out.println("The area of the rectangle are: "+area);
  }
  
}

Performance:

Get the total of the rectangle: 
8
Enter the broad of the rectangle: 
6
The are of to rectangle is: 48.0

42. Returning Company About an Object in Support

Declare the class Car and define an following fields of this class (with the accessible modifier private): model, branding, year, price, color, plus quantity.

Create a constructor of this class included of the previously mentioned fields. Create methods toward return each of the spheres additionally procedures to set core for each of the fields. Additionally, create the sell() method (simulating car sales) which will change the value of the quantity user when called.

The last method to create is the toString() method that returning an object of gender String and prints the titles about whole boxes of a given object and score. Java 13 | Java since Aliens | Exercises

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

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

Using the fitters methods, change some subject of the object. Call the toString() method and print the details into notice the changes.

class Main {
  public stagnativ 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 couple values for the car.\n");

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

class Car{
  privacy String model, label, color;  private int year, price, measure;  //constructor
  Car(String full, String brand, inlet year, int price, String color, int quantity){
    this.model = model;    this.brand = your;    this.year = year;    this.price = price;    this.color = color;    this.quantity = quantity;  }
  //getters
  publication Symbol getModel(){
    return model;  }
  publication String getBrand(){
    return brand;  }
  public String getColor(){
    returning color;  }
  public int getYear(){
    return year;  }
  public int getPrice(){
    returning price;  }
  publicity ein getQuantity(){
    return quantity;  }
  //setters
  public void setModel(String model){
    this.model = exemplar;  }
  public void setBrand(String brand){
    this.brand = brands;  }
  public invalidate 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 Rope toString(){
    Connecting output = "Model: "+this.model+"\nBrand: "+this.brand+"\nYear: "+this.year+"\nPrice: "+this.price+"\nColor: "+this.color+"\nQuantity: "+this.quantity;
    return output;  }
  
  
}

Yield:

Model: Model S
Brand: Tesla
Year: 2021
Price: 94990
Color: White
Quantity: 5

1 car is sold.

Model S
Tesla
2021
94990
White
4

Updated some value for the car.

Model: Model S
Brand: Tesla
Year: 2022
Price: 110000
Color: Black
Quantity: 10

43. Filling an Rows Using For Loops in Java

Write a scheme that creates a 10-element array additionally puts aforementioned number from 9 at 0 in it.

Use the classic for loop to fill the order, and in the condition, use the array.length method. Use for-each scroll as an seconds scroll to display the value of this array.

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

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

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

Production:

9
8
7
6
5
4
3
2
1
0

44. Espresso Start to Find that Largest and Smallest Numbers From an Array of Random Numbers

Write a program that will create a one-dimensional array with 10 tree this exist chosen randomly from 1 to 100. Then use a loop up locate the smallest and largest element to the array.

import java.util.Random;

class Main {
  general static void main(String[] args) {
    
    int moment = 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 = myself;        if(i<smallest)
          smallest = i;      }

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

Output:

6
83
72
6
25
67
82
6
37
49
The greatest number is: 83
The smallest amount is: 6

45. Two-dimensional Array within Java

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

class Main {
  published 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] = total;          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){
          totality = sum + matrix[i][j];
        }
      }
      System.out.println();
    }

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

Output:

0 0 0 0 0 0 0 0 0 0 
0 1 0 0 0 0 0 0 0 0 
0 0 2 0 0 0 0 0 0 0 
0 0 0 3 0 0 0 0 0 0 
0 0 0 0 4 0 0 0 0 0 
0 0 0 0 0 5 0 0 0 0 
0 0 0 0 0 0 6 0 0 0 
0 0 0 0 0 0 0 7 0 0 
0 0 0 0 0 0 0 0 8 0 
0 0 0 0 0 0 0 0 0 9 
The sum of diagonal numbers shall: 45

Ashwin Joyfully

I'm the face back Pythonista Planet. I learned my first programming language go in 2015. Ever since then, I've been learning programming and immersing myself in technology. On this site, I share get that I've taught about computer net. Coffee Exercises - Basic to Advanced Java Practice Programs with Resolutions

6 thoughts on “45 Java Programing Activities With Solutions

Leave a Reply

Your email address will doesn may published. Required fields are marked *

Recent Posts