How to find String length in java with and without string method

Get String length with String length() method

To find String length in java there is a method length().

This method is used to get length of string.

Signature of length method is:

Length method returns the length of the string. it counts the number of unicode in string.

This is very simple way to get length of a string in java.

Output

Finding the length of unicode string in java

Here we are considering hindi language stored in String. We use length() to get the string length.

You can take any unicode character to check length string length() works properly.

Output

Finding the String length in java of unicode characters

Here we have stored a unicode value in String and finding its length.

Output

Using toCharArray() to find String length in java

toCharArray() is another method in String class to convert String to character array.

Signature of toCharArray() is

In above program String is converted to character array using toCharArray().

Character array is have a field length. This length property finds the length of character array.

Output

Using Function to find the String length in java

In above program you find length of Java String in main method.

Here we have created two static methods length() and length1().

these two methods are accepting string and getting its length.

Using Recursion to find String length

Here we are using recursion to find the length of string.

When a function is called it is checking the lenth of string if string is empty then return zero else call again itself with adding one to return value.

On each recursive call we are eliminating first character from string.

Output

Hope you learn and understand how to get length of string as we discussed different ways to find string length.

Keep Reading other topics.

Inheritance in Java-Types and Examples

Inheritance in Java is the process of acquiring the properties of one class object into another class object.

It allows the hierarchical classification. Inheritance also provides the facility of reusability.

In Java programming, a class that is inherited is called a superclass or sub class or parent class and class that does the inheriting is called sub class or child class.     

If we want to inherit a class, we simply incorporate the definition of one class into another class by using extends keyword.

General form of a class declaration that inherits a super class

Type of Inheritance in Java

There are following type of inheritance

  1. Single level Inheritance
  2. Multi-level Inheritance
  3. Hierarchical Inheritance
  4. Hybrid Inheritance

Note: Java does not support multiple inheritance.        

Single level Inheritance

Property of single level inheritance is as below

  • One Super class and one sub class
  • Sub class inherits the features of super class

java single inheritance
Fig:java single inheritance

Write a program for single level inheritance.

Multi level Inheritance

In multi level inheritance inheritance exists in multiple level.

  • One Super Class
  • It has a child class
  • Child class has a child class

This process may continue and each child class inherits feature of all parent class.

Multilevel Inheritance

program for Multi level inheritance.

Result

Hierarchical Inheritance

java hierarchical inheritance
java hierarchical inheritance

Hybrid  Inheritance

java Hybrid  Inheritance
java Hybrid Inheritance

Result

Note: A subclass can access the public member of super class. A subclass can’t access the private member of super class.

Super Class Cant Access Sub Class Member

A sub class can access all the public member of super class but reverse is not true. Super class cannot access sub class data.

Result

A sub class can’t access the private member of super class.   

Result

Write a program for Hierarchical Inheritance.

Result

String in Java- Constructor methods and examples

Java String is defined in java.lang.String.

Java String is a sequence of characters quoted in double quote (” “).

String Constructors

Java String Methods

There are many methods avaible in string class few common and widely used methods are

Java String Method charAt()

This method takes one integer argument and return a character specified at index position.

For any string the index value starts from 0 to string length -1 position.

If passed index value not in valid range then it throws IndexOutOfBoundsException.

For example string Hello Friends contains 13 characters starting from 0 to 12 H is first position with index value 0, F is in seventh position with index value 6 and s is in 13 position with index value 12.


Using number other then 0 to 12( 0 to length()-1) will result in IndexOutOfBountException

Signature:

public char charAt(int index)

Parameters:

index -Integer index value to get character at specified index position.

Return:

Character at passed index value.

Exception Throws:

IndexOutOfBoundsException If index value in not between 0 to String length()-1

Example

Sr NoConstructor and description
1String()
Create a new empty string object
2String(byte[] bytes)
Construct a string object with byte array
3String(char[] value)
Construct a string object with character array
4String(String original)
Create a string with another string
5String(StringBuffer buffer)
Create a string with StringBuffer object
6String(StringBuilder builder)
Create a string with StringBuilder object
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class StringChatAtExample {
 
    public static void main(String args[]) {
        String test = "Java String charAt() example";
        char firstCharacter = test.charAt(0);
        char sixthCharacter = test.charAt(5);
        char lastCharacter = test.charAt(test.length() - 1);
        System.out.println("String:" + test);
        System.out.println("Character at first position: " + firstCharacter);
        System.out.println("Character at sixth position: " + sixthCharacter);
        System.out.println("Character at last position: " + lastCharacter);
    }
 
}

