Showing posts with label corejava. Show all posts
Showing posts with label corejava. Show all posts

Saturday 24 August 2013

DataTypes in JAVA

// siddhu vydyabhushana // 2 comments
What is Data Type?
Data types are common in any language (c, java,etc.,).It tells that the type of data in the variable or what type of value  is going to be stored .
For example: 

int number; // it will store only numericals
String word; //Store charchters
there are two types of data types in java 1.Primitive 2.Non-Primitive
Primitive sub divided into two types 1.Numeric 2.Non-Numeric Non-Primitive sub divided into two types 1.Array 2.Interface 3.Class

See Below Image:
datatypes in java

Numeric is subdivided into two types Integer, floating Point . Non Numeric is subdivided into two types Character ,Boolean.
Again Integer  subdivided into 4 types 1.byte 2.Int 3.Long 4.Short.

Primitive Data Types: it is also called a standard data type , intrinsic  or built-in data type.the java compiler contains detailed instructions on each legal operations supported by the data type.
there are 8 primitive data types, these classified into four groups.
NOTE: to find the range of numerical data types use the following formula


-2^(n-1) to +2^(n-1) - 1
Non-Primitive Data type:
it is also called derived type , Abstract data type (or) reference type .The derived data type built on the primitive data type.
Example: Class, Interface. the another good example is string datatype .
Java does not have any  unsigned types.the sizes of all numeic types are platform independent.
Read More

Wednesday 21 August 2013

How to modify XML FILE IN JAVA

// siddhu vydyabhushana // 6 comments
In this example, we demonstrate the use of DOM parser to modify an existing XML file :
  1. Add a new element
  2. Update existing element attribute
  3. Update existing element value
  4. Delete existing element

1. XML file

See before and after XML file.
File : file.xml – Original XML file.
<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<company>
   <staff id="1">
	<firstname>yong</firstname>
	<lastname>mook kim</lastname>
	<nickname>mkyong</nickname>
	<salary>100000</salary>
   </staff>
</company>
Later, update above XML file via DOM XML Parser.
  1. Update the staff attribute id = 2
  2. Update salary value to 200000
  3. Append a new “age” element under staff
  4. Delete “firstname” element under staff
File : file.xml – Newly modified XML file.
<?xml version="1.0" encoding="UTF-8" standalone="no" ?> 
<company>
   <staff id="2">
	<lastname>mook kim</lastname>
	<nickname>mkyong</nickname>
	<salary>2000000</salary> 
        <age>28</age> 
   </staff>
</company>

2. DOM Parser

DOM XML parser to update an above XML file.
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
 
public class ModifyXMLFile {
 
	public static void main(String argv[]) {
 
	   try {
		String filepath = "c:\\file.xml";
		DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
		Document doc = docBuilder.parse(filepath);
 
		// Get the root element
		Node company = doc.getFirstChild();
 
		// Get the staff element , it may not working if tag has spaces, or
		// whatever weird characters in front...it's better to use
		// getElementsByTagName() to get it directly.
		// Node staff = company.getFirstChild();
 
		// Get the staff element by tag name directly
		Node staff = doc.getElementsByTagName("staff").item(0);
 
		// update staff attribute
		NamedNodeMap attr = staff.getAttributes();
		Node nodeAttr = attr.getNamedItem("id");
		nodeAttr.setTextContent("2");
 
		// append a new node to staff
		Element age = doc.createElement("age");
		age.appendChild(doc.createTextNode("28"));
		staff.appendChild(age);
 
		// loop the staff child node
		NodeList list = staff.getChildNodes();
 
		for (int i = 0; i < list.getLength(); i++) {
 
                   Node node = list.item(i);
 
		   // get the salary element, and update the value
		   if ("salary".equals(node.getNodeName())) {
			node.setTextContent("2000000");
		   }
 
                   //remove firstname
		   if ("firstname".equals(node.getNodeName())) {
			staff.removeChild(node);
		   }
 
		}
 
		// write the content into xml file
		TransformerFactory transformerFactory = TransformerFactory.newInstance();
		Transformer transformer = transformerFactory.newTransformer();
		DOMSource source = new DOMSource(doc);
		StreamResult result = new StreamResult(new File(filepath));
		transformer.transform(source, result);
 
		System.out.println("Done");
 
	   } catch (ParserConfigurationException pce) {
		pce.printStackTrace();
	   } catch (TransformerException tfe) {
		tfe.printStackTrace();
	   } catch (IOException ioe) {
		ioe.printStackTrace();
	   } catch (SAXException sae) {
		sae.printStackTrace();
	   }
	}
}
Read More

Read XML file in java

// siddhu vydyabhushana // 1 comment
In this tutorial, we will show you how to read an XML file via DOM XML parser. DOM parser parses the entire XML document and loads it into memory; then models it in a “TREE” structure for easy traversal or manipulation.
In short, it turns a XML file into DOM or Tree structure, and you have to traverse a node by node to get what you want.
What is Node?
In the DOM, everything in an XML document is a node, read this.
Warning
DOM Parser is slow and consumes a lot of memory when it loads an XML document which contains a lot of data. Please consider SAX parser as solution for it, SAX is faster than DOM and use less memory.

1. DOM XML Parser Example

This example shows you how to get the node by “name”, and display the value.
/Users/mkyong/staff.xml
<?xml version="1.0"?>
<company>
	<staff id="1001">
		<firstname>yong</firstname>
		<lastname>mook kim</lastname>
		<nickname>mkyong</nickname>
		<salary>100000</salary>
	</staff>
	<staff id="2001">
		<firstname>low</firstname>
		<lastname>yin fong</lastname>
		<nickname>fong fong</nickname>
		<salary>200000</salary>
	</staff>
</company>
ReadXMLFile.java
package com.mkyong.seo;
 
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
 
public class ReadXMLFile {
 
  public static void main(String argv[]) {
 
    try {
 
	File fXmlFile = new File("/Users/mkyong/staff.xml");
	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
	Document doc = dBuilder.parse(fXmlFile);
 
	//optional, but recommended
	//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
	doc.getDocumentElement().normalize();
 
	System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
 
	NodeList nList = doc.getElementsByTagName("staff");
 
	System.out.println("----------------------------");
 
	for (int temp = 0; temp < nList.getLength(); temp++) {
 
		Node nNode = nList.item(temp);
 
		System.out.println("\nCurrent Element :" + nNode.getNodeName());
 
		if (nNode.getNodeType() == Node.ELEMENT_NODE) {
 
			Element eElement = (Element) nNode;
 
			System.out.println("Staff id : " + eElement.getAttribute("id"));
			System.out.println("First Name : " + eElement.getElementsByTagName("firstname").item(0).getTextContent());
			System.out.println("Last Name : " + eElement.getElementsByTagName("lastname").item(0).getTextContent());
			System.out.println("Nick Name : " + eElement.getElementsByTagName("nickname").item(0).getTextContent());
			System.out.println("Salary : " + eElement.getElementsByTagName("salary").item(0).getTextContent());
 
		}
	}
    } catch (Exception e) {
	e.printStackTrace();
    }
  }
 
}
Result
Root element :company
----------------------------
 
Current Element :staff
Staff id : 1001
First Name : yong
Last Name : mook kim
Nick Name : mkyong
Salary : 100000
 
Current Element :staff
Staff id : 2001
First Name : low
Last Name : yin fong
Nick Name : fong fong
Salary : 200000

2. Looping the Node

This example reads the same “staff.xml“, and showing you how to loop the node one by one, and print out the node name and value, and also the attribute if any.
ReadXMLFile2.java
package com.mkyong.seo;
 
import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
 
public class ReadXMLFile2 {
 
  public static void main(String[] args) {
 
    try {
 
	File file = new File("/Users/mkyong/staff.xml");
 
	DocumentBuilder dBuilder = DocumentBuilderFactory.newInstance()
                             .newDocumentBuilder();
 
	Document doc = dBuilder.parse(file);
 
	System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
 
	if (doc.hasChildNodes()) {
 
		printNote(doc.getChildNodes());
 
	}
 
    } catch (Exception e) {
	System.out.println(e.getMessage());
    }
 
  }
 
  private static void printNote(NodeList nodeList) {
 
    for (int count = 0; count < nodeList.getLength(); count++) {
 
	Node tempNode = nodeList.item(count);
 
	// make sure it's element node.
	if (tempNode.getNodeType() == Node.ELEMENT_NODE) {
 
		// get node name and value
		System.out.println("\nNode Name =" + tempNode.getNodeName() + " [OPEN]");
		System.out.println("Node Value =" + tempNode.getTextContent());
 
		if (tempNode.hasAttributes()) {
 
			// get attributes names and values
			NamedNodeMap nodeMap = tempNode.getAttributes();
 
			for (int i = 0; i < nodeMap.getLength(); i++) {
 
				Node node = nodeMap.item(i);
				System.out.println("attr name : " + node.getNodeName());
				System.out.println("attr value : " + node.getNodeValue());
 
			}
 
		}
 
		if (tempNode.hasChildNodes()) {
 
			// loop again if has child nodes
			printNote(tempNode.getChildNodes());
 
		}
 
		System.out.println("Node Name =" + tempNode.getNodeName() + " [CLOSE]");
 
	}
 
    }
 
  }
 
}
Result :
Root element :company
 
Node Name =company [OPEN]
Node Value =
 
		yong
		mook kim
		mkyong
		100000
 
 
		low
		yin fong
		fong fong
		200000
 
 
 
Node Name =staff [OPEN]
Node Value =
		yong
		mook kim
		mkyong
		100000
 
attr name : id
attr value : 1001
 
Node Name =firstname [OPEN]
Node Value =yong
Node Name =firstname [CLOSE]
 
Node Name =lastname [OPEN]
Node Value =mook kim
Node Name =lastname [CLOSE]
 
Node Name =nickname [OPEN]
Node Value =mkyong
Node Name =nickname [CLOSE]
 
Node Name =salary [OPEN]
Node Value =100000
Node Name =salary [CLOSE]
Node Name =staff [CLOSE]
 
Node Name =staff [OPEN]
Node Value =
		low
		yin fong
		fong fong
		200000
 
attr name : id
attr value : 2001
 
Node Name =firstname [OPEN]
Node Value =low
Node Name =firstname [CLOSE]
 
Node Name =lastname [OPEN]
Node Value =yin fong
Node Name =lastname [CLOSE]
 
Node Name =nickname [OPEN]
Node Value =fong fong
Node Name =nickname [CLOSE]
 
Node Name =salary [OPEN]
Node Value =200000
Node Name =salary [CLOSE]
Node Name =staff [CLOSE]
Node Name =company [CLOSE]
Note
You may interest at this How to get Alexa Ranking In Java. It shows you how to use DOM to parse the Alexa XML result.
 
Read More

Tuesday 20 August 2013

Validate regular expression for username in java

// siddhu vydyabhushana // Leave a Comment
Username Regular Expression Pattern
^[a-z0-9_-]{3,15}$
Description
^                    # Start of the line
  [a-z0-9_-]	     # Match characters and symbols in the list, a-z, 0-9, underscore, hyphen
             {3,15}  # Length at least 3 characters and maximum length of 15 
$                    # End of the line
Whole combination is means, 3 to 15 characters with any lower case character, digit or special symbol “_-” only. This is common username pattern that’s widely use in different websites.

1. Java Regular Expression Example

UsernameValidator.java
package com.mkyong.regex;
 
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class UsernameValidator{
 
	  private Pattern pattern;
	  private Matcher matcher;
 
	  private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";
 
	  public UsernameValidator(){
		  pattern = Pattern.compile(USERNAME_PATTERN);
	  }
 
	  /**
	   * Validate username with regular expression
	   * @param username username for validation
	   * @return true valid username, false invalid username
	   */
	  public boolean validate(final String username){
 
		  matcher = pattern.matcher(username);
		  return matcher.matches();
 
	  }
}

2. Username that match:

1. mkyong34
2. mkyong_2002
3. mkyong-2002
4. mk3-4_yong

3. Username that doesn’t match:

1. mk (too short, min 3 characters)
2. mk@yong (“@” character is not allow)
3. mkyong123456789_- (too long, max characters of 15)

4. Unit Test – UsernameValidator

Using testNG to perform unit test.
UsernameValidatorTest.java
package com.mkyong.regex;
 
import org.testng.Assert;
import org.testng.annotations.*;
 
/**
 * Username validator Testing
 * @author mkyong
 *
 */
