Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Sunday 29 September 2013

Java Interview Questions

// siddhu vydyabhushana // 1 comment
java interview questions
Q: What is the difference between an Interface and an Abstract class?
A: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract. An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.
.

Q: What is the purpose of garbage collection in Java, and when is it used?
A: The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

Q: Describe synchronization in respect to multithreading.
A: With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors. 


Q: Explain different way of using thread?
A: The thread could be implemented by using runnable interface or by inheriting from the Thread class. The former is more advantageous, 'cause when you are going for multiple inheritance..the only interface can help.

Q: What are pass by reference and passby value?
A: Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed. 


Q: What is HashMap and Map?
A: Map is Interface and Hashmap is class that implements that.


Q: Difference between HashMap and HashTable?
A: The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is unsynchronized and Hashtable is synchronized.


Q: Difference between Vector and ArrayList?
A: Vector is synchronized whereas arraylist is not.


Q: Difference between Swing and Awt?
A: AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT.


Q: What is the difference between a constructor and a method?
A: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.


Q: What is an Iterator?
A: Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.


Q: State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
A: public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected).It means that it is visible to all within a particular package
.


Q: What is an abstract class?
A: Abstract class must be extended/subclassed (to be useful). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such.
A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.


Q: What is static in java?
A: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

Q: What is final?
A: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).
Read More

Wednesday 25 September 2013

Create DataTable in JSF2.0

// siddhu vydyabhushana // 1 comment
In JSF, “h:dataTable” tag is used to display data in a HTML table format. The following JSF 2.0 example show you how to use “h:dataTable” tag to loop over an array of “order” object, and display it in a HTML table format.

1. Project Folder

Project folder structure of this example.
                                                      jsf2-dataTable-folders

                                                     
                                                           
2. Managed bean
A managed bean named “order”, initialized the array object for later use.
OrderBean.java
package com.mkyong;
 
import java.io.Serializable;
import java.math.BigDecimal;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
 
@ManagedBean(name="order")
@SessionScoped
public class OrderBean implements Serializable{
 
	private static final long serialVersionUID = 1L;
 
	private static final Order[] orderList = new Order[] {
 
		new Order("A0001", "Intel CPU", 
				new BigDecimal("700.00"), 1),
		new Order("A0002", "Harddisk 10TB", 
				new BigDecimal("500.00"), 2),
		new Order("A0003", "Dell Laptop", 
				new BigDecimal("11600.00"), 8),
		new Order("A0004", "Samsung LCD", 
				new BigDecimal("5200.00"), 3),
		new Order("A0005", "A4Tech Mouse", 
				new BigDecimal("100.00"), 10)
	};
 
	public Order[] getOrderList() {
 
		return orderList;
 
	}
 
	public static class Order{
 
		String orderNo;
		String productName;
		BigDecimal price;
		int qty;
 
		public Order(String orderNo, String productName, 
                                BigDecimal price, int qty) {
 
			this.orderNo = orderNo;
			this.productName = productName;
			this.price = price;
			this.qty = qty;
		}
 
		//getter and setter methods
	}
}

3. CSS

Create a CSS file to style the table layout.
table-style.css
.order-table{   
	border-collapse:collapse;
}
 
.order-table-header{
	text-align:center;
	background:none repeat scroll 0 0 #E5E5E5;
	border-bottom:1px solid #BBBBBB;
	padding:16px;
}
 
.order-table-odd-row{
	text-align:center;
	background:none repeat scroll 0 0 #FFFFFFF;
	border-top:1px solid #BBBBBB;
}
 
.order-table-even-row{
	text-align:center;
	background:none repeat scroll 0 0 #F9F9F9;
	border-top:1px solid #BBBBBB;
}

4. h:dataTable

A JSF 2.0 xhtml page to show the use of “h:dataTable” tag to loop over the array of “order” object. This example should be self-explanatory.
default.xhtml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"   
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      >
    <h:head>
    	<h:outputStylesheet library="css" name="table-style.css"  />
    </h:head>
    <h:body>
 
    	<h1>JSF 2 dataTable example</h1>
 
    		<h:dataTable value="#{order.orderList}" var="o"
    			styleClass="order-table"
    			headerClass="order-table-header"
    			rowClasses="order-table-odd-row,order-table-even-row"
    		>
 
    			<h:column>
    				<!-- column header -->
    				<f:facet name="header">Order No</f:facet>
    				<!-- row record -->
    				#{o.orderNo}
    			</h:column>
 
    			<h:column>
    				<f:facet name="header">Product Name</f:facet>
    				#{o.productName}
    			</h:column>
 
    			<h:column>
    				<f:facet name="header">Price</f:facet>
    				#{o.price}
    			</h:column>
 
    			<h:column>
    				<f:facet name="header">Quantity</f:facet>
    				#{o.qty}
    			</h:column>
 
    		</h:dataTable>
 
    </h:body>
</html>
Generate this HTML output
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
	   <link type="text/css" rel="stylesheet" 
	      href="/JavaServerFaces/faces/javax.faces.resource/table-style.css?ln=css" />
	</head>
	<body> 
 
	<h1>JSF 2 dataTable example</h1>
 
	<table class="order-table"> 
 
  	  <thead> 
		<tr> 
		<th class="order-table-header" scope="col">Order No</th> 
		<th class="order-table-header" scope="col">Product Name</th> 
		<th class="order-table-header" scope="col">Price</th> 
		<th class="order-table-header" scope="col">Quantity</th> 
		</tr> 
	  </thead> 
 
	  <tbody> 
		<tr class="order-table-odd-row"> 
			<td>A0001</td> 
			<td>Intel CPU</td> 
			<td>700.00</td> 
			<td>1</td> 
		</tr> 
		<tr class="order-table-even-row"> 
			<td>A0002</td> 
			<td>Harddisk 10TB</td> 
			<td>500.00</td> 
			<td>2</td> 
		</tr> 
		<tr class="order-table-odd-row"> 
			<td>A0003</td> 
			<td>Dell Laptop</td> 
			<td>11600.00</td> 
			<td>8</td> 
		</tr> 
		<tr class="order-table-even-row"> 
			<td>A0004</td> 
			<td>Samsung LCD</td> 
			<td>5200.00</td> 
			<td>3</td> 
		</tr> 
		<tr class="order-table-odd-row"> 
			<td>A0005</td> 
			<td>A4Tech Mouse</td> 
			<td>100.00</td> 
			<td>10</td> 		
		</tr> 
	  </tbody> 
	 </table> 
      </body> 	
</html>

6. Demo

URL : http://localhost:8080/JavaServerFaces/default.xhtml
jsf2-dataTable-example
Download It – JSF-2-DataTable-Example.zip (11KB)
jsf2-dataTable-folders
Read More

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

Friday 23 August 2013

Java Program to read and write json

// siddhu vydyabhushana // 2 comments
JSON.simple, is a simple Java library for JSON processing, read and write JSON data and full compliance with JSON specification (RFC4627).
Note
To convert object to / from JSON, you should consider Jackson or Gson.
In this tutorial, we show you how to use JSON.simple to read and write JSON data from / to a file.

1. JSON.simple Dependency

JSON.simple is available at Maven central repository, just declares following dependency in your pom.xml file.
  <dependency>
	<groupId>com.googlecode.json-simple</groupId>
	<artifactId>json-simple</artifactId>
	<version>1.1</version>
  </dependency>
 
hii

2. Write JSON to file

In below example, it write JSON data via JSONObject and JSONArray, and save it into a file named “test.json“.
import java.io.FileWriter;
import java.io.IOException;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
 
public class JsonSimpleExample {
     public static void main(String[] args) {
 
	JSONObject obj = new JSONObject();
	obj.put("name", "mkyong.com");
	obj.put("age", new Integer(100));
 
	JSONArray list = new JSONArray();
	list.add("msg 1");
	list.add("msg 2");
	list.add("msg 3");
 
	obj.put("messages", list);
 
	try {
 
		FileWriter file = new FileWriter("c:\\test.json");
		file.write(obj.toJSONString());
		file.flush();
		file.close();
 
	} catch (IOException e) {
		e.printStackTrace();
	}
 
	System.out.print(obj);
 
     }
 
}
Output – See content of file named “test.json“.
{
	"age":100,
	"name":"mkyong.com",
	"messages":["msg 1","msg 2","msg 3"]
}

3. Read JSON from file

Use JSONParser to read above generated JSON file “test.json“, and display each of the values.
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
 
