Thursday 9 August 2012

how to create java class dynamically

Program:

package com.accordess.ca;

import java.io.IOException;
import java.net.URI;
import java.util.Arrays;
import java.util.Locale;
import java.util.logging.Logger;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaCompiler.CompilationTask;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;

/**
 * A test class to test dynamic compilation API.
 *
 */
public class CompilerAPITest {
   
    final Logger logger = Logger.getLogger(CompilerAPITest.class.getName()) ;
   
    /**Java source code to be compiled dynamically*/
    static String sourceCode = "package com.accordess.ca;" +
        "class DynamicCompilationHelloWorld{" +
            "public static void main (String args[]){" +
                "System.out.println (\"Hello, dynamic compilation world!\");" +
            "}" +
        "}" ;
   
    /**
     * Does the required object initialization and compilation.
     */
    public void doCompilation (){
       
        /*Creating dynamic java source code file object*/
        SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject ("com.accordess.ca.DynamicCompilationHelloWorld", sourceCode) ;
        JavaFileObject javaFileObjects[] = new JavaFileObject[]{fileObject} ;
       
        /*Instantiating the java compiler*/
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
       
        /**
         * Retrieving the standard file manager from compiler object, which is used to provide
         * basic building block for customizing how a compiler reads and writes to files.
         *
         * The same file manager can be reopened for another compiler task.
         * Thus we reduce the overhead of scanning through file system and jar files each time
         */
       
        StandardJavaFileManager stdFileManager = compiler.getStandardFileManager(null, Locale.getDefault(), null);
       
       
       
        /* Prepare a list of compilation units (java source code file objects) to input to compilation task*/
        Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects);
       
        /*Prepare any compilation options to be used during compilation*/
        //In this example, we are asking the compiler to place the output files under bin folder.
       
        String[] compileOptions = new String[]{"-d", "bin"} ;
        Iterable<String> compilationOptionss = Arrays.asList(compileOptions);
       
        /*Create a diagnostic controller, which holds the compilation problems*/
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
       
        /*Create a compilation task from compiler by passing in the required input objects prepared above*/
        CompilationTask compilerTask = compiler.getTask(null, stdFileManager, diagnostics, compilationOptionss, null, compilationUnits) ;
       
        //Perform the compilation by calling the call method on compilerTask object.
        boolean status = compilerTask.call();
       
        if (!status){//If compilation error occurs
            /*Iterate through each compilation problem and print it*/
            for (Diagnostic diagnostic : diagnostics.getDiagnostics()){
                System.out.format("Error on line %d in %s", diagnostic.getLineNumber(), diagnostic);
            }
        }
        try {
            stdFileManager.close() ;//Close the file manager
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
   
    public static void main(String args[]){
        new CompilerAPITest().doCompilation() ;
    }

}

/**
 * Creates a dynamic source code file object
 *
 * This is an example of how we can prepare a dynamic java source code for compilation.
 * This class reads the java code from a string and prepares a JavaFileObject
 *
 */
class DynamicJavaSourceCodeObject extends SimpleJavaFileObject{
    private String qualifiedName ;
    private String sourceCode ;
   
    /**
     * Converts the name to an URI, as that is the format expected by JavaFileObject
     *
     *
     * @param fully qualified name given to the class file
     * @param code the source code string
     */
    protected DynamicJavaSourceCodeObject(String name, String code) {
        super(URI.create("string:///" +name.replaceAll(".", "/") + Kind.SOURCE.extension), Kind.SOURCE);
        this.qualifiedName = name ;
        this.sourceCode = code ;
    }
   
    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors)
            throws IOException {
        return sourceCode ;
    }

    public String getQualifiedName() {
        return qualifiedName;
    }

    public void setQualifiedName(String qualifiedName) {
        this.qualifiedName = qualifiedName;
    }

    public String getSourceCode() {
        return sourceCode;
    }

    public void setSourceCode(String sourceCode) {
        this.sourceCode = sourceCode;
    }
}