Result

Now Print all characters with its index value

Example

Result

Java String Method compareToIgnoreCase()

This method is used to compare two string with case ignorance and compare both string lexicographically. If both strings are same then it returns 0. If first string is greater then another then it returns positive integer, if second string is greater then first then it returns negative integer value.

Signature

public int compareToIgnoreCase(String str)

Parameters

str – String value that will compared with string.

Return

Integer value. if string is greater then passed str value then it returns positive integer if both strings are equal then it returns zero if passed str is greater then string then this method returns negative integer value.

Example1

Result

In above program comparing same string is returning 0. In second println() statement A is lexicographically smaller then b so it is returning -1. In third println() statement C is lexicographically greater then b so it is returning 1 and so on.

Example2

Result

Java String Method indexOf with int parameter

indexOf(int ch) method is used to get the first occurrence of a character in given string. This method takes a character input (in Unicode code units) and return the index value of character in string, if character not found in string then it returns -1.

Signature

public int indexOf(int ch)

Parameters

A charcter value in unicode code point.

Return

Returns the int value that represents the first occurance of the character in string, if character not fount in string then it returns -1.

Example

Java String Method indexOf()

indexOf method is used to get the first occurrence of a sub string in given string. This method takes a string input and return the index value of it in given string object, if sub string not found in string then it returns -1.

Signature

public int indexOf(String str)

Parameters

str is sub string value to find in specified string.

Return

Returns the int value that represents the first occurrence of the sub string in string, if sub string not fount in string then it returns -1.

Example

Result

Java String Method lastIndexOf

This method take a string parameter as input and return the last index value of parameter string in specified string. If string not found then it returns -1.
The second overloaded method find the string from fromindex position.

Signature

public int lastIndexOf(String str)
public int lastIndexOf(String str, int fromIndex)

Parameters

str- to search in String
fromindex- to search str from specified index

Return

Return the last index value of parameter str in specified string. If str not found then it returns -1

Example

Result

Java String substring() method

This method takes a int argument to generate sub string of string. It returns sub string starting from beginIndex value to last of string.
The second overloaded method allows to specify the ending index value also.
beginIndex parameters is inclusive and endIndex is exclusive.

Signature

public String substring(int beginIndex)
public String substring(int beginIndex,int endIndex)

Parameters

beginIndex –generate substring from this index value(inclusive).
endIndex-generate substring up to endIndex-1 value(exclusive).

Return

A substring

Throw

IndexOutOfBoundsException: If beginIndex is negative or endIndex is greater then length of string or if beginIndex is greater then endIndex.

Example

Result

Java String concat() method

String concat() is used to concatenate two strings. The parameter str string is appended to specified string and new string object is returned by this method.
Example
“Hello ”.concat(“Friends”)
This will generate a new string object “Hello Friends”

Parameters

Str – is string parameter used to concatenate with specified string

Example

Here str is concatenated with ” ” then it is concatenated with str1 and result is assigned to str3 String object.

StringTokenizer in java- Constructor, method with example

1 What is StringTokenizer?

A StringTokenizer is a class in Java. It is used to divide strings in form of token based on some delimiters.

It is defined in java.util.stringtokenizer

2 StringTokenizer Constructors

Sr NoConstructor and Description
1StringTokenizer(String str) Construct a string tokenizer for given string
2StringTokenizer(String str, String delim) Construct a string tokenizer for given string and generate tokens based on delimiters
3StringTokenizer(String str, String delim, boolean returnDelims) Construct a string tokenizer for given string and generate tokens based on delimiters the returnDelims specify whether to include delim in token or not

Creating StringTokenizer object using first constructor

Creating StringTokenizer object using second constructor

3 StringTokenizer methods

A Java StringTokenizer countTokens() Method

This method is used to count the number of the tokens from current token position to the last token

Signature

public int countTokens()

Parameters

NA

Return

Return the number of tokens available from specific token position

Example

Initially token position was before the first word “Arise” so on calling st.countToken() returns 11.
on calling st.nextToken() position of token is incresed by one and it is on “Arise” from this position new token count is 10.

B Java StringTokenizer hasMoreElements() Method

This method checks for next token in StringTokenizer if the token exists then return true else return false. Work similar as
hasMoreToken()

Parameters

NA

Return

Return true if next token exists else return false

Example

Result

At starting object st is pointing before the first word(Java). on calling st.hasMoreElements it is checkin that the first word java is there so it is returning true.

C Java StringTokenizer hasMoreToken() Method

