Blog

  • Java Program to Create Login Window using AWT Controls

    This article is based on the Java Program to create Login Window using AWT Controls. Here we will use the AWT components Label, Button and Textfield. We will see the code to create a user_name and password text field with login and signup buttons.

    AWT program in Java with output:


    Awt Program in java with Output to Create Login Window

    import java.awt.*;
    import java.awt.event.*;
    
    class LoginWindowAWT extends Frame
    {
        //Declaring text fields and Buttons
        TextField userName, password;
        Button btn1, btn2;
        
        LoginWindowAWT()
        {
            setLayout(new FlowLayout());
            this.setLayout(null);
            
            //Setting the name and password that will be displayed
            Label u_name = new Label("User Name:",Label.CENTER);
            Label pass = new Label("Password:",Label.CENTER);
            
            //username declaration
            userName = new TextField(20);
            this.add(u_name);
            this.add(userName);
    
            //Password declaration
            password = new TextField(20);
            this.add(pass);
            this.add(password);
            
            password.setEchoChar('#');
            
            //Button Declaration
            btn1 =new Button("LogIn");
            btn2 =new Button("SignUp");
            this.add(btn1);
            this.add(btn2);
            
            //Setting the display Bounds
            userName.setBounds(200,100,90,20);
            u_name.setBounds(70,90,90,40);
            
    
            password.setBounds(200,140,90,20);
            pass.setBounds(70,130,90,40);
    
            btn1.setBounds(100,260,70,40);
            btn2.setBounds(180,260,70,40);
     
        }
        public static void main(String args[])
        {
            //creating an object
            LoginWindowAWT ml=new LoginWindowAWT();
            
            //background Color
            ml.setBackground(Color.RED) ;
    
            ml.setTitle("Login Window AWT");
            ml.setVisible(true);
            ml.setSize(400,400);
            
        }
    }

    Output: Save the file with .java extension and open the command prompt on that directory and run the following code.

    C:\java>javac LoginWindowAWT.java
    C:\java>java LoginWindowAWT

    You will see the following result:


    This is the end of the article to create a Login Window with an AWT program in Java with output.
    Learn more about Java Programs.


  • Get Subarray between Specified Indexes in Java

    Before getting into the programming on subarray between specified indexes, let us first learn about the subarray.

    What is a subarray?

    For example, consider an array = [2,3,4], then the subarrays are [2], [3], [4], [2,3], [3,4], and [2,3,4]. But something like [2,4] would not be considered as subarray.

    For an array of size n, we can calculate non-empty subarrays by n*(n+1)/2.


    Get a subarray of an array between specified indexes in Java

    The various methods to get java array subarray between specified indices is as follows:

    1. Arrays.copyOfRange()

    It is the standard way to get a subarray of an array that returns a subarray from the specified range of an original array. Following is the example:

    int[] copyOfRange(int[] original, int from index number, int to index number)

    import java.util.Arrays;
    
    public class Main 
      {
        public static void main (String[] args) 
        {
            int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            int[] arrayResult = Arrays.copyOfRange(arr, 3, 9);
            System.out.println(Arrays.toString(arrayResult));
        }
      }

    Output:

    [4, 5, 6, 7, 8, 9]


    2. System.arraycopy()

    This is also one of the methods that are used to copy from the specified position of the source array to the destination array.

    public static vois arraycopy(Object source, srcPpos, Object destination, destPos, int length)

    Example of System.arraycopy():

    import java.util.Arrays;
    
    public class Main 
     {
        public static void main (String[] args) 
        {
            int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
            int[] arrayResult = new int[3];
            System.arraycopy(arr, 3, arrayResult, 0, 3);
            System.out.println(Arrays.toString(arrayResult));
        }
    }

    Output:

    [4, 5, 6]

    3. Arrays.copyOf()

    This is also another way of copying the specified array to a specified type of array. But if the sub-array is not at the first index but is at some intermediate index, this method won’t work.

    Example of Arrays.copyOf():

    import java.util.Arrays;
    
    class Main
    {
       public static void main(String[] args)
       {
          String[] array = new String [] {"A", "B", "C", "D", "E", "F", "G", "H", "I"};
    		
          System.out.println("The sub_array:");
           //Here startingPosition is 0
          String[] sub_array = Arrays.copyOf(array, 6, String[].class);
          System.out.println(Arrays.toString(sub_array));
       }
    }

    Output:

    The sub_array:
    [A, B, C, D, E, F]


    4. Custom Method

    This is a method where we can write our own custom method to copy the specified elements from an array to the new array.

    Example to demonstrate the Custom method:

    import java.util.Arrays;
    
    class Main
    {
     public static void main(String[] args)
     {
      String[] array = new String[] { "A", "B", "C", "D", "E", "F", "G", "H" };
      int startPos = 3, endPos = 6;
      int finalPos = (endPos - startPos) + 1;
    
       System.out.println("The sub_array:");
       String[] sub_array = new String[finalPos];
       for (int i = 0; i < sub_array.length; i++) 
       {
        sub_array[i] = array[startPos + i];
       }
    
      System.out.println(Arrays.toString(sub_array));
     }
    }

    Output:

    The sub_array:
    [D, E, F, G]


    5. Subarray: without copying

    Sometimes it may cause a problem in performance while copying the large part of an array. And in such cases, instead of locating a new array, we can use the instance of the same array.

    Example of subarray through callback

    import java.util.function.Consumer;
    
    public class Main 
    {
     public static void main (String[] args) 
     {
      int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
      System.out.println("The result:");
      arrayResult(array, 3, 9, System.out::println);
     }
    
     public static void arrayResult (int[] ts, int from, int to,Consumer<Object> rangeConsumer) 
     {
      for (int i = from; i < to; i++) 
            rangeConsumer.accept(ts[i]);
          
     }
    }

    Output:

    The result:
    4
    5
    6
    7
    8
    9


  • Java Program to Check if the String is empty or not

    In this tutorial, we will write a java program to check whether the string is empty or not.

    The strings are defined in the program and it is passed to the method as an argument. After checking for null and empty (built-in empty() function is used), a true or false value is returned accordingly. And finally displays the result.

    The condition checking in this program is performed with the help of if..else statement:


    Check if the String is empty or not in Java

    //check if the string is empty or not in java
    
     public class CheckForEmpty
     {
         public static void main(String[] args) 
         {
            String string1 = "Simple2Code";
            String string2 = "";
            
            if(checkEmpty(string1 ))
                System.out.println("string1 is empty.");
            else
                System.out.println("string1 is not empty.");
                
            if(checkEmpty(string2 ))
                System.out.println("string2 is empty.");
            else
                System.out.println("string2 is not empty.");
         }
         
         public static boolean checkEmpty(String str) 
         {
            if(str != null && !str.isEmpty())
            {
              return false;
            }
            else
            {
              return true;
            }
         }
     }

    Output:

    string1 is not empty.
    string2 is empty.


  • Java Program for user String Input

    It is a simple demonstration to show how to take a string as an input from the user.

    The only thing you need to be concerned about is the data type that you declare in the program that is the String data type as shown below in the program.


    How to take user Input as String in java

     //user String input in java
    
     import java.util.Scanner;
     public class UserInput
     {
        public static void main(String []args)
        {
           String str;
           Scanner in = new Scanner(System.in);
      
          //Get input String
          System.out.println("Enter a string: ");
          str = in.nextLine();
          
          System.out.println("Entered String is: "+str);
         } 
     }

    Output:

    Enter a string:
    I am Coding right now.
    Entered String is: I am Coding right now.


  • Java Program to Count Letters in a String

    In this tutorial to Count Letters in a String in java, we will see two examples to count the number of letters present in a String in Java.

    • The first one, where the String is already defined in a program.
    • The second one, where the String is taken as input from the user

    Both the program uses for loop and if statement to count the letters so if you do not know about them, click the link below.


    1. Java Program to Count the Letters in a String.

     //count letters in a string 
    
     public class CountLetters
     {
        public static void main(String []args)
        {
           String str = "ab5gh6d"; //given String
           int count = 0;
           
           System.out.println("Given String is: "+str);
     
           for (int i = 0; i < str.length(); i++) 
           {
              if (Character.isLetter(str.charAt(i)))
              {
                count++;
              }
           }
           System.out.println("Number of Letters in a given string: "+count);
        }
     }

    Output:

    Given String is: ab5gh6d
    Number of Letters in a given string: 5


    2. Java Program to Count the Letters in a String (user’s input)

     //count letters in a string (user inputs)
     
     import java.util.Scanner;
    
     public class CountLetters
     {
      public static void main(String []args)
      {
        String str;
        int count = 0;
        
        Scanner sc = new Scanner(System.in);
    
       //Get input String
        System.out.println("Enter a string: ");
        str = sc.nextLine();
        
        System.out.println("Entered String is: "+str);
    
        for (int i = 0; i < str.length(); i++) 
        {
          if (Character.isLetter(str.charAt(i)))
          {
            count++;
          }
        }
        System.out.println("Number of Letters Present in a String are: "+count);
      }
     }

    Output:

    Enter a string: 45ab6gh

    Entered String is: 45ab6gh
    Number of Letters Present in a String are: 4


  • Java Program to Create a Calculator using Switch Case

    The program shows how to Create a Calculator using Switch Case in java. The program uses a scanner class to take the inputs from the user. The switch case is mostly used when it is necessary to give options to the users.

    As we all have used a basic calculator before and we know how it works. It basically lets you input two numbers (operands) and one operator in between. The operator could be one of the following:

    • + = Addition
    • = Subtraction
    • * = Multiplication
    • / = Division

    Similarly, the program below gives you an option for the operation to perform on operands.

    If you do not know about the operators in java and the switch case statements then click the link below.


    Java Program to Create a Calculator using Switch Case

    //Making Calculator in java
      
     import java.util.Scanner;
    
     public class CalculatorJava 
     {
       public static void main(String[] args) 
       {
        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 (+, -, *, /): ");
        char operator = reader.next().charAt(0);
        double result;
        
        //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 Convert Fahrenheit to Celsius and Vice-Versa

    The program shows how to convert Fahrenheit to Celsius and Vice-Versa in java using a switch statement. The program uses a scanner class to take the inputs from the user.

    Switch case is mostly used when it is necessary to give options to the users. The Java program below gives you two options to choose from case 1 and case 2 that calculate the conversion of Fahrenheit to Celsius and Celsius to Fahrenheit respectively.

    If you do not know the working process of the switch case statement then click the link below.


    Java Program to Convert Fahrenheit to Celsius and Vice-Versa using Switch Case

     //convert Fahrenheit to Celsius and vice-versa using switch in java
    
     import java.util.Scanner;
    
     class FahrenheitCelsius
     {
       public static void main(String args[])
       {
          Scanner sc = new Scanner(System.in);
          
        
          System.out.println("Press 1 to convert Celsius into Fahrenheit");
          System.out.println("Press 2 to convert Fahrenheit into Celsius");
        
          System.out.println("Enter your Choice:");
          int ch = sc.nextInt();
    
          switch(ch)
          {
            case 1:  System.out.println("Enter temperature in Fahrenheit:");
                      float F = sc.nextFloat();
                      float C = ((5/9.0f)*(F-32));
                      System.out.println("Temperature in Centigrade degrees:"+C);
                      break;
    
            case 2: System.out.println("Enter temperature in Celsius:");
                    float c = sc.nextFloat();    
                    float f = ((c - 32)*5)/9;
                    System.out.println("Temperature in Fahrenheit degrees:"+f);
                    break;
    
                        
    
            default:System.out.println("Invalid Input");
                    break;
        }
       }
     }

    Output:

    Press 1 to convert Celsius into Fahrenheit
    Press 2 to convert Fahrenheit into Celsius
    Enter your Choice:
    2 
    Enter temperature in Celsius:
    41
    Temperature in Fahrenheit degrees:5.0

  • Java Program to Calculate Simple Interest, Amount and Compound Interest using a Switch

    The program shows how to Calculate Simple Interest, Amount, and Compound Interest using a Switch in java. The program uses a scanner class to take the inputs from the user.

    The switch case is mostly used when it is necessary to give options to the users. The following program gives users 3 different options to choose from and it displays results accordingly.

    If you do not know the working process of the switch case statement then click the link below.


    Java Program to Calculate Simple Interest, Amount and Compound Interest

     //calculate Simple Interest, Amount in java
     //and Compound Interest using switch 
    
     import java.util.Scanner;
     import java.io.*;
     
     class InterestAmountCI
     {
      public static void main(String args[])
      {
            Scanner sc = new Scanner(System.in);
            
          
            System.out.println("Press 1 to find Simple Interest");
            System.out.println("Press 2 to find the Amount");
            System.out.println("Press 3 to find the Compound Interest");
            
            System.out.print("Enter your Choice: ");
            int ch = sc.nextInt();
    
            switch(ch)
            {
              case 1:  System.out.println("Enter Principal, Rate and Time:");
                       float principal = sc.nextFloat();
                       float rate = sc.nextFloat();
                       float time = sc.nextFloat();
                        
                       float SI =principal*rate*time/100;
                       System.out.println("Simple Interest: "+SI);
                       break;
    
              case 2: System.out.println("Enter principal and Interest:");
                      float P = sc.nextFloat(); 
                      float I = sc.nextFloat();
                      
                      float Amount =P + I;
                      System.out.println("Amount: "+Amount);
                      break;
              case 3: System.out.println("Enter principal, Rate and Time:");
                      float Pr = sc.nextFloat(); 
                      float r = sc.nextFloat();
                      float t = sc.nextFloat();
                      double CI = Pr *  Math.pow( 1.0 + r, t);
    
                      System.out.println("Compound Interest: "+CI);
                      break;
    
                          
    
              default:System.out.println("Invalid Input");
                      break;
            }
      }
     }

    Output:

    Press 1 to find Simple Interest
    Press 2 to find the Amount
    Press 3 to find the Compound Interest
    Enter your Choice: 1
    Enter Principal, Rate and Time:
    1000
    5
    2
    Simple Interest: 100.0

  • Java Program to Calculate the Area of Different Geometric Figures

    The program shows how to Calculate the Area of Different Geometric Figures in java using a switch statement. The program uses a scanner class to take the inputs from the user.

    The switch case is mostly used when it is necessary to give options to the users. The following program gives users seven cases or options to choose from and it displays results accordingly.

    If you do not know the working process of the switch case statement then click the link below.


    Java Program to Calculate the Area of Different Geometric Figures using Switch Case

     //area of different geometric figures using switch case in java
    
     import java.util.Scanner;
    
     public class AreasSwitch
     {
      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 for the Circumference of a Circle");
        System.out.println("6 for the Perimeter of a Square");
        System.out.println("7 for the Perimeter of a Rectangle");
        System.out.println("Enter 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.println("Enter radius for circle:");
                  float rad = sc.nextFloat();
                  float cir = 3.14f*2f*rad;
                  System.out.println("Circumference:"+cir);
                  break;
    
    
          case 6: System.out.println("Enter side for square:");
                  int side = sc.nextInt();
                  int peri = 4*side;
                  System.out.println("Perimeter:"+peri);
                  break;
          
          case 7: System.out.println("Enter length and breadth for rectangle:");
                  int lg = sc.nextInt();
                  int br = sc.nextInt();
                  int per = 2*(lg+br);
                  System.out.println("Perimeter:"+per);
                  break;             
    
          default:System.out.println("Invalid Input");
                  break;
        }
      }
     }

    Output:

    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 for the Circumference of a Circle
    6 for the Perimeter of a Square
    7 for the Perimeter of a Rectangle
    Enter your Choice:
    4
    Enter length and breadth for rectangle:
    5
    8
    Area:40

  • Java Program to Check for the Negative Number

    The program shows how to Check for the Negative Number in java. This program is also a good demonstration to know the working process of the if-else statement.

    If you do not understand the program, perhaps you may want to learn about the if-else statement first.


    Java Program to Check for the Negative Number

     //check for the negative number using if-else statement in java
    
     public class IfElseNegNumber
     {
       public static void main(String[] args) 
       {
         int num = 5;
          
          if(num < 0)  //checking condition for true
          { 
            System.out.println("Number is negative");
          }
          else //executed if the condition is false
          { 
            System.out.println("Number is positive");
          }
            
          System.out.println("Always executed");
       }
       
     }

    Output:

    Number is positive
    Always executed