if-else control statement example in Java

It is a control statement. It checks if condition is true then performs particular task else it performs another task. Task perform depends on condition is right or wrong.

if-else control statement example in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Check given number is positive or negative or zero
public class IfConditionExample 
{
	public static void main(String[] args) 
	{
		int number=10;
		if(number==0)
		{
			System.out.println(number+" is equal to zero");
		}
		else if(number>0)
		{
			System.out.println(number+" is positive number");
		}
		else
		{
			System.out.println(number+" is negative number");
		}
	}
}

Output
10 is positive number

do-while loop example in Java

It is an exit control loop. Condition is checked after first iteration. Means statements of block executed at least once, if condition is failed.

do-while loop example in Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class DoWhileLoopExample 
{
	public static void main(String[] args) 
	{
		int number=0; //initialization
		//do while loop
		do
		{
			System.out.println("number is: "+number);
			number++;		//increment
		}while(number>10);  //condition - it checked after block executed once
		//condition failed because number is not greater than 10
 
	}
}

Output
number is: 0

If you have option to select any one from while or do-while then while is more efficient than do-while loop because in do-while loop programmer does not have control from the right of beginning of execution. After the first loop programmer gets control. But in while loop condition is tested first so control from the right of beginning of execution.

For Loop Example in Java

For Loop Example in Java

1
2
3
4
5
6
7
8
9
10
11
12
public class ForLoopExample 
{
	public static void main(String[] args) 
	{
		//for loop
		//for(initialization;condition;increment/decrement)
		for(int number=10;number>0;number--)
		{
			System.out.println("number is: "+number);
		}
	}
}

Output
number is: 10
number is: 9
number is: 8
number is: 7
number is: 6
number is: 5
number is: 4
number is: 3
number is: 2
number is: 1

While Loop Example in Java

While Loop Example in Java

1
2
3
4
5
6
7
8
9
10
11
12
public class WhileLoopExample 
{
	public static void main(String[] args) 
	{
		int number=0; //number initialization
		while(number<10)  //condition
		{
			System.out.println("number is: "+number);
			number++;   //increment/decrement
		}
	}
}

Output
number is: 0
number is: 1
number is: 2
number is: 3
number is: 4
number is: 5
number is: 6
number is: 7
number is: 8
number is: 9

Java Primitive Data Types Example – Java Variables

There are 8 primitive data types in Java.
1. byte
2. short
3. int
4. long
5. float
6. double
7. boolean
8. char

Java sample example to demonstrate primitive data types

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class PrimitiveDataTypesExample 
{
 
	public static void main(String[] args) 
	{
		//declaring primitive data types: 8 types
		int intNumber=1000000000;
		short shortNumber=32767;
		long longNumber=1000000000;
		float floatNumber=100.03244f;
		double doubleNumber=100000.33432;
		char oneCharacter='A';
		boolean flag=true;
		byte byteNumber=127;
 
		//displaying primitive data types results
		System.out.println("integer number is: "+intNumber);
		System.out.println("short number is: "+shortNumber);
		System.out.println("long number is: "+longNumber);
		System.out.println("float number is: "+floatNumber);
		System.out.println("double number is: "+doubleNumber);
		System.out.println("charcter is: "+oneCharacter);
		System.out.println("boolean flag is: "+flag);
		System.out.println("byte is: "+byteNumber);
 
	}
 
}

Output
integer number is: 1000000000
short number is: 32767
long number is: 1000000000
float number is: 100.03244
double number is: 100000.33432
charcter is: A
boolean flag is: true
byte is: 127

Java Iterator

What is an Iterator?
Most of the collection provide traversal of collection with the help of Iterator interface (java.util.Iterator). This Interface helps you to guarantee the collection objects one by one.
Actually when you try to iterate a collection with the help of iterator, a snapshot of the collection will be created. So, Ideally you should not modify the collection object while you are traversing the collection with the help of iterator.
iterator in java sample