public class UsernameValidatorTest {
 
	private UsernameValidator usernameValidator;
 
	@BeforeClass
        public void initData(){
		usernameValidator = new UsernameValidator();
        }
 
	@DataProvider
	public Object[][] ValidUsernameProvider() {
		return new Object[][]{
		   {new String[] {
	             "mkyong34", "mkyong_2002","mkyong-2002" ,"mk3-4_yong"
		   }}
      	        };
	}
 
	@DataProvider
	public Object[][] InvalidUsernameProvider() {
		return new Object[][]{
		   {new String[] {
		     "mk","mk@yong","mkyong123456789_-"	  
		   }}
	        };
	}
 
	@Test(dataProvider = "ValidUsernameProvider")
	public void ValidUsernameTest(String[] Username) {
 
	   for(String temp : Username){
		boolean valid = usernameValidator.validate(temp);
		System.out.println("Username is valid : " + temp + " , " + valid);
		Assert.assertEquals(true, valid);
	   }
 
	}
 
	@Test(dataProvider = "InvalidUsernameProvider", 
                 dependsOnMethods="ValidUsernameTest")
	public void InValidUsernameTest(String[] Username) {
 
	   for(String temp : Username){
		boolean valid = usernameValidator.validate(temp);
		System.out.println("username is valid : " + temp + " , " + valid);
		Assert.assertEquals(false, valid);
	   }
 
	}	
}

5. Unit Test – Result

