TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java length Example: Get Character Count

Use the length method on strings to get their character counts.
Length. A String object may be null. But if it exists, it has zero or more characters. This character count is its length. With length() we get this number.Strings
In a loop over characters, we can proceed from 0 to length() minus 1. A string's length has many uses in programs. We can take the length of a literal directly.
An example. We use string literals. These are specified directly in the program. Then with the plus operator, we combine (concatenate) these strings.

Concat: The plus-operator combines strings. We combine the data from two or more strings this way.

Length: We call the length method on each string variable reference. This returns the character count.

Java program that uses strings public class Program { public static void main(String[] args) { // Create strings with literals. String value1 = "Java"; String value2 = "Programmer"; // Concatenate strings. String value3 = value1 + " " + value2; // Print string. System.out.println(value3); // Get string lengths. int length1 = value1.length(); int length2 = value2.length(); int length3 = value3.length(); // Print lengths. System.out.println(length1); System.out.println(length2); System.out.println(length3); } } Output Java Programmer 4 10 15
Literal length. This program uses a literal "abc" and immediately takes the length of that literal. This returns the number 3. This is valid Java syntax.
Java program that uses length, literal public class Program { public static void main(String[] args) { // Take the length of a literal directly. int length = "abc".length(); System.out.println(length); } } Output 3
Some notes. When using string literals in a program, we want to avoid confusing code. It is clearer to use length() on a literal than encode the magic value 3 in a program.
A summary. The length() method is called on a String object. The String must not be null. Length returns the character count in the string data.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf