ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Java Program: Count the Number of String Characters in Java

Updated on November 1, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

How to count the number of characters inside a string in Java Programming?

Counting a number of characters inside a string is not that hard at all. Here we will use another Java predefined function. There are actually number of ways on how to count the characters inside the string but we will just use 1, which is the length(). Have you use length() predefined function before? Apart from length(), we will also use for loop to count the characters. So, the algorithm is like this: Count the characters in the first string entered by the user and add it to the characters of second string entered by the user. Sounds boring? Well, this is just a programming for fun, and there might be others who want to know it, so bear with this. (smile)

The Java Source Code for Counting the Characters inside a String

package count_the_numberofcharacters_inside_the_string;

import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);

        int count1 = 0;
        int count2 = 0;
        System.out.print("Enter your first name: ");
        String first_name = input.nextLine();

        System.out.print("Enter your last name: ");
        String last_name = input.nextLine();


        for(int i=0; i < first_name.length(); i++)
        {
            count1++;
        }
        System.out.println("firstname: " +count1);
        for(int i=0; i < first_name.length(); i++)
        {
            count2++;
        }
        System.out.println("last_name:"+ count2);
        System.out.println("Result:");
        System.out.println((count1+count2) + " is the sum of the 2 strings above.");
    }

}

Sample Output:

Is this hub useful to you? Please rate it or leave a comment. Happy Programming!

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      bhuvan_easwar 3 years ago

      In the 25th line the for loop has a slight mistake. change the first_name to last loop and try.