Sunday, July 11, 2021

5 easy java exercises with solution.

 1. Write a Java program to print 'Hello' on screen and then print your name on a separate line.

-->

public class Main {

      public static void main(String[] args) {

          System.out.println("Hello");

          System.out.println("Berry Sherstha");

     }

}


2. Write a Java program to print the sum of two numbers.

-->

import java.util.Scanner;


public class Main {

      public static void main(String[] args) {

          Scanner sc = new Scanner(System.in);

          System.out.println("Enter your first number");

          float a = sc.nextFloat();

          System.out.println("Enter your second number");

          float b = sc.nextFloat();

          float sum = a + b;

          System.out.println(sum);

     }

}


3. Write a Java program to divide two numbers and print on the screen.

-->

import java.util.Scanner;


public class Main {

  public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);

  System.out.println("Enter your first number");

  float a = sc.nextFloat();

  System.out.println("Enter your second number");

  float b = sc.nextFloat();

  float divide = a / b;

  System.out.println(divide);

 }

}


4. Write a Java program to print the result of the following operations.

Test Data:

a. -5 + 8 * 6
b. (55+9) % 9
c. 20 + -3*5 / 8
d. 5 + 15 / 3 * 2 - 8 % 3

-->

public class Main {

      public static void main(String[] args) {

          System.out.println(-5 + 8 * 6);

          System.out.println((55+9) % 9);

          System.out.println(20 + -3*5 / 8);

          System.out.println(5 + 15 / 3 * 2 - 8 % 3);

     }

}


5. Write a Java program that takes two numbers as input and display the product of two numbers.

-->

import java.util.Scanner;


public class Main {

  public static void main(String[] args) {

  Scanner sc = new Scanner(System.in);

  System.out.println("Enter the first number");

  float a = sc.nextFloat();

  System.out.println("Enter the second number");

  float b = sc.nextFloat();

  float c = a * b;

  System.out.println(c);

  }

}


NOTE: 

  1. Scanner class takes input from the user.
  2. To use Scanner class you need to import it using (import java.util.Scanner;).
  3. As java is case sensitive you cannot mess up your upper case and lower case.For example you cannot mess up scanner and Scanner.
  4. In java a and A are different same as to other letters.
  5. Java dose not have a Scanner to take data so you need to import it manually using no. 2 statement.


ANNOUNCEMENT: I'll be posting more five questions and solutions tomorrow so stay tuned. If you have any suggestions tell me it'll help me improve.

No comments:

Post a Comment