Tag: java basic programs

  • Java Program to Find the Distance between Two Points

    In this tutorial, we will write a program to find the distance between two given points in java. Before that, you should have knowledge of the following topic in Java.

    Distance Formula:

    The distance between two coordinates or points is calculated using the following formula.

    First point: (x1, y1)
    Second point: (x2, y2)
    Distance (MN): √((x2 – x1)2 + (y2 -y1)2)

    Here x1, y1 are the coordinates of the first point and x2, y2 are the coordinates of the second point. These points indicate the x-axis and y-axis values.

    Example:

    First Points: (4, 8)
    Seecond Points: (12, 14)
    Then distance between them √((12-4)2 + (14-8)2) = √(64 + 36) = √(100) = 10


    Java Program to Find the Distance between Two Points

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String[] args)
      {
        Scanner scan = new Scanner(System.in);
    
        int x1, x2, y1, y2, x, y;
        double distance;
    
        System.out.println("Enter first coordinates (x1, y1): ");
        x1 = scan.nextInt();
        y1 = scan.nextInt();
    
        System.out.println("Enter second coordinates (x2, y2): ");
        x2 = scan.nextInt();
        y2 = scan.nextInt();
    
        //calculation
        x = x2 - x1;
        y = y2 - y1;
        distance = Math.sqrt(x * x + y * y);
    
        System.out.println("Distance between the two coordinates: " + distance);
      }
    }

    Output:

    Enter first coordinates (x1, y1):
    5
    3
    Enter second coordinates (x2, y2):
    2
    3
    Distance between the two coordinates: 3.0


  • Java Program to Calculate Grade of Students

    In this tutorial, we will write a java program to calculate the grade of the student. Before that, you should have knowledge on the following topic in java:

    Java Program to calculate and display Student Grades: The program simply takes a user input for the number of subjects and then for the marks obtained on each of those subjects.

    Then the sum of the marks is calculated and then the average of that sum is calculated. The average is calculated by dividing the sum of the marks by the number of subjects. Lastly, using the if-else ladder the grade is displayed on the screen.

    The grade is printed by following grade slab:

    • If marks > 80, Grade is A
    • If marks > 60 and <= 79, Grade is B
    • If marks > 40 and <= 59, Grade is C
    • Else Grade is D

    You can change the grades according to your need and your question. We will perform two different programs:

    1. Using if else ladder
    2. Using Switch Case

    Java program to find grade of a student using if else ladder

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String args[])
      {
        int marks[] = new int[5];
        int i, subjects;
        float sum = 0, avg;
        Scanner sc = new Scanner(System.in);
    
        System.out.print("Enter the number of subjects: ");
        subjects = sc.nextInt();
    
        System.out.println("Enter Marks for " + subjects + " Subjects: ");
        for (i = 0; i < subjects; i++)
        {
          marks[i] = sc.nextInt();
          sum = sum + marks[i];
        }
    
        avg = sum / subjects;
    
        System.out.print("Your Grade: ");
        if (avg > 80)
        {
          System.out.print("A");
        }
        else if (avg > 60 && avg <= 79)
        {
          System.out.print("B");
        }
        else if (avg > 40 && avg <= 59)
        {
          System.out.print("C");
        }
        else
        {
          System.out.print("D");
        }
      }
    }

    Output:

    Enter the number of subjects: 5
    Enter Marks for 5 Subjects:
    55
    84
    72
    67
    90
    Your Grade: B


    Java Program to find grade of a student using switch case

    import java.util.Scanner;
    
    public class Main
    {
      public static void main(String[] args)
      {
        int subjects, i;
        float sum = 0, percent;
        Scanner sc = new Scanner(System.in);
    
        System.out.println("Enter the Number of Subjects: ");
        subjects = sc.nextInt();
    
        System.out.println("Enter Marks for " + subjects + " Subjects:");
        for (i = 0; i < subjects; i++)
        {
          sum += sc.nextInt();
        }
    
        percent = (sum / (subjects *100)) *100;
        System.out.println("Percentage Obtained: " + percent);
    
        switch ((int) percent / 10)
        {
          case 9:
            System.out.println("Your Grade: A+");
            break;
          case 8:
            System.out.println("Your Grade: A");
            break;
          case 7:
            System.out.println("Your Grade: B");
            break;
          case 6:
            System.out.println("Your Grade: B+");
            break;
          case 5:
            System.out.println("Your Grade: C");
            break;
          default:
            System.out.println("Your Grade: D");
            break;
        }
      }
    }

    Enter the Number of Subjects:
    4
    Enter Marks for 4 Subjects:
    84
    79
    92
    85
    Percentage Obtained: 85.0
    Your Grade: A


  • Currency Conversion Program in Java

    In this section of the java program tutorial, we will learn how to write a Java Currency Converter Program and see how it works. Before we begin, let me tell you that this is a beginner’s tutorial for the currency converter program in java.

    Although there are many ways in which you can create a currency converter using java. You can create separate methods or you can use if..else-if statement, here we are going to use a switch case statement for the currency converter.


    Java Currency Converter program using Switch case

    import java.util.*;
    import java.text.DecimalFormat;
    
    public class CurrencyConverter
    {
       public static void main(String[] args)
       {
          double amount;
          double rupee, dollar, pound, euro, yen, ringgit;
          int choice;
    
          DecimalFormat f = new DecimalFormat("##.##");
    
          Scanner sc = new Scanner(System.in);
    
          System.out.println("Following are the Choices:");
          System.out.println("Enter 1: Ruppe");
          System.out.println("Enter 2: Dollar");
          System.out.println("Enter 3: Pound");
          System.out.println("Enter 4: Euro");
          System.out.println("Enter 5: Yen");
          System.out.println("Enter 5: Ringgit");
    
          System.out.print("\nChoose from above options: ");
          choice = sc.nextInt();
    
          System.out.println("Enter the amount you want to convert?");
          amount = sc.nextFloat();
    
          switch (choice)
          {
             case 1:  // Ruppe Conversion
                dollar = amount / 70;
                System.out.println(amount + " Rupee = " + f.format(dollar) + " Dollar");
    
                pound = amount / 88;
                System.out.println(amount + " Rupee = " + f.format(pound) + " Pound");
    
                euro = amount / 80;
                System.out.println(amount + " Rupee = " + f.format(euro) + " Euro");
    
                yen = amount / 0.63;
                System.out.println(amount + " Rupee = " + f.format(yen) + " Yen");
    
                ringgit = amount / 16;
                System.out.println(amount + " Rupee = " + f.format(ringgit) + " ringgit");
                break;
    
             case 2:  // Dollar Conversion
                rupee = amount * 70;
                System.out.println(amount + " Dollar = " + f.format(rupee) + " Ruppes");
    
                pound = amount *0.78;
                System.out.println(amount + " Dollar = " + f.format(pound) + " Pound");
    
                euro = amount *0.87;
                System.out.println(amount + " Dollar = " + f.format(euro) + " Euro");
    
                yen = amount *111.087;
                System.out.println(amount + " Dollar = " + f.format(yen) + " Yen");
    
                ringgit = amount *4.17;
                System.out.println(amount + " Dollar = " + f.format(ringgit) + " ringgit");
                break;
    
             case 3:  // Pound Conversion
                rupee = amount * 88;
                System.out.println(amount + " pound = " + f.format(rupee) + " Ruppes");
    
                dollar = amount *1.26;
                System.out.println(amount + " pound = " + f.format(dollar) + " Dollar");
    
                euro = amount *1.10;
                System.out.println(amount + " pound = " + f.format(euro) + " Euro");
    
                yen = amount *140.93;
                System.out.println(amount + " pound = " + f.format(yen) + " Yen");
    
                ringgit = amount *5.29;
                System.out.println(amount + " pound = " + f.format(ringgit) + " ringgit");
                break;
    
             case 4:  // Euro Conversion
                rupee = amount * 80;
                System.out.println(amount + " euro = " + f.format(rupee) + " Ruppes");
    
                dollar = amount *1.14;
                System.out.println(amount + " euro = " + f.format(dollar) + " Dollar");
    
                pound = amount *0.90;
                System.out.println(amount + " euro = " + f.format(pound) + " Pound");
    
                yen = amount *127.32;
                System.out.println(amount + " euro = " + f.format(yen) + " Yen");
    
                ringgit = amount *4.78;
                System.out.println(amount + " euro = " + f.format(ringgit) + " ringgit");
                break;
    
             case 5:  // Yen Conversion
                rupee = amount *0.63;
                System.out.println(amount + " yen = " + f.format(rupee) + " Ruppes");
    
                dollar = amount *0.008;
                System.out.println(amount + " yen = " + f.format(dollar) + " Dollar");
    
                pound = amount *0.007;
                System.out.println(amount + " yen = " + f.format(pound) + " Pound");
    
                euro = amount *0.007;
                System.out.println(amount + " yen = " + f.format(euro) + " Euro");
    
                ringgit = amount *0.037;
                System.out.println(amount + " yen = " + f.format(ringgit) + " ringgit");
                break;
    
             case 6:  // Ringgit Conversion
                rupee = amount *16.8;
                System.out.println(amount + " ringgit = " + f.format(rupee) + " Ruppes");
    
                dollar = amount *0.239;
                System.out.println(amount + " ringgit = " + f.format(dollar) + " dollar");
    
                pound = amount *0.188;
                System.out.println(amount + " ringgit =: " + f.format(pound) + " pound");
    
                euro = amount *0.209;
                System.out.println(amount + " ringgit = " + f.format(euro) + " euro");
    
                yen = amount *26.63;
                System.out.println(amount + " ringgit = " + f.format(yen) + " yen");
                break;
    
              //Default case
             default:
                System.out.println("Invalid Input");
          }
       }
    }

    Output:

    Following are the Choices:
    Enter 1: Ruppe
    Enter 2: Dollar
    Enter 3: Pound
    Enter 4: Euro
    Enter 5: Yen
    Enter 5: Ringgit
    
    Choose from above options: 3
    Enter the amount you want to convert?
    200
    200.0 pound = 17600 Ruppes
    200.0 pound = 252 Dollar
    200.0 pound = 220 Euro
    200.0 pound = 28186 Yen
    200.0 pound = 1058 ringgit

    The above java program is the simple one as you can see that the conversion is done using the basic switch statement. And as told earlier, you can do the same by using the if..else-if ladder statement, or either you can create a separate function for each currency conversion. This is how you can create a basic currency converter in java program.


  • Menu Driven Program in Java

    In this tutorial, we will write a program on menu driven in java using switch statement along with source code. The switch case is mostly used when it is necessary to give options to the users. If you do not know the working process of the switch case statement then click the link below.

    Java Menu-driven Program using switch case:

    This is a menu program in java that displays a menu and takes the input from the user. The choice made by the user is among the option displayed in the menu. And accordingly, the output is displayed on the screen. It is a user-friendly program in java.


    Menu Driven Program in Java.

    The below menu-driven Java program calculates the area of different geometrical figures.

    //area of different geometric figures using switch case in java
    
     import java.util.Scanner;
    
     public class MenuDriven
     {
        public static void main(String args[])
        {
           Scanner sc = new Scanner(System.in);
    
           System.out.println("To find the areas of following press:");
           System.out.println("1 for the Area of a Circle");
           System.out.println("2 for the Area of a Square");
           System.out.println("3 for the Area of a Right Angled Triangle");
           System.out.println("4 for the Area of a Rectangle");
           System.out.println("5: Area of Rhombus");
           System.out.print("\nEnter your Choice: ");
           int ch = sc.nextInt();
    
           switch (ch)
           {
              case 1:
                 System.out.println("Enter radius for the circle:");
                 float r = sc.nextFloat();
                 float area = 3.14f *r * r;
                 System.out.println("Area:" + area);
                 break;
    
              case 2:
                 System.out.println("Enter side for square:");
                 int s = sc.nextInt();
                 int ae = s * s;
                 System.out.println("Area:" + ae);
                 break;
    
              case 3:
                 System.out.println("Enter height and base for traingle:");
                 float h = sc.nextFloat();
                 float bs = sc.nextFloat();
                 float ar = 0.5f *h * bs;
                 System.out.println("Area:" + ar);
                 break;
    
              case 4:
                 System.out.println("Enter length and breadth for rectangle:");
                 int l = sc.nextInt();
                 int b = sc.nextInt();
                 int aa = l * b;
                 System.out.println("Area:" + aa);
                 break;
    
              case 5:
                 System.out.print("Enter the first diagonal of a Rhombus: ");
                 float diagonal1 = sc.nextInt();
                 System.out.print("Enter the second diagonal of the Rhombus: ");
                 float diagonal2 = sc.nextInt();
                 float aRhombus = (diagonal1 *diagonal2) / 2;
                 System.out.println("Area of the Rhombus is: " + aRhombus);
                 break;
    
              default:
                 System.out.println("Invalid Input");
                 break;
           }
        }
     }

    Output 1:

    To find the areas of following press:
    1 for the Area of a Circle
    2 for the Area of a Square
    3 for the Area of a Right Angled Triangle
    4 for the Area of a Rectangle
    5: Area of Rhombus
    
    Enter your Choice: 2
    Enter side for square:
    4
    Area:16

    Output 2:

    To find the areas of following press:
    1 for the Area of a Circle
    2 for the Area of a Square
    3 for the Area of a Right Angled Triangle
    4 for the Area of a Rectangle
    5: Area of Rhombus
    
    Enter your Choice: 3
    Enter height and base for traingle:
    3
    2
    Area:3.0

    Output 3:

    To find the areas of following press:
    1 for the Area of a Circle
    2 for the Area of a Square
    3 for the Area of a Right Angled Triangle
    4 for the Area of a Rectangle
    5: Area of Rhombus
    
    Enter your Choice: 5
    Enter the first diagonal of a Rhombus: 4
    Enter the second diagonal of the Rhombus: 3
    Area of the Rhombus is: 6.0

    Using this logic you can create various other menu programs in java.


  • Java Program to print ASCII value of a Character

    In this tutorial, you will learn how to find the ASCII value of a character in Java. Before that, you need to have the knowledge of the following in Java Programming.

    ASCII stands for American Standard Code for Information Interchange. It is a 7-bit character set that contains 128 (0 to 127) characters. It represents the numerical value of a character.

    Example: ASCII value for character A is 65, B is 66 but a is 97, b is 98, and so on.

    There are two ways to find the ASCII value of a character, we will learn both of them.

    1. Variable Assignment
    2. Using Type-Casting

    1. Variable Assignment

    Java internally converts the character values to ASCII values, we do not require any type of method to do so.

    public class AsciiValue    
    {  
        public static void main(String[] args)   
        {  
            // character whose ASCII value to be found  
            char ch1 = 'A';  
            char ch2 = 'a';  
            
            //assigning character to int  
            int ascii1 = ch1;  
            int ascii2 = ch2;  
            
            System.out.println("The ASCII value of " + ch1 + " is: " + ascii1);  
            System.out.println("The ASCII value of " + ch2 + " is: " + ascii2);  
        }  
    }  

    Output:

    The ASCII value of A is: 65
    The ASCII value of a is: 97


    2. Using Type-Casting

    Type-casting refers to the casting of one data-type variable to another data type.

    public class AsciiValue    
    {  
        public static void main(String[] args)   
        {  
            // character whose ASCII value to be found  
            char ch1 = 'A';  
            char ch2 = 'a';  
            
            //casting to int  
            int ascii1 = (int) ch1;  
            int ascii2 = (int) ch2;  
            
            System.out.println("The ASCII value of " + ch1 + " is: " + ascii1);  
            System.out.println("The ASCII value of " + ch2 + " is: " + ascii2);  
        }  
    }  

    Output:

    The ASCII value of A is: 65
    The ASCII value of a is: 97


    We can also take the user input for character by using the Scanner class and print the ASCII value accordingly as shown in the program below.

    import java.util.Scanner;
    
    public class AsciiValue    
    {  
        public static void main(String[] args)   
        {  
            Scanner sc = new Scanner(System.in);
            
            // User Input 
            System.out.print("Enter a character: ");  
            char ch = sc.next().charAt(0); 
            
            //assigning to int  
            int ascii1 = ch;  
            
            System.out.println("The ASCII value of " + ch + " is: " + ascii1);  
        }  
    }  

    Output:

    Enter a character: b
    The ASCII value of b is: 98


  • Java Program to Check for Leap Year

    The following Program to Check if the Entered year is a leap year or not, the if-else statement has been used. If you want to learn about the if-else statement in Java, click the link below.

    A leap year comes after every 4 years and has 366 days that year instead of 365 days. In the leap year, an additional day is added to the February month has 29 days instead of 28 days.

    Now let us understand through mathematical logic,

    • If a year is divisible by 4 then it is leap year.
    • If a year is divisible by 400 and not divisible by 100 then it is also a leap year.
    • Example: 2000, 2004, 2008, etc are the leap years.

    Java Program to Check for Leap Year

     //check for leap year in java
    
     import java.util.*;
    
     public class LeapYearJava
     {
       public static void main(String[] args)
       {
         int n;
         int year;
         Scanner sc = new Scanner(System.in);
    
         System.out.println("Enter the year");
         n = sc.nextInt();
    
         year = n;
         boolean leap = false;
    
         if (year % 4 == 0)
         {
           if (year % 100 == 0)
           {
             // year is divisible by 400, hence the year is a leap year
             if (year % 400 == 0)
               leap = true;
             else
               leap = false;
           }
           else
             leap = true;
         }
         else
           leap = false;
    
         //Display
         if (leap)
           System.out.println(year + " is a leap year.");
         else
           System.out.println(year + " is not a leap year.");
       }
     }

    Output:

    Enter the year
    2016
    2016 is a leap year.


  • Java Program to Check Whether the Given Number Is Binary or Not

    In this post, we will write a program on how to check whether given number is binary or not in java. Let start by knowing the Binary number and then see the example with an explanation.

    What is a Binary Number?

    binary number is a number expressed in the base-2 numeral system that is the number that contains 2 symbols to represent all the numbers. The symbols are 0 and 1.

    For example: 101011, 110011110, 10001111 are binary numbers.


    Let’s see an explanation to find out whether the given number is binary or not in java:

    There are many ways we can find the binary number in java, In this one, we will create a separate function and pass the number that needed to be check and print the result.

    First, take the user input with the Scanner class and pass that number to the numBinaryOrNot() function as an argument. Then declare a boolean variable (isBinary). After that execute while loop until the passed number is not equal to zero (copyNum != 0).

    Inside while loop, take the remainder and check if the remainder is greater than 1 or not. If it is greater then change the boolean value to false and break else divide the number by 10. The loop continues till all the numbers are checked.

    At last, check if the boolean value is still true then the number is binary number print the result else it is not a binary number.


    Java Program to Check Whether the Given Number Is Binary or Not

    import java.util.Scanner;
    
    public class CheckForBinary
    {
       static void numBinaryOrNot(int num)
       {
        boolean isBinary = true;
    
        int copyNum = num;
    
        while (copyNum != 0)
        {
          int temp = copyNum%10;  
    
          if(temp > 1)
           {
             isBinary = false;
             break;
           }
            else
           {
             copyNum = copyNum/10;    
           }
        }
    
         if (isBinary)
         {
            System.out.println(num+" is a binary number");
         }
         else
         {
            System.out.println(num+" is not a binary number");
         }
       }
     
      public static void main(String[] args)
      {
        Scanner sc=new Scanner(System.in);
        
        System.out.println("Enter a number");
        int num = sc.nextInt();
    
        numBinaryOrNot(num);
      }
    }

    The output to check for the binary number in java:

    Binary Number

  • Java Program to make a Calculator using a Switch Statement

    This Java program simply creates an option to chose the Operators just like any calculator. A switch statement is used for creating an option in programming that will make case for a different option and operate according to the option that the user provides. It will also take two operands (numbers) at the beginning.

    If you do not know about the Switch Case statement or Data Types in java, click the link below to learn about them as this program uses one.


    Java Program to make a Calculator using a Switch Statement

     //Making Calculator using a switch in Java
      
     import java.util.Scanner;
    
     public class CalculatorJava
     {
       public static void main(String[] args)
       {
         double result;
         char operator;
         Scanner reader = new Scanner(System.in);
    
         System.out.print("Enter first numbers: ");
         double num1 = reader.nextDouble();
    
         System.out.print("Enter second numbers: ");
         double num2 = reader.nextDouble();
    
         System.out.print("Choose an operator(+, -, *, /): ");
         operator=reader.next().charAt(0);
    
         //switch case 
         switch (operator)
         {
           case '+':
             result = num1 + num2;
             break;
    
           case '-':
             result = num1 - num2;
             break;
    
           case '*':
             result = num1 * num2;
             break;
    
           case '/':
             result = num1 / num2;
             break;
    
           default:
             System.out.printf("Error! operator is not correct");
             return;
         }
    
         //Displaying result
         System.out.printf("%.1f %c %.1f = %.1f", num1, operator, num2, result);
       }
     }

    Output:

    Enter first numbers: 5
    Enter second numbers: 3
    Choose an operator (+, -, *, /): -
    5.0 - 3.0 = 2.0


  • Java Program to Calculate the Simple Interest

    Here, you will learn how to calculate the Simple Interest in Java using the Formula ((p * r * t) / 100)) where,

    • p = Principal
    • r = Rate of Interest
    • t = Time Period

    The program takes the user input for Principal, Rate, and Time, calculates the result, and displays the result on the screen.

    If you do not know about the operators or Data Types in java, click the link below to learn about operators as this program is using one.


    Java Program to Calculate the Simple Interest

     //Simple Interest in Java
      
     import java.util.Scanner;
    
     public class SimpleInterestJava
     {
        public static void main(String args[]) 
        {
         float p, r, t, SI;
        
         Scanner scan = new Scanner(System.in);
        
         System.out.print("Enter the value for Principal: ");
         p = scan.nextFloat();
        
         System.out.print("Enter the value for Rate of interest: ");
         r = scan.nextFloat();
        
         System.out.print("Enter the value for Time period: ");
         t = scan.nextFloat();
         scan.close();
        
         SI = (p * r * t) / 100;
         System.out.print("Simple Interest is: " +SI);
        }
     }

    Output:

    Enter the value for Principal: 1000
    Enter the value for Rate of interest: 5
    Enter the value for Time period: 2
    Simple Interest is: 100.0

    The above source code to calculate the Simple Interest in Java is compiled and ran successfully on a windows system. Browse through Java Program to learn more.


  • Java Program to Calculate the Area of a Triangle

    Here, you will learn how to calculate the Area of a Triangle using the Formula [(Base* Height)/2]. The program takes the user input for the Base and Height of a triangle, calculates the result, and displays the result on the screen.

    If you do not know about the operators in java, click the link below to learn about operators as this program is using one.


    Java Program to Calculate the Area of a Triangle

     //Area of a traingle
    
     import java.util.Scanner;
    
     public class AreaOfTriangle 
     {
        public static void main(String args[]) 
        {   
            Scanner sc = new Scanner(System.in);
    
            System.out.println("Enter the base of the Triangle:");
            float base = sc.nextFloat();
    
            System.out.println("Enter the height of the Triangle:");
            float height = sc.nextFloat();
    
            //Area = (base*height)/2
            float area = (base* height)/2;
            System.out.println("Area of the Triangle is: " + area);      
        }
     }

    Output:

    Enter the base of the Triangle:
    8
    Enter the height of the Triangle:
    10
    Area of the Triangle is: 40.0