Thanks to www.javaworld.com

Wednesday 8 August 2012

how to use map.entry in java example

Here,How to split  HashMap values  using Map and set interface..........

//package OtherHashMapExamples;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

public class MapUsageExample {

    public static void main(String[] args) {
       
        HashMap hm = new HashMap();
       
        hm.put("Hari" , new Integer(50));
        hm.put(" Kumar", new Integer(30));
        hm.put("Daya", new Integer(60));
        //hm.put("Krishnan", new Integer(70));
       
        Set set = hm.entrySet();
        //System.out.println(" hm.entrySet() : " + set);
       
        Iterator it = set.iterator();
       
        while(it.hasNext()) {
       
            //System.out.println("it Values :  " + it.next());
            Map.Entry<String, Integer> mapMe = (Map.Entry) it.next();
           
            System.out.println(" Mapped Values from Iterator Key : " + mapMe.getKey());
            System.out.println(" Mapped Values from Iterator Values : " + mapMe.getValue());
           
           
        }
        int addValue =  ((Integer) hm.get("Hari")).intValue();
        hm.put("Hari",new Integer(addValue + 450));
        System.out.println( " Hari new Name is : " + hm.get("Hari"));
       

    }

}

Example Program for using ArrayList and Comparator in java Collections and their Methods

Java Object Sorting using Comparator vs Comparable interface Class.
Java Sorting Comparator vs Comparable interface .
Here we are using for Collections Methods  for Sorting Purpose. and ArrayList for Storing Purpose.....
Write a java program to use the Comparator  and Comparable interface in Java.....
(1) Employee.java

package ComparatorVsComparable;

import java.util.Comparator;


public class Employee   {

    private String empNameId;
    private int empAge;
   
    public Employee() {
       
    }
   
    Employee(String empNameId , int empAge) {
   
       
        this.empNameId = empNameId ;
        this.empAge    = empAge ;
       
    }
   
    public String getName() {
       
        return empNameId;
    }
    public void setName(String empNameId) {
       
        this.empNameId = empNameId;
       
    }
    public int getAge() {
       
        return empAge;
    }
    public void setAge(int empAge) {
       
        this.empAge = empAge;
    }
   
   
}

(2)CompareClassOnly.java
package ComparatorVsComparable;

import java.util.Comparator;

public class CompareClassOnly implements Comparator<Employee> {


   
    @Override
    public int compare(Employee emp1, Employee emp2) { // Compare Numbers
       
        System.out.println(" -----------CompareClassOnly Class Executed with Compare Method -----------");
               
        return emp1.getAge() > emp2.getAge() ? -1 : (emp1.getAge() == emp2.getAge() ? 0 : 1 );
    }

}

(3)CompareStringOnly.java

package ComparatorVsComparable;

import java.util.Comparator;

public class CompareStringOnly implements Comparator<Employee>{

    @Override
    public int compare(Employee o1, Employee o2) {
      
        System.out.println(" -----------CompareStringOnly Class Executed with Compare Method -----------");
      
        String str1 = o1.getName();
        String str2 = o2.getName();
      
        return str1.compareTo(str2);
    }

   
   
   
}
(4) ComparatorMainClass.java

package ComparatorVsComparable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;



public class ComparatorMainClass {
   
    public static void main(String args[]) {
      
        List<Employee> list = new ArrayList<Employee>();
      
        list.add(new Employee("Hari581", 24));
        list.add(new Employee("Dayanidhi582", 23));
        list.add(new Employee("Athik111", 22));
        list.add(new Employee("Premkumar486", 28));
        list.add(new Employee("Muthu420", 27));
      
        Collections.sort(list , new CompareStringOnly());
        System.out.println(" \n After Collection Default Descending Sorting NameWise Order Details : ");
        for(Employee e : list) {
          
            System.out.println(" EmpNameId : " +e.getName()+"      EmpAge : " + e.getAge());
        }
      
      
        Collections.sort(list , new CompareClassOnly());
        System.out.println(" \n After Collection Default Descending Sorting AgeWise Order Details : ");
        for(Employee e : list) {
          
            System.out.println(" EmpNameId : " +e.getName()+"      EmpAge : " + e.getAge());
        }
      
    }

}


