Blog

  • Java Program to Count the Number of Lines in a File

    In this tutorial, you will learn how to Count the Number of Lines in a File in java. To understand it better, you may want to check the following first:


    Java Program to Count the Number of Lines in a File

    First, save the content in a text file with the same name that you enter in a program.
    For this example, a text file saved with the name javaCode.txt

    javaCode.txt

    Welcome to Simple2Code.
    Let Start
    first tutorial
    second Program

    Source Code:

    //count number of lines in a file
    
     import java.io.BufferedReader;
     import java.io.File;
     import java.io.FileReader;
     import java.io.IOException;
     
     public class LineCount 
     {
      public static void main(String[] args) throws IOException 
      {
        File f = new File("javaCode.txt");
        int count=0;   
            
        FileReader fr = new FileReader(f);  
        BufferedReader br = new BufferedReader(fr); 
        
        String s;         
            
        while((s=br.readLine())!=null) //Reading Content 
        {
          count++; //increases for each line
        }
        fr.close();
        //Display number of line
        System.out.println("Total number of line:"+count); 
      }
     
     }

    Output:

    Total number of line: 4


  • Java Program to Copy Content from one File to another File

    In this tutorial, you will learn how to copy the content of one file to another in java. Here the new file is created where the content of another file is copied to this newly created file.


    Java Program to Copy Content from one File to another File

    First, save the content in a text file with the same name that you enter in a program.
    For this example, a text file saved with the name javaCode.txt

    javaCode.txt

    Welcome to Simple2Code.
    Let Start
    first tutorial
    second Program

    And after the execution new file will be created as named copiedJavaCode.txt. And the content will be copied to this text file.

    Source Code:

     //copy content from one to another file 
    
     import java.io.*;
    
     public class CopyFile
     {
        public static void main(String[] args) throws IOException 
      {
          File f1 = new File("javaCode.txt");      //saved file
          File f2 = new File("copiedJavaCode.txt");   //destined file
          
          FileReader fr = new FileReader(f1);      //file reader object 
          BufferedReader br=new BufferedReader(fr);  //buffer reader object
          FileWriter fw= new FileWriter(f2); //file writer object 
          
          String s=null;
          
          while((s = br.readLine())!=null) //Copying Content to the new file
          {
            fw.write(s);
            fw.write("\n");
            fw.flush();
          }
            fw.close();
            
          System.out.println("Successfully Copied.");
          System.out.println("Check the copiedJavaCode.txt.");
        }
     
     }

    Output: After execution check your copiedJavaCode.txt file where all the content is copied from javaCode.txt file.

    Successfully Copied.
    Check the copiedJavaCode.txt.


  • Java Program to Check Whether a New file is Created or Already Exists

    In this tutorial, we will write a program to check whether a new file is created or already exists in java. This java program check if the file is already created in that particular directory or it is already present.

    The program also uses try and catch for exception handling. If you want to learn about Java files and Exceptions, click the link below.


    Java Program to Check Whether a New file is Created or Already Exists

    //check whether new file is created or already exists 
    
     import java.io.*;  
     public class FileCreated 
     {  
      public static void main(String[] args) 
      {  
    
        try {  
          File file = new File("javaCode.txt");  
          if (file.createNewFile()) {  
              System.out.println("New File is created.");  
          } else {  
              System.out.println("File already exists.");  
          }  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    
      }  
     }

    Output:

    New File is created.

    A new file will be created in the same directory.


  • Java Program to Append Content into a File

    This tutorial shows you how to append Content into a file in java.

    Append means to add something at the end. Similarly, the following java program adds new Content into a file. File in-built function append() is used to add new content at the end.

    If you do not about the file system in java then click the link below.


    Program to Append Content into a File in Java

     //append content into a file 
    
     import java.io.File;
     import java.io.FileWriter;
     import java.io.IOException;
     
     public class FileAppend
     {
      public static void main(String[] args) throws IOException 
      {
        File f = new File("javaCode.txt");     
        FileWriter fw = new FileWriter(f,true);  //Create filewriter object
    
        fw.append("Welcome to Simple2Code\n");  //Append the Content 
    
        fw.flush();          
        fw.close();
    
        System.out.println("Check javaCode.txt.")
      }
     
     }

    Output:

    Check javaCode.txt.

    Open the file that will be created in the same directory after execution.
    javaCode.txt

    Welcome to Simple2Code.


  • Java Program to Find the Number of Vowels and Consonants in a String

    The program to find the number of vowels and consonants present in a String in java is simple. It checks each of the characters in strings and compares it with vowels (i.e. a, e, i, o, u).

    When the program finds the character equals to vowel then it increases the vow integer else cons integer increases. And at last, the result is displayed.

    You may also take the user input instead of declaring the String in a Program. Following the below to take a user input.


    Java Program to Find the Number of Vowels and Consonants in a String

     //number of vowels and consonants in a string 
    
     public class CountVowelConsonants
     {
       public static void main(String[] args)
       {
         String str = "Learning To Code";
         int vow = 0, cons = 0;
         str = str.toLowerCase();
    
         for (int i = 0; i < str.length(); ++i)
         {
           char ch = str.charAt(i);
           if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u')
           {
             ++vow;
           }
           else if ((ch >= 'a' && ch <= 'z'))
           {
             ++cons;
           }
         }
    
         System.out.println("Number of Vowels : " + vow);
         System.out.println("Number of Consonants: " + cons);
       }
     }

    Output:

    Number of Vowels : 6
    Number of Consonants: 8


  • Java Program to Count Total Character in a String

    In this tutorial, we will see how to Count Total Characters in a String in java.

    The program below counts the number of letters present in the sentence (String) and displays the total character present in number.

    The program checks for spaces present in the Strings and if gets space while checking each character then it will skip the spaces, charAt() function is used in the following java program.

    Although if you want to know about the String and loop that are used in the program below. you may click the link below:

    We will see two Example:

    1. Where the String is already defined in the program.
    2. Where the string is taken as an input from the user.


    1. Program to Count Total Character in a String in Java

     //count total character in a string
    
     public class CountCharString
     {    
      public static void main(String[] args) 
      {    
        String str = "I am learning java";    
        int count = 0;  
          
        //counting String
        for(int i = 0; i < str.length(); i++) 
        {    
          if(str.charAt(i) != ' ')    
              count++;    
        }    
              
        //Displays the total character, space exclused    
        System.out.println("Total character in a given string: " + count);    
      }    
     }

    Output:

    Total character in a given string: 15


    2. Program to Count Total Character in a String in Java

    We will see the example where we will get the String from the user inputs in the program as shown below:

    //count total character in a string (user inputs)
     
     import java.util.Scanner;
    
     public class CountCharString
     {    
       public static void main(String[] args) 
       {    
         String str;    
         int count = 0;  
         
         Scanner in = new Scanner(System.in);
      
          //User Input
          System.out.println("Enter a string: ");
          str = in.nextLine();
                 
          //Excluding Space  
          for(int i = 0; i < str.length(); i++) 
          {    
             if(str.charAt(i) != ' ')    
                count++;    
          }    
                 
          //Displays the total character, space exclused    
          System.out.println("Total character in a entered string: " + count);    
         }    
     }

    Output:

    Enter a string:
    I am learning java
    Total character in a entered string: 15


  • Java Program to Find the Frequency of a Character

    In this tutorial, we will write a program to calculate the frequency of Characters present in a String in java.

    Frequency refers to the number of times that have occurred. In this program, we will count how many times each character is repeated in a String and display the result for each word’s frequency.

    The program splits each word with space count present after every word, toCharArray() function is used in the following java program.

    Although if you want to know about the String and loop that are used in the program below. you may click the link below:

    We will see two examples:

    1. Where the String is already defined in the program.
    2. Where the string is taken as an input from the user.


    1. Program to find the frequency of Words in Java

    //find a frequency of a character 
    
    public class FrequencyOfCharacter
    {
      public static void main(String[] args)
      {
        int i, j;
        String str = "Beautiful Beach";
        int[] frequency = new int[str.length()];
    
        char string[] = str.toCharArray();
    
        for (i = 0; i < str.length(); i++)
        {
          frequency[i] = 1;
          for (j = i + 1; j < str.length(); j++)
          {
            if (string[i] == string[j])
            {
              frequency[i]++;
    
             	//Set string[j] to 0  
              string[j] = '0';
            }
          }
        }
    
        //Displays the characters with their frequency    
        System.out.println("Following Lists the characters and their frequency:");
        for (i = 0; i < frequency.length; i++)
        {
          if (string[i] != ' ' && string[i] != '0')
            System.out.println(string[i] + "->" + frequency[i]);
        }
      }
    }

    Output:

    Following Lists the characters and their frequency:
    B->2
    e->2
    a->2
    u->2
    t->1
    i->1
    f->1
    l->1
    c->1
    h->1

    2. Program to find the frequency of Words in Java, user’s input

    //find a frequency of a character 
    
    import java.util.Scanner;
    
    public class FrequencyOfCharacter
    {
      public static void main(String[] args)
      {
        int i, j;
        String str;
        Scanner sc = new Scanner(System.in);
    
        //User Input
        System.out.println("Enter a string: ");
        str = sc.nextLine();
    
        int[] frequency = new int[str.length()];
    
        char string[] = str.toCharArray();
    
        for (i = 0; i < str.length(); i++)
        {
          frequency[i] = 1;
          for (j = i + 1; j < str.length(); j++)
          {
            if (string[i] == string[j])
            {
              frequency[i]++;
    
              //Set string[j] to 0  
              string[j] = '0';
            }
          }
        }
    
        //Displays the characters with their frequency    
        System.out.println("Following Lists the entered characters and their frequency:");
        for (i = 0; i < frequency.length; i++)
        {
          if (string[i] != ' ' && string[i] != '0')
            System.out.println(string[i] + "->" + frequency[i]);
        }
      }
    }

    Output:

    Enter a string: 
    Beautiful Beach
    Following Lists the characters and their frequency:
    B->2
    e->2
    a->2
    u->2
    t->1
    i->1
    f->1
    l->1
    c->1
    h->1

  • Java Program to Find a Frequency of Words

    In this tutorial, we will see how to calculate the frequency of words present in a String in java.

    Frequency refers to the number of times that have occurred. In this program, we will count how many time each word are repeated and display the result for each word’s frequency.

    The program splits each word with space count present after every word, split() and equals() functions are used in the following java program.


    Java Program to Find a Frequency of Words

    //find a frequency of words
    
     public class RepeatedWord
     {
     
      public static void main(String[] args)
      {
          String input="Welcome to java java Simle2code to java";  //String
          
          String[] words = input.split(" ");  //Split the word from String
          int wc = 1;    //word count initiated
          
          for(int i=0; i < words.length;i++)  
          {
            for(int j = i+1; j < words.length;j++) 
            {
             if(words[i].equals(words[j]))  //Checking for both strings are equal
             {
               wc = wc+1;    //if equal increment the count
               words[j]="0"; //Replace repeated words by zero
             }
            }
            if(words[i]!="0")
            System.out.println(words[i]+"--"+wc); //Display
            wc=1;
            
          }  
      }
    }

    Output:

    Welcome--1
    to--2
    java--3
    Simle2code--1


  • 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.