Username is valid : mkyong34 , true
Username is valid : mkyong_2002 , true
Username is valid : mkyong-2002 , true
Username is valid : mk3-4_yong , true
username is valid : mk , false
username is valid : mk@yong , false
username is valid : mkyong123456789_- , false
PASSED: ValidUsernameTest([Ljava.lang.String;@1d4c61c)
PASSED: InValidUsernameTest([Ljava.lang.String;@116471f)
 
===============================================
    com.mkyong.regex.UsernameValidatorTest
    Tests run: 2, Failures: 0, Skips: 0
===============================================
 
 
===============================================
mkyong
Total tests run: 2, Failures: 0, Skips: 0
===============================================
 
Read More

Wednesday 31 July 2013

Final modifier in java

// siddhu vydyabhushana // Leave a Comment
Another useful modifiers in regard to controlling class member usage is the final modifier. The final modifier specifies that a variable as a constant value or that a method cannot be overridden in a subclass. The final modifier makes class member is the final version allowed for the class.For creating symbolic constant you can use final modifier.

final public int CENT=100;//constant
the above is similar to const variable in c++,they must always be initialized upon declaration and their value can't change any time afterward.
final boolean FLAG=true;

Three usage of final are:

1. A final class cannot be inherited.
2. A final method cannot be changed by subclass (or) overriding.
3. A final data member cannot be changed after initialization(constant).


Final Class:
final class X{ }
class Y extends X
{
  void print()
  {
  System.out.println("inside block y");
  }
public static void main(String args[])
{
Y a=new Y();
a.print();
}
}
Output:



Example-2:

Final Variable:
class X
{ 
final int i=10;// constant variable

  void print()
  {
   i=20;
  }
public static void main(String args[])
{
X a=new X();
a.print();
}
}

Output:


Read More

Tuesday 30 July 2013

smart uses of STATIC in JAVA

// siddhu vydyabhushana // 3 comments
STATIC IN JAVA
  • Every class has two parts.One is variable and other one is method.The variables are called instance variables and methods are called instance methods.This is because every time the class is instantiated ,a new copy of each them is created .They are accessed with dot operator.
  • The modifier static is used to specify that a method is a class method.A class method is a method that is invoked without being bound to any specific object of the class.These are associated with itself not an individual objects.
For Example:

       public static void main(String args[])

which means,this method  as one that belong to the entire class and not a part of any object of the class.so interpreter uses this method before any object is created. 

Three uses of static 

1.if you declare static in before variable that variables gets memory once from the heap.
E.g


static example 1:
class inc
{
 int i=0;
void print()
{

   i++;
     System.out.println(i);
   
}

}
class staticvariable
{
 public static void main(String args[])
 {
inc a=new inc();
inc b=new inc();
inc c=new inc();
a.print();   
b.print();   
c.print();   
 }
  
}
Output:
After modifying using static

Using static variable:
class inc
{
static int i=0;
void print()
{

   i++;
     System.out.println(i);
   
}

}
class staticvariable
{
 public static void main(String args[])
 {
inc a=new inc();
inc b=new inc();
inc c=new inc();
a.print();   
b.print();   
c.print();   
 }
  
}
Output:

2. if you declare any class using static without creating instance automatically when class loads it will be executed.
for example if we take public static void main(String args[]).
before executing all classes in a particular class the main method will be executed first because of using static modifier.

3.Static block: it will executed before main method.
for Example:


Example of static block:
 
class staticBlock
{
static
{
System.out.println("Executing Before main method");
}
public static void main(String args[])
{
System.out.println("WELCOME TO JAVA TYRO");
}
}
Output:

Read More

Monday 29 July 2013

Converting applet into application in java

// siddhu vydyabhushana // 1 comment

Converting applet into application in java:

Suppose the user who do not have a browser,he cannot execute an applet. So we must convert the applet to application. In general applications have the main() method.You can use the Frame class to convert the applet to application.
Applet's default layout manager is FlowLayout .But ,Frames default Layout manager is BorderLayout.


program for applet convertion.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

 public class convert extends Applet
{
  public void paint(Graphics g)
  {
   setBackground(Color.pink);
   g.drawString("Applet to Application",10,10);
   g.drawString("ALT+F4 to close",10,40);
  }
  public static void main(String args[])
  {
    myframe m=new myframe();
 convert c=new convert();
 c.init();
 m.add("Center",c);
 m.show();
  }
}
   class myframe extends Frame
   {
     public myframe()
  {
   setTitle("Quit for close button");
   setSize(300,200);
   addWindowListener(
   new WindowAdapter()
   {
       public void windowClosing(WindowEvent e)
      {
           System.exit(0);
      }
   });
 
     }
     
   }
Output of a Program:-


 Your sweet comments, likes, shares makes us very happy...
Read More

Friday 26 July 2013

Native, Transient, Synchronized, Volatile Modifiers in java

// siddhu vydyabhushana // 3 comments
Native Modifier:  

This is used as a methods modifier. Its body is implemented in another programming language such as c (or) c++. Native methods are platform dependent. The Native modifier informs the java compiler that a methods implementation is in external c file. It is for this reason that native method declaration look different from other java methods .they have no body
                
                                   E.g.:  native int findTotal ();


Note:   That the method declaration ends with a semicolon. There are no curly braces containing java code .This is implemented in C or C++ code. It  makes potential security risk and loss of portability
Transient Modifier

The object has a transient part it is not part of the persistent state of an object. You can use the transient modifier if you do not want to store certain data member to file. This is used only with data members.

Class transistent
{
   Transistent Boolean b; //not to be stored
   Int k;                                 //to be stored
} 

Volatile Modifier

It may be modified by asynchronous threads. The volatile modifier is used for volatile that can be simultaneously modified by many threads.

Note:
      1.     You can change the order of the access specifier and modifiers
                                Public static void main(String args[])
                                Static public void main(String srgs[])

2.      You cannot use two or  more access specifiers in a declaration
Private public int a; //illegal

Synchronized Modifier


This is used in multi –threaded programming .A thread is a unit of execution within a process. In multi-threaded you need to synchronize various threads. The synchronized keyword used to tell the program that the thread is safe. This is allowing a single thread access to a method at once, forcing the others to wait their turn.

Read More

Introduction to Applets

// siddhu vydyabhushana // 2 comments
Introduction to Applets

v  An applet is a special program that you can embed in a web page such that the applet gains control over a certain part of the displayed page.

v  Applet differs from application programs. Like applications, applets are created from classes.

v  However, applets do not have a main method as an entry point, but instead have several methods to control specific aspects of applet execution

simple hello world applet
Compiling JAVA Applet


This applet consists of two import statements.

               1.      The first import the abstract windowing tool kit class. Because applet programs are GUI based not console based.
               2.      The second import statement here is Applet class. Every applet that you can create must be a sub class of Applet.
        3.    The paint method is called to display the output. It has one parameter of type Graphics.
                                
                                   Syntax: drawString(String s1, int x, int y);


Read More