This method is used with StringTokenizer object to check whether there is more token or not
For example
StringTokenizer st=new StringTokenizer(“Hello Friends”);
There are two tokens Hello and Friends. At starting hasMoreToken() point before the Hello Token so calling this method will return true at first.
To get next token we use nextToken().
After getting token Friends, again calling hasMoreToken() it return false.

Signature

public boolean hasMoreToken()

Parameters

NA

Return

Return true if there is more token else return false

Example

Result

St object is pointing before the Hello so calling st.hasMoreTokens() will always return true.

D Java StringTokenizer nextElement() Method

This method returns next token from stringTokenizer object this method work same as nextToken() only the return type of this method is object instead of String

Signature

public Object nextElement()

Parameters

NA

Return

Return next token from StringTokenizer object

Throws

NoSuchElementException – If there is no token in StringTokenizer object then it throw this exception

Example

Lets see how to tokenize a string in java

Another Example

E Java StringTokenizer nextToken() Method

This method returns next token from stringTokenizer object

Signature

public String nextToken()

Parameters

NA

Return

Return next token from StringTokenizer object

Throws

NoSuchElementException – If there is no token in StringTokenizer object then it throw this exception

Example

Result

Primitive Data Types in Java

Primitive data types are primary and basic data types in java.

In Java there are 8 primitive data types.

List of primitive datatypes in java is as follows

  1. byte
  2. short
  3. int
  4. long
  5. float
  6. double
  7. char
  8. boolean

Details of all data types are below.

1 Java Integer Data Type

There are four integer data types (byte, short, int and long) in java that can hold integer values.

All four data types with default value size and minimum and maximum value range that can store  are shown below

TypeDefaultSizeMin Max Value
byte08 bits-27, 27 -1
short016 bits-215, 215 -1
int032 bits-231, 231 -1
long064 bits-263, 263 -1

A byte data type in Java

  1. Byte stores 8 bits signed integer value.
  2. byte stores data in range of -128 to 127.
  3. Default value of byte is 0.
  4. Byte data type can use where we have to save memory during data storage.

B short Data type in java

  1. short stores 16 bits signed integer value.
  2. short stores data in range of -32768 to 32767.
  3. Default value of short is 0.
  4. Short data type can use where we have to save memory during data storage.

C int Data type in java

  1. int stores 32 bits signed and unsigned integer value.
  2. int stores data in range of -2^31 to -2^31-1 for signed integer and 0 to 2^32-1 for unsigned integer.
  3. Default value of short is 0.
  4. Int data type can used to represent normal integer values.

D long Data type in java

  1. long stores 64 bits signed and unsigned long integer value.
  2. long stores data in range of -2^63 to -2^63-1 for signed integer and 0 to 2^64-1 for unsigned integer.
  3. Default value of short is 0.
  4. long data type can used to represent higher integer values.

Lets see a simple program to initialize and print integer data type in java.

Output

2 Float and Double Data Types

Floating point value (example  11.23, 333.3330 etc. ) can be stored in data type float and double.

Small floating value can be stored in float and large floating stored in double. 

java data types float and double contains real values.

TypeDefaultSize
float0.032 bits
double0.064 bits

A float data type in java

  1. float stores decimal values in 32 bits, represents data in single-precision IEEE754 floating point.
  2. floats stores fractional values in range of 3.4e-038 to 3.4e+038.
  3. Default value of float is 0.0.
  4. float data type can used to represent fractional values.

B double data type in java

  1. double stores decimal values in 64 bits, represents data in double-precision IEEE754 floating point.
  2. double stores fractional values in range of 1.7e-308 to 1.7e+308.
  3. Default value of double is 0.0.
  4. double data type can used to represent fractional values with more precision.

Write a program to demonstrate use of float data types.

Output

3 Java Character Data Type

Character data ( example ‘a’ , ‘b’ , ‘f’, ….. etc. ) is stored in “char” data type.

TypeDefaultSize
char\u000016 bits

B char data type in java

  1. char stores single 16 bit unicode character
  2. double stores fractional values in range of 1.7e-308 to 1.7e+308.
  3. Default value of double is 0.0.
  4. double data type can used to represent fractional values with more precision.

Write a program to demonstrate char data types.

Result

Program to print character using ASCII value

Result

4 Java Boolean Data Type

boolean data type in java store the true and false value.

By default value of boolean data type is false.

TypeDefaultSize
booleanfalse1 bit

Write a program to demonstrate boolean data types.

Result

Prime number program in java using while loop

1 What is a Prime Number

A prime number is whole number that has only two factor 1 and number itself.

For example 23 is a prime number, because it has only two factor 1 and 23.

