Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Saturday, November 9, 2013

Javac/Java searching algorithm for other classes

With this post, I would like to explain how exactly the Java/Java will search for its dependencies in the project or application level. Java Applications can be run using the command line or in the Web/Application servers. For both the scenarios will be covered as below:

When you are accessing standalone application using command prompt, below will be the search criteria steps:
                                                                                                                                                 More>>>

Monday, August 12, 2013

7 years experienced core java interview questions job interview


This post covers the java interview questions asked for 7 years experienced developers. Post completion of this tutorial, you understand how to prepare for interview if you are experienced developer in Java.

Monday, October 1, 2012

Copy an Array into another Array in Java

The contents of one array can be copied into another array by using the arraycopy() method of the System class in Java.
The arraycopy() method accepts source array, source length, destination array and destination length.
The following program shows the use of arraycopy() method to copy the contents of one array to another.


package com.Test;

public class ArrayCopyTest{

public static void main(String[] args){
int[] src = new int[] {1, 2, 3, 4, 5};

int[] dest = new int[src.length];

System.arraycopy(src, 0, dest, 0, src.length);

for (int i = 0; i < dest.length; i++){
System.out.println(dest[i]);
}
}
}

Wednesday, September 5, 2012

Create XML File in JAVA using DOM


package com.test;
import java.io.File;
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.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class CreateXMLInJava {
public static void main(String argv[]) {
        CreateXMLInJava createXml = new CreateXMLInJava();
        createXml.createXML();
}
public void createXML() {
    try {
         DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
         DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
        // root elements
        Document doc = docBuilder.newDocument();
        Element rootElement = doc.createElement(“Company”);
       doc.appendChild(rootElement);
       // staff elements
       Element staff = doc.createElement(“Dept”);
       rootElement.appendChild(staff);
       // set attribute to staff element
       Attr attr = doc.createAttribute(“id”);
       attr.setValue(“1″);
       staff.setAttributeNode(attr);
       // can be written as
       // staff.setAttribute(“id”, “1″);
       // firstname elements
      Element firstname = doc.createElement(“Firstname”);
       firstname.appendChild(doc.createTextNode(“mallik”));
       staff.appendChild(firstname);
      // lastname elements
      Element lastname = doc.createElement(“Lastname”);
      lastname.appendChild(doc.createTextNode(“Gunda”));
      staff.appendChild(lastname);
        // salary elements
      Element salary = doc.createElement(“Salary”);
      salary.appendChild(doc.createTextNode(“100000″));
      staff.appendChild(salary);
      // 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(“D:\\test.xml”));
     // Output to console for testing
     // StreamResult result = new StreamResult(System.out);
       transformer.transform(source, result);
      System.out.println(“File saved!”);
   } catch (ParserConfigurationException pce) {
       pce.printStackTrace();
  } catch (TransformerException tfe) {
    tfe.printStackTrace();
  }
 }
}

Sunday, September 2, 2012

Percentage calculation Example in Java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public final class Percent {

public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("enter the total no.of sub");
int n = Integer.parseInt(br.readLine());
int marks[] = new int[n];
int i, tot = 0;
for (i = 0; i < n; i++) {
System.out.println("enter ur marks");
marks[i] = Integer.parseInt(br.readLine());
tot = tot + marks[i];
}
System.out.println("total marks: " + tot);
System.out.println("percentage of marks: " + (float) tot / n);
}
}

Friday, July 20, 2012

Convert charr array to String in Java

1. We can convert char array to String by passing the array to String constructor.
public void convertCharArrayToStringOption1() {
    char[] charArray = new char[] { 'a', 'b', 'c', 'd' };
    System.out.println("The new String Array is : "+new String(charArray));
}

2. We can also pass the char array to 'valueOf()' static method of String class:
public void convertCharArrayToStringOption1() {
    char[] charArray = new char[] { 'a', 'b', 'c', 'd' };
    System.out.println("The new String Array is : "+
String.valueOf(charArray));
}

