Author: admin

  • Java Program to Count the Number of Words Present in a text file

    In this tutorial, we will see the example of how to count the number of words present in a text file in java.

    First, create a text file with any name you like. In this example, inputInfo.txt is the file name. Then insert some sentences in that text file. The following java code will count the number of words present in that file.

    Before we start, it is important that you have an idea of the following, as this program uses them.


    Java Program to count the number of words present in a file

    //count the number of words present in a text file 
    
     import java.io.BufferedReader;  
     import java.io.FileReader;  
       
     public class CountNoOfWords
     {  
        public static void main(String[] args) throws Exception 
        {  
        String str;  
        int count = 0;  
    
        //file in read mode  
        FileReader f = new FileReader("inputInfo.txt ");  
        BufferedReader br = new BufferedReader(f);  
    
      
        while((str= br.readLine()) != null) 
        {  
          //Splits into words  
          String words[] = str.split(""); 
    
          //Counts each word  
          count = count + words.length;  
    
        }  
    
        System.out.println("Number of words present in given file: " + count);  
        br.close();  
        }  
     }

    Output:

    Number of words present in given file: 72


  • Java Program to Create a Calculator Using AWT Controls

    Today in this java programming we will learn a Java Program to Create a Calculator Using AWT Controls(Abstract Window Toolkit). This will be a basic calculator with a user interface. The AWT components we will be using are Textfields, Buttons, and labels.

    As we know a simple calculator requires two fields for input and one field to show the result of the operation performed on those two operands.


    Program to create Calculator in Java using AWT

    Source Code:

    import java.awt.*;
    import java.awt.event.*;
     
    class Calculator implements ActionListener
    {
    	//Declaring Objects
    	Frame f = new Frame("Calculator AWT");
    	Label l1 = new Label("First Number:");
    	Label l2 = new Label("Second Number:");
    	Label l3 = new Label("Result:");
    	
    	TextField t1 = new TextField();
    	TextField t2 = new TextField();
    	TextField t3 = new TextField();
    	
    	Button b1 = new Button("Add");
    	Button b2 = new Button("Sub");
    	Button b3 = new Button("Mul");
    	Button b4 = new Button("Div");
    	Button b5 = new Button("Quit");
    	
    	Calculator()
        {      
           //Background Color
           f.setBackground(Color.GRAY) ;
    
    		//Giving Bounds for Labels
    		l1.setBounds(50,100,100,20);
    		l2.setBounds(50,140,100,20);
    		l3.setBounds(50,180,100,20);
    		
            //Giving Bounds for Labels
    		t1.setBounds(200,100,100,20);
    		t2.setBounds(200,140,100,20);
    		t3.setBounds(200,180,100,20);
    		
            //Giving Bounds for Labels
    		b1.setBounds(50,230,50,20);
    		b2.setBounds(110,230,50,20);
    		b3.setBounds(170,230,50,20);
    		b4.setBounds(230,230,50,20);
    		b5.setBounds(290,230,50,20);
    		
    		//Add components to the frame
    		f.add(l1);
    		f.add(l2);
    		f.add(l3);
    		
    		f.add(t1);
    		f.add(t2);
    		f.add(t3);
    		
    		f.add(b1);
    		f.add(b2);
    		f.add(b3);
    		f.add(b4);
    		f.add(b5);
    		
            //Action Buttons
    		b1.addActionListener(this);
    		b2.addActionListener(this);
    		b3.addActionListener(this);
    		b4.addActionListener(this);
    		b5.addActionListener(this);
    		
    		f.setLayout(null);
    		f.setVisible(true);
    		f.setSize(400,350);
    	}
    	
    	public void actionPerformed(ActionEvent e)
    	{
    		int n1=Integer.parseInt(t1.getText());
    		int n2=Integer.parseInt(t2.getText());
    		
    		//Buttons Operations
    		if(e.getSource() == b1)
    		{
    		  t3.setText(String.valueOf(n1+n2));
    		}
    			
    		if(e.getSource() == b2)
    		{
    		  t3.setText(String.valueOf(n1-n2));
    		}
    		
    		if(e.getSource() == b3)
    		{
    		  t3.setText(String.valueOf(n1*n2));
    		}
    		
    		if(e.getSource() == b4)
    		{
    		  t3.setText(String.valueOf(n1/n2));
    		}
    		
    		if(e.getSource() == b5)
    		{
    		  System.exit(0);
    		}
    	}
    	
    	public static void main(String args[])
    	{
                new Calculator();
    	}
    }

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

    C:\java>javac Calculator.java
    C:\java>java Calculator

    You will see the following result:

    This is the end of the article Simple calculator program in java using AWT with output.
    Learn more about Java Programs.


  • 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