Learn More about

  1. While Loop
  2. If Else Statements

2 Java program to check prime number

Java program to find prime number can be divided in following steps.

  1. Take a number
  2. start a loop from 2 to number/2 times
  3. check whether a number is divisible in between
  4. if divisible then increase count variable by one and break loop
  5. after loop check if count variable in zero then number is prime otherwise not a prime number.

Prime no in java can be checked very easily with above steps.

Output

3 Program to check prime number in java using java method

We have created a java static method to check prime number in java

This is another way to check Prime no program in java.

Here a method is created and specified the work to check prime no in this static method.

Output

4 Program to check prime numbers in Java with in range

To find prime numbers in java program we can use following source code.

Prime numbers program in java Takes two integer numbers for range and generate prime numbers between range.

java program for prime number check each number and print if it is prime.

Output

print prime numbers in java in specified range also checks that number2 must be greater than number1.

4 Java Method check prime numbers in range

Prime number java program in range takes two integer range and check each number is prime or not if it is prime then prime number method returns list of prime numbers to calling method.

java program for prime numbers code is same as above code we have only created function by using that code.

Output

In above programs we have seen different java program to print prime numbers.

Hope you learned easy way to how to check prime number in java.

for, while, do while and for each loops in Java

In a programming language we have to repeat set of instruction many time as per programmer’s requirements.

To repeat instructions java provides looping statements. Looping is also known as Iterative statement
Following are types of loop in java.
1. For loop statement
2. While loop statement
3. Do while loop statement
4. For each loop (enhanced for loop)

Work of above statement are same but the have syntax difference. Let us see all of them one by one

1 For Loop in Java

for loop syntax in java

Example: Print 1 to 10 numbers using for loop in java

In for statement first loop variable is initialized then condition is checked if condition is true body of loop is executed after that variable is updated.   

Again condition is cheeked condition satisfied body of loop is executed and variable updated this process is continue until condition is false.

Variable initialization is done only once.

Output

2 While Loop in Java

while loop syntax in java

In while statement only condition is checked if condition is true then the body of loop is executed loop variable initialization should be before the while statement.

Variable updating is part of body of loop.

Example: Print 1 to 10 numbers using for loop in java

Output

3 do while in Java

do while loop syntax in java

In do loop condition is cheeked at last. First time body of loop is excuted without checking the condition after that if condition specified in while is true then body of loop is executed until condition is false.


Example: Print 1 to 10 numbers using for loop in java

Result

If condition is false then also do while statement is executed once.
Example: Executing do while loop once in false condition.

Result

Here condition in do while is false then also body of loop is executed once.

4 for each loop in java

For each loop is more readable and easier then for loop.

It is used to iterate over array and collection.

Syntax of for each loop in java

Difference between for and for each loop is that in for loop we can access index value but not in for each.

Example: Print all array elements using for each loop

Output

Example: Iterating a student object using for each loop.

Created a class student it contains a method getStudents() to get student list.

Class forEach1 call getStudents() and store its data in studentList.

then for each loop is used to iterate the student object.

Output

5 Examples on Loops

Example: Multiplication table program in java using while loop in Java

Output

Example: Sum of n natural numbers in java using for loop in java

Output

Example Java program to check whether a given number is prime or not

Output

Read more about prime numbers

Program: Program to find sum of digits in java

Applet Life Cycle in Java with Example

Applet in Java

Applet in Java is a special Java program that are primarily used in a internet programming.

Applet Life Cycle is very important to know in Java Applet Programming. 

As we have already seen how to run program from command prompt, but there were no GUI.

To provide Graphical user interface(GUI) Java Applet is used.

Applet program runs on a web browser at client side. Applet program are used to make the web site more dynamic.

1 Applet Life Cycle Stages

When the applet program is loaded is passes through several stages:

Java Applet Life Cycle
Java Applet Life Cycle

A Applet Born State

Also known as initialization state.  

It is the first state of applet lifecycle.

Applet enters in a born/ initialization state when it is first loaded.  

Applet moves in a born state when init() method of Applet class executes.

Applet initialization occurs once in a  applet lifecycle.

Inside the init() method we initialize all the variables.

Syntax of init() method in Java Applet

B Applet Running State

  Applet enters in a running state from born state when a start() method of Applet class executes.  

Running sates call automatically when the initialization phase completes. 

Applet also comes in a running state from idle state when idle applet again get processor.

Running sates call automatically when the initialization phase completes. 

Applet also comes in a running state from idle state when idle applet again get processor.

Syntax of start()              

C Applet Idle State