Thursday, July 19, 2012

Marker or Tag interface in java


An interface is called a marker interface when it is provided as a handle by java interpreter to mark a class so that it can provide special behaviour to it at runtime and they do not have any method declarations.

Java Marker Interface Examples


  • java.lang.Cloneable
  • java.io.Serializable
  • java.util.EventListener

Why we need Marker Interface?

Suppose you want to persist (save) the state of an object then you have to implement the Serializable interface otherwise the compiler will throw an error. To make more clearly understand the concept of marker interface you should go through one more example.
Suppose the interface Clonable is neither implemented by a class named Myclass nor it’s any super class, then a call to the method clone() on Myclass’s object will give an error. This means, to add this functionality one should implement the Clonable interface. While the Clonable is an empty interface but it provides an important functionality.
We cannot create marker interfaces, as you cannot instruct JVM to add special behavior to all classes implementing (directly) that special interface.
From java 1.5, the need for marker interface is eliminated by the introduction of the java annotation feature. So, it is wise to use java annotations than the marker interface. It has more feature and advantages than the java marker interface.

Wednesday, March 28, 2012

Java Programming Language Version 7 Features


  • Binary Literals - In Java SE 7, the integral types (byteshortint, and long) can also be expressed using the binary number system. To specify a binary literal, add the prefix0b or 0B to the number.
  • Underscores in Numeric Literals - Any number of underscore characters (_) can appear anywhere between digits in a numerical literal. This feature enables you, for example, to separate groups of digits in numeric literals, which can improve the readability of your code.
  • Strings in switch Statements - You can use the String class in the expression of a switch statement.
  • Type Inference for Generic Instance Creation - You can replace the type arguments required to invoke the constructor of a generic class with an empty set of type parameters (<>) as long as the compiler can infer the type arguments from the context. This pair of angle brackets is informally called the diamond.
  • Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods - The Java SE 7 complier generates a warning at the declaration site of a varargs method or constructor with a non-reifiable varargs formal parameter. Java SE 7 introduces the compiler option -Xlint:varargs and the annotations@SafeVarargs and @SuppressWarnings({"unchecked", "varargs"}) to supress these warnings.
  • The try-with-resources Statement - The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements the newjava.lang.AutoCloseable interface or the java.io.Closeable interface can be used as a resource. The classes java.io.InputStreamOutputStreamReader,Writerjava.sql.ConnectionStatement, and ResultSet have been retrofitted to implement the AutoCloseable interface and can all be used as resources in a try-with-resources statement.
  • Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking - A single catch block can handle more than one type of exception. In addition, the compiler performs more precise analysis of rethrown exceptions than earlier releases of Java SE. This enables you to specify more specific exception types in the throwsclause of a method declaration.

Sunday, February 12, 2012

About Isolation levels & Transaction levels


The isolation level measures concurrent transaction's capacity to view data that have been updated, but not yet committed, by another transaction if other transactions were allowed to read data that are as yet uncommitted, those transactions could end up with inconsistent data were the transaction to roll back, or end up waiting unnecessarily were the transaction to commit successfully.

A higher isolation level means less concurrence and a greater likelihood of performance bottleneck, but also a decreased chance of reading inconsistent data. A good rule of thumb is to use the highest isolation level that yields an acceptable performace level. The following are commin issilation levels, arranged from lowest to highest.

  1. ReadUncommitted: Data that have been updated but not yet committed by a transaction my be read by other transactions
  2. Readcommitted: Only data that have been committed by a transaction can be read by other transactions.
  3. Repeatable Read: Only data that have been commited by a trasaction can be read by other transactions, and multiple reads will yield the same result as log as the data have been committed.
  4. Serializable: This highest possible iosolation level, ensures a transaction's execlusive read-write access to data, it includes the conditions of ReadCommitted and Repeatable Read and stiplulates that all transactions run serially to achieve maximum data integrity. This yields the slowest performance and least concurrency. The term serializable in this context is absolutely unrelated to the database.

Tuesday, January 24, 2012

equals() and hashCode() methods of Object Class

HashTable, HashMap and HashSet are the Collection classes in java.util package that make use of hashing algorithm to store objects. In all these Collection classes except HashSet, objects are stored as key-value pairs. For the storage and the retrieval of any user-defined objects it is a good practice to override the following methods which is mentioned below,
  • hashCode()
  • equals()
These methods are available in the Object class and hence available to all java classes.Using these two methods, an object can be stored or retrieved from a Hashtable, HashMap or HashSet.
hashCode() method
This method returns a hashcode value as an int for the object. Default implementation for hashcode() should be overridden in order to make searching of data faster. The implementation of hashCode() method for an user-defined object should be calculated based on the properties of the class which we wish to consider.
equals() method
This method returns a boolean which specifies whether two objects are equal or not. The default implementation of equals() method given by the Object Class uses the '==' operator to compare two object references, and returns true only if they refer to the same object. But, we can meaningfully re-define this equals() method to have en equality check based on our own criterias.
Consider the following code, which defines two user defined classes Employee and EmployeeId which are supposed to be stored in a Map.
Employee.java

public class Employee {
        private String name;

        public Employee(String name){
               this.name = name;
        }

        public String toString(){
        return name;
        }
}
EmployeeId.java

public class EmployeeId {

        private String id;

        public EmployeeId(String id){
               this.id = id;
        }

        public String toString(){
               return id;
        }      
}
The following class makes use of the above classes by storing it in a Map for later retrieval. We are adding Employee objects into the Map keyed with Employee Id.
HashCodeTest.java

public class HashCodeTest {

        public static void main(String[] args) {

               Map employees = new HashMap();

               employees.put(new EmployeeId("111"), new Employee("Johny"));
               employees.put(new EmployeeId("222"), new Employee("Jeny")); // Line A
               employees.put(new EmployeeId("333"), new Employee("Jessie"));

               Employee emp =  employees.get(new EmployeeId("222")); // Line B
               System.out.println(emp); // Line C
        }
}
In Line B, we try to retrieve the Employee object who has Employee Id with a value of 222. We expect the output to be 'Jeny', because the Employee with Employee Id (222) was already there in the Collection, but surprisingly, the output of the above code is null. The reason is that we did not override the equals() method for EmployeeId and Employee classes because the default implementation of equals() in the Object class considers the new EmployeeId("222") in the put statement and new EmployeeId("222") in the get statement as two different instances, and hence the call to get() in Line B returns null.
Let us look at how the same code works when we provide our desired implementation for hashcode() and equals() methods. We basically override hashcode() here just to make the object to be searched fast.
Employee.java

public class Employee {

        private String name;

        public Employee(String name){
               this.name = name;
        }

        public String toString(){
               return name;
        }

        @Override
        public boolean equals(Object obj){

               if(obj == null) {
                       return false;
               }
               if(obj.getClass() != getClass()){
                       return false;
               }

                Employee emp = (Employee)obj;
               if(this.name == emp.name){
                       return true;
               }
               return false;
        }

        @Override
        public int hashCode(){
               return name.hashCode();
        }
}
EmployeeId.java

public class EmployeeId {

        private String id;

        public EmployeeId(String id){
               this.id = id;
        }

        public String toString(){
               return id;
        }      

        public boolean equals(Object obj){

        if(obj == null)
               return false;

        if(obj.getClass() != getClass()){
               return false;
        }

        EmployeeId empId = (EmployeeId)obj;
        if(this.id == empId.id){
               return true;
        }
        return false;
        }

        @Override
        public int hashCode(){
               return id.hashCode();
        }
}
Now, we get the desired output 'Jeny', because as per our implementation for the equals() method, the new EmployeeId("222") in the put statement and new EmployeeId("222") in the get statement are considered one and the same.