public class JsonSimpleExample {
     public static void main(String[] args) {
 
	JSONParser parser = new JSONParser();
 
	try {
 
		Object obj = parser.parse(new FileReader("c:\\test.json"));
 
		JSONObject jsonObject = (JSONObject) obj;
 
		String name = (String) jsonObject.get("name");
		System.out.println(name);
 
		long age = (Long) jsonObject.get("age");
		System.out.println(age);
 
		// loop array
		JSONArray msg = (JSONArray) jsonObject.get("messages");
		Iterator<String> iterator = msg.iterator();
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}
 
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	} catch (ParseException e) {
		e.printStackTrace();
	}
 
     }
 
}
Output
 100 msg 1 msg 2 msg 3
Read More

java program to compress files in zip format

// siddhu vydyabhushana // 2 comments
Java comes with “java.util.zip” library to perform data compression in ZIp format. The overall concept is quite straightforward.
  1. Read file with “FileInputStream
  2. Add the file name to “ZipEntry” and output it to “ZipOutputStream

1. Simple ZIP example

Read a file “C:\\spy.log” and compress it into a zip file – “C:\\MyFile.zip“.
package com.mkyong.zip;
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
public class App 
{	
    public static void main( String[] args )
    {
    	byte[] buffer = new byte[1024];
 
    	try{
 
    		FileOutputStream fos = new FileOutputStream("C:\\MyFile.zip");
    		ZipOutputStream zos = new ZipOutputStream(fos);
    		ZipEntry ze= new ZipEntry("spy.log");
    		zos.putNextEntry(ze);
    		FileInputStream in = new FileInputStream("C:\\spy.log");
 
    		int len;
    		while ((len = in.read(buffer)) > 0) {
    			zos.write(buffer, 0, len);
    		}
 
    		in.close();
    		zos.closeEntry();
 
    		//remember close it
    		zos.close();
 
    		System.out.println("Done");
 
    	}catch(IOException ex){
    	   ex.printStackTrace();
    	}
    }
}

2. Advance ZIP example – Recursively

Read all files from folder “C:\\testzip” and compress it into a zip file – “C:\\MyFile.zip“. It will recursively zip a directory as well.
package com.mkyong.zip;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
public class AppZip
{
    List<String> fileList;
    private static final String OUTPUT_ZIP_FILE = "C:\\MyFile.zip";
    private static final String SOURCE_FOLDER = "C:\\testzip";
 
    AppZip(){
	fileList = new ArrayList<String>();
    }
 
    public static void main( String[] args )
    {
    	AppZip appZip = new AppZip();
    	appZip.generateFileList(new File(SOURCE_FOLDER));
    	appZip.zipIt(OUTPUT_ZIP_FILE);
    }
 
    /**
     * Zip it
     * @param zipFile output ZIP file location
     */
    public void zipIt(String zipFile){
 
     byte[] buffer = new byte[1024];
 
     try{
 
    	FileOutputStream fos = new FileOutputStream(zipFile);
    	ZipOutputStream zos = new ZipOutputStream(fos);
 
    	System.out.println("Output to Zip : " + zipFile);
 
    	for(String file : this.fileList){
 
    		System.out.println("File Added : " + file);
    		ZipEntry ze= new ZipEntry(file);
        	zos.putNextEntry(ze);
 
        	FileInputStream in = 
                       new FileInputStream(SOURCE_FOLDER + File.separator + file);
 
        	int len;
        	while ((len = in.read(buffer)) > 0) {
        		zos.write(buffer, 0, len);
        	}
 
        	in.close();
    	}
 
    	zos.closeEntry();
    	//remember close it
    	zos.close();
 
    	System.out.println("Done");
    }catch(IOException ex){
       ex.printStackTrace();   
    }
   }
 
    /**
     * Traverse a directory and get all files,
     * and add the file into fileList  
     * @param node file or directory
     */
    public void generateFileList(File node){
 
    	//add file only
	if(node.isFile()){
		fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));
	}
 
	if(node.isDirectory()){
		String[] subNote = node.list();
		for(String filename : subNote){
			generateFileList(new File(node, filename));
		}
	}
 
    }
 
    /**
     * Format the file path for zip
     * @param file file path
     * @return Formatted file path
     */
    private String generateZipEntry(String file){
    	return file.substring(SOURCE_FOLDER.length()+1, file.length());
    }
}
Output
Output to Zip : C:\MyFile.zip
File Added : pdf\Java-Interview.pdf
File Added : spy\log\spy.log
File Added : utf-encoded.txt
File Added : utf.txt
Done
Read More