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

String Palindrome Example in Java

It is a string palindrome example in java programming. Here need to modify(reverse) the string. String class objects are immutable. StringBuffer class objects are mutable, so I used StringBuffer class object to reverse the string. Reverse method is available in StringBuffer class.

Program Code

//String palindrome example in java
import java.util.*;
class stringPalindromeExample
{
	public static void main(String args[])
	{
                //Read string from console
		Scanner scn=new Scanner(System.in);
		System.out.print("Enter first string: ");
		String str1=scn.next();
		//copy first string to second string
		String str2=str1;
		StringBuffer sb=new StringBuffer(str1);
		//reverse first string
		sb.reverse();
		System.out.println("Reverse string is: "+sb);
		str1=sb.toString();
		if(str1.equalsIgnoreCase(str2))
		{
			System.out.println(str2+" is palindrome");
		}
		else
		{
			System.out.println(str2+" is not palindrome");
		}
	}
}

Output

string palindrome java

Command Line Argument Example in Java

For command line argument we pass argument to the main method. String args[] is a one dimensional String array. It stored arguments received at run time from the user. It stored values as a String type. If you pass any numbers then it also stores as a String only. If you want to do any manipulation on any number argument. You have to convert String into particular data type first then you can do any manipulation. Size of one dimensional String array(args[]) depends on number of arguments.

Command Line Argument Example in Java

Program Code

class cmdLineArgument
{
	public static void main(String args[])
	{
		//Find count of arguments
		int count=args.length;

		System.out.println("Count of argument:  "+count);
		System.out.println("All the arguments are: ");
		for(int i=0;i<count;i++)
		{
			System.out.println(args[i]);
		}
	}

}

Output
command line argument example

In this example we received 4 arguments from the user and display them. Suppose if we want to do addition on last two arguments then first convert it into int type.
In this example args[0]=”hello”; args[1]=”world”; args[2]=”10″; args[3]=”20″;
For conversion String to int we use: Integer.parseInt();
convert args[2] String into integer:- Integer.parseInt(args[2]);

How to store file into database using Java?

Here I discussed on “How to store file into database using Java?“. As we know that we can store image into database. Similarly we can store file or large volume data into database. To store large volume of data or text files into table, we can use CLOB data type. CLOB(Character Large Object) used to store an entire file, large text data etc. into column of table.

Store File in Database

Suppose I create a table with table name InsertFile into Oracle database.
create table InsertFile(FileData clob, FileNo int);
I used 2 columns. Column 1 for file storage and column 2 for file number.

Insert row into InsertFile table.
insert into InsertFile(FileNo) values(5);
It insert value 5 to FileNo column.

Follow steps to store file into table

1. First need to load text file into File object
File TxtFile=new File(“sample.txt”);

2. Attach file object to FileReader to read data from file.
FileReader fr=new FileReader(TxtFile);

3. Read data from FileReader and send it to First column of the table using setCharacterStream() method.
pstmt.setCharacterStream(1,fr,(int)TxtFile.length());

It has 3 parameters
1 – It represents that data set to First column.
fr – Data read from fr.
(int)TxtFile.length() – length of the file.

4. Execute the statement using executeUpdate().
pstmt.executeUpdate();

Java example to store file into oracle database