How to use an Iterator in Java?
To use an iterator for traversing the contents of a collection, you should follow below steps:

1) Get the Iterator object of that collection by calling Collection’s iterator() method.

2) Write a loop with the condition of interatorObj.hasNext( ), hasNext() will return true till you reach the last element.

3) Process the object using next( ) method inside the loop

Here is the example:

		List<String> list = new ArrayList<String>();
		
		list.add("AAA");
		list.add("BBB");
		list.add("CCC");
		
		Iterator<String> itrObj = list.iterator();
		while(itrObj.hasNext()){
			System.out.println(itrObj.next());
		}

Different Types of Comments in Java

What is the Comments?

Comments are description of program in a plain English language. These describe the program code and features of program.
Main purpose behind comments is to make our code understandable to others. These increase readability of program code. If other person wants to know function of particular code block then comments are helpful in understanding. Writing comments are necessary for good programming.

Different Types of Comments in Java

Three types of comments in Java.
Single Line Comment
This comment is start with double slash symbol (//).

Example

//It is a single line comment example.

Multi Line Comments
This comment is start with /* and end with */. The multi line comments write between the /* and */.

Example

/*
It is a multi line comment example.
This is sample comment type to describe the code.
It increases the code understandability.
In multi line comment example several lines are as comments.
*/

Java Documentation Comments
This comment is start with /** and end with */. It is document(doc) comment. It is used to provide description for every feature in a Java program. The JDK javadoc tool uses doc comments when preparing automatically generated documentation. Javadoc generates html documentation file which contains java documentation comments.

Example

/**
 * This class is a sample for demonstrate java documentation comments.
 * @author int2354
 * @version 1.2
 */

/**create a class*/
class A
{
	/**create a method*/
	void a1()
	{
	
	}
}

String Split Example in Java

String split method is used to break a string into pieces at places represented by the delimiter. Split method break string into pieces and returned into a String type array.

It is a java example to demonstrate split method of String class. This method used to break a string into pieces wherever delimiter found in the string.

Program Code

//String split example in java
class stringSplit
{
    public static void main(String args[])
    {
        String str1="Alok Sharma,24,MBA,Mumbai,9734543123";
        System.out.println("Original String is:"+str1);
	//Split the string where ',' found
        String str[]=str1.split(",");
	for(int i=0;i<str.length;i++)
	System.out.println(str[i]);
    }
}

Output

string split
In this example delimiter is comma(,). String splits wherever a comma(,) found in the string.

Remove all white spaces from a string in java

To remove all white spaces(blank space) from string we can use replaceAll() method of String class. This method removes spaces from beginning, ending and between the string. It removes all spaces from string. Remove blank space by replacing spaces with empty string “”. replaceAll method is used to replace any expression with another expression.

Program Code

//replaceAll method example in java
class removeAllSpaces
{
	public static void main(String args[])
	{
		String str1=" H e l l o W o r l d ";
		System.out.println("Original String:"+str1);
		System.out.println("string length: "+str1.length());
		//String after trim
		str1=str1.replaceAll(" ","");
		System.out.println("Trimmed string:"+str1);
		System.out.println("length of trimmed string:"+str1.length());
	}
}

Output

remove space java

How to remove white spaces from string in java?

In Java String is a powerful class with many important methods. One important method is trim(). This method is used to remove white spaces(blank space) from the beginning and ending of a string. Trim() method removes space from beginning and ending of a string but not between the string. As we know that String class is a immutable so trim() method returns another object which is different from previous object.

Program Code

//String trim method example in java
class stringTrim
{
	public static void main(String args[])
	{
		String str1="         Hello Everybody       ";
		System.out.println("Original String:"+str1);
		System.out.println("string length: "+str1.length());
		//String after trim
		System.out.println("Trimmed string:"+ str1.trim());
		System.out.println("string length: "+(str1.trim()).length());
	}
}

Output

string trim example