In this demonstation you will be shown how to get the length of a string using the length() function in Java
The length() is a built-in Java function that returns its length by appending to a string. All the white spaces and special characters are calculated as part of the length.
Here is how you get the length of a string in Java
- Use the length() method
- Spaces within the string will be counted as well
Here is an example without white space:
String str = "string";
System.out.print(str.length()); //Outputs 6
As you can see above, the length() method is appended to a string which in this case is the word "string". It counts the amount of letters in the word.
Here is an example with space:
String str = "this is a string";
System.out.print(str.length()); //Outputs 16
The length() method will count the white space as part of the length of the string.
Here is an example with white space and special character:
String str = "this is a string!!";
System.out.print(str.length()); //Outputs 18
The length() method will count the white space and special characters as part of the length of the string.