// Java Example to store file into Oracle database
import java.sql.*;
import java.io.*;
public class FileInsertExample
{
    public static void main(String[] args)
    {
        try
        {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
            //Use PreparedStatement to update table. Here table is InsertFile.
            PreparedStatement pstmt=con.prepareStatement("update InsertFile set FileData=? where FileNo=5");
            //Load file into file object
            File TxtFile=new File("sample.txt");
            //Connect the file to FileReader for reading
            FileReader fr=new FileReader(TxtFile);
            //Write the file contents into the table
            pstmt.setCharacterStream(1,fr,(int)TxtFile.length());
            //Execute the statement
            int i=pstmt.executeUpdate();
            
            System.out.println("No. of records updated = "+i);
            con.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Output

Java file Name: FileInsertExample.java
D:\jdk1.7.0_02\bin> javac FileInsertExample.java
D:\jdk1.7.0_02\bin> java FileInsertExample
No. of records updated = 1

How to store images into database?

Hello friends, here I try to explain how to store images into database. I discussed steps to insert images into database. It explains with a sample example. In example, I store an image into Oracle database using Java programming.

If we want to store images into database then we use BLOB data type to store images. BLOB(Binary Large Object) is a SQL data type that represents binary data to be stored into a database. BLOBs used to store images, audio files or multimedia files.

Steps to store an image into database table

1. Create table with Blob data type. Here I used ImageData column to store Image.

create table ImageTable(ImageData blob, ImageNo int);

2. First load image into File object.

File ImageFile= new File(“sampleImage.jpg”);

3. Attach the file object to FileInputStream for reading the image.

FileInputStream fis= new FileInputStream(ImageFile);

4. Read the image using FileInputStream and store it into the table using setBinaryStream() method of Statement interface.
pstmt.setBinaryStream(1,fis,(int)ImageFile.length());
It has 3 parameters.
1 represents First column of ImageTable where the image should be stored.
fis is a object of FileInputStream that read image.
ImageFile.length() gives ImageFile size in bytes.

pstmt is a object for PreparedStatement we use.

5. Execute the statement using executeUpdate().

pstmt.executeUpdate();

Thus we store image into database.

Java Example to store an image into database

// Java Example to store image into Oracle database
import java.sql.*;
import java.io.*;
public class ImageInsert 
{
	public static void main(String[] args) 
	{
		try
		{
			Class.forName("oracle.jdbc.driver.OracleDriver");
			Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
			//Use PreparedStatement to update table. Here table is ImageTable.
			PreparedStatement pstmt=con.prepareStatement("update ImageTable set ImageData=? where ImageNo=5");
			//Load image into file object
			File ImageFile= new File("sampleImage.jpg");
			//Attach the file object to FileInputStream for reading the image.
			FileInputStream fis= new FileInputStream(ImageFile);
			//Write the file contents into the table
			pstmt.setBinaryStream(1,fis,(int)ImageFile.length());
			//Execute the statement
			int i=pstmt.executeUpdate();
			
			System.out.println("No. of records updated = "+i);
			con.close();
		}
		catch (Exception e) 
		{
			e.printStackTrace();
		}
	}
}

Output

Java File Name: ImageInsert.java
D:\jdk1.7.0_02\bin> javac ImageInsert.java
D:\jdk1.7.0_02\bin> java ImageInsert
No. of records updated = 1

JVM – Is it Program or Machine?

Java Virtual Machine(JVM) is not a machine. It is a program. It is a free program which is available on internet. JVM gives run time environment to execute Java program. When we compile java file then we get java bytecode(class file). It is not understandable by machine. So bytecode can not directly execute on machine. So need of JVM. JVM understands the bytecode and convert bytecode to machine level code. So JVM is used to execute the bytecode.
Java virtual machine is a program which used in execution. It interacts with operating system. So it is a platform specific. On internet different version of JVM available for different operating system and processors. If we write java code in Windows platform and we want to execute that java code on Linux platform then we need Linux compatible JVM.

java virtual machine

How JVM handles bytecodes?

JVM is the important part of entire java program execution. It is used to convert each bytecode instruction into machine level code. Later that machine code executed by microprocessor.
When Java bytecode(class) comes to JVM. First class loader subsystem helps to allocate necessary memory to the java program. It verifies that bytecodes are poper or not. If bytecode contains suspicious code then JVM rejected it. JVM plays important role in security. Proper bytecodes allocates necessary memory for execution the program. JVM execution engine contains interpreter and JIT(Just In Time) compiler.Interpreter and JIT compiler both work to convert bytecodes into machine code. JIT compiler is a part of JVM which increase the speed of execution of java bytecodes.

Conclusion

JVM is a program which used to execute java class files. JVM is a platform dependent. For different operating systems different JVM program available on internet. It is free available on internet. It converts bytecodes instruction into the machine language instruction.