A running appletenters in a idle sate from running state when execution of start complete.

In a another words when we leave the page of running applet then automatically it enters in a idle sate from running state.

Applet moves in idle state when  stop() method executes and it moves idle to running state when again start() calls.

Syntax of stop()               

D Applet Dead State

  An applet is moved to dead state when we quit the web browser.  When applet moves in a dead state it removed from memory. 

The Applet will be terminate when destroy () method calls. In a applet lifecycle, applet terminates/destroys ones.

Syntax of destroy()        

E Applet Display State

The Display state executes immediately after when applet enters in a running state.

In this state we display the information on the output screen using paint() method.

2 Applet Life Cycle in Java Method Example

Lets see one program to demonstrate the life cycle of applet.

Compile and Run

>javac AppletLifeCycle.java
>appletviewer AppletLifeCycle.java

Applet Life Cycle in Java Example
Fig: Java Applet Life Cycle Example

Output At Console

On running Applet It will print first 3 line from output.

On closing applet it will call stop and destroy method.

init() method can be used to initialize various values and objects that are going to use in program.

Similarly to release resource we can use destroy().

Example: Write a program to read file and show in java applet.

Output

Fig: Reading File in showing in applet

Simple Calculator in Java Applet

How to remove special characters from a string in java

Here we will see how you can remove special characters from given string.

In Java String is a class which provides different constructors and methods to manipulate strings.

To remove special characters we will use String class method replaceAll().

String replaceAll(String regex, String replacement)

This method takes two argument.

First is String regular expression (regex) that matched the substring which user want to replace.

Second is String replacement, the string which will replace with regular expression substring.

1. Removing specific special characters

Output

In above program we know that special characters [email protected],^ are available in String.

2. Removing all special characters

Some times we don’t know which special character is there.

To remove all special characters from string we use

string.replaceAll("[^a-zA-Z]+"," ");

It will remove all special characters except small a-z and A-Z.

Output

It remove characters other then small and capital alphabets.

Here you can see there is a digit in a String that is also removed.

3. Removing special characters except digits

It you want not to remove digits then you have to modify your Regular expression.

Output

To achieve above two results we can also use this

replaceAll("[^a-zA-Z0]+"," "); is same as replaceAll("[^\\p{Alpha}]+","");

replaceAll("[^a-zA-Z0-9]+"," "); is same as replaceAll("[^\\p{Alpha}\\p{Digit}]+","");

Output

4. Allow few special characters in string

Some times we want to keep some special characters with string like comma(,) or fullstop (.).

Other then this we want to remove.

For that we have to add these two in our regular expression as below

replaceAll("[^a-zA-Z0-9,.]+"," ");

Output

If else nested and ladder if else statement in Java

If else is used to select a set of statements based on condition.

If condition is true then statement associated with if is executed, otherwise else part is executed.

If can also be used without else.

If ,if else, switch are conditions statements that java supports.

If else has variations it can use as follows

  1. If Statement
  2. If Else Statement
  3. Nested If Else
  4. Ladder Else If

1 If Else Statement


syntax of if else

Condition specified in if statement is true then the statement associated with if statement are executed otherwise statements of else block is executed.
Example: Find the greater among two number.

we use if else as follows

Output

2 If Statement

It is not mandatory to use else with if statement

Syntax of If statement

Example: To print value if is less than 10

Output

This program will not do any thing if number is greater then 10

3 Nested if else in Java

if else statement can be used with in another if else statement.

If or if else inside another if else is known as nesting of if else.

Syntax

Example: Find the greatest among the three numbers.

This is a example of Nested if else.

4 Else if ladder

Syntax

It is the combination of if else if statement Here execution of statement depends upon if statement’s condition.

If the condition is true for if or else if block only its associated statement is executed rest of the condition is not checked.

It any condition does not match then else block is executed.

Example: show grade of student based on percentage.

This is a good example of If Else Ladder.

5 If Else in short way (Ternary Operator)

We can write if else in short form using ternary operator

Syntax of Ternary operator is as below

variable=(condition)?expression1:expression2

If condition is true then expression1 is executed else expression2 will be executed.

and the result will be stored in variable.

Lets see one example of ternary operator

Example: Find the Greatest among two numbers using ternary operator.

Output

Java If Else Programs

Example: String comparison in If Else

Comparing two string to find is it working day or holiday

Example: Comparing dates in if statements

Output

You can un comment other two value and run to got other if statement executed

Example: Checking Boolean value in if statement

Output

Here we are calling a method in if statement.

This method returns true or false.

based on boolean value it is showing if or else statement.