In This Example used to Find the Given Name with Age for Sorting Purpose..
First Sort with Name Wise ( String Sorting )
Second Sort With Age Wise ( Number Sorting)

output::

 -----------CompareStringOnly Class Executed with Compare Method -----------
 -----------CompareStringOnly Class Executed with Compare Method -----------
 -----------CompareStringOnly Class Executed with Compare Method -----------
 -----------CompareStringOnly Class Executed with Compare Method -----------
 -----------CompareStringOnly Class Executed with Compare Method -----------
 -----------CompareStringOnly Class Executed with Compare Method -----------

 After Collection Default Descending Sorting NameWise Order Details :
 EmpNameId : Athik111      EmpAge : 22
 EmpNameId : Dayanidhi582      EmpAge : 23
 EmpNameId : Hari581      EmpAge : 24
 EmpNameId : Muthu420      EmpAge : 27
 EmpNameId : Premkumar486      EmpAge : 28
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------
 -----------CompareClassOnly Class Executed with Compare Method -----------

 After Collection Default Descending Sorting AgeWise Order Details :
 EmpNameId : Premkumar486      EmpAge : 28
 EmpNameId : Muthu420      EmpAge : 27
 EmpNameId : Hari581      EmpAge : 24
 EmpNameId : Dayanidhi582      EmpAge : 23
 EmpNameId : Athik111      EmpAge : 22

Note:: This Program is for mm Own Code.. If you have any Query pls mail to:  vhkrishnan.v@gmail.com

Wednesday 1 August 2012

why java is not fully or completely oops langauge?

Java is a OOP language and it is not a pure Object Based Programming Language.

Many languages are Object Oriented. There are seven qualities to be satisfied for a programming language to be pure Object Oriented. They are:
  1. Encapsulation/Data Hiding
  2. Inheritance
  3. Polymorphism
  4. Abstraction
  5. All predefined types are objects
  6. All operations are performed by sending messages to objects
  7. All user defined types are objects.

Java is not because it supports Primitive datatype such as int, byte, long... etc, to be used, which are not objects.

Contrast with a pure OOP language like Smalltalk, where there are no primitive types, and boolean, int and methods are all objects.

Which language is fully object oriented language and how ?

OOP languages

Simula (1967) is generally accepted as the first language to have the primary features of an object-oriented language. It was created for making simulation programs, in which what came to be called objects were the most important information representation. Smalltalk (1972 to 1980) is arguably the canonical example, and the one with which much of the theory of object-oriented programming was developed. Concerning the degree of object orientation, the following distinctions can be made:
  • Languages called "pure" OO languages, because everything in them is treated consistently as an object, from primitives such as characters and punctuation, all the way up to whole classes, prototypes, blocks, modules, etc. They were designed specifically to facilitate, even enforce, OO methods. Examples: Eiffel, Emerald.[19], JADE, Obix, Scala, Smalltalk
  • Languages designed mainly for OO programming, but with some procedural elements. Examples: C++, Java, C#, VB.NET, Python.
  • Languages that are historically procedural languages, but have been extended with some OO features. Examples: Visual Basic (derived from BASIC), Fortran, Perl, COBOL 2002, PHP, ABAP.
  • Languages with most of the features of objects (classes, methods, inheritance, reusability), but in a distinctly original form. Examples: Oberon (Oberon-1 or Oberon-2) and Common Lisp.
  • Languages with abstract data type support, but not all features of object-orientation, sometimes called object-based languages. Examples: Modula-2 (with excellent encapsulation and information hiding), Pliant, CLU.

 

Complete Details about eLitmus pH Test at Rs:699/- Share your java material and fresher interview Information for us to Help Others... mail to : vhkrishnan.v@gmail.com