Pages

Wednesday 23 April 2014

What is the role of JIT in JVM?



This session will explain you brief description about JIT  and how it is different from Interpreter:

JIT (Just In Time):

  In the Java programming language and environment, a just-in-time (JIT) compiler is a program that turns Java byte code into instructions that can be sent directly to the processor. After you've written a Java program, the source language statements are compiled by the Java compiler into bytecode rather than into code that contains instructions that match a particular hardware platform's processor (for example, an Intel Pentium microprocessor). The bytecode is platform-independent code that can be sent to any platform and run on that platform.

 The Java on any platform will interpret the compiled bytecode into instructions understandable by the particular processor. However, the virtual machine handles one bytecode instruction at a time. Using the Java just-in-time compiler at the particular system platform compiles the bytecode into the particular system code (as though the program had been compiled initially on that platform). Once the code has been (re-)compiled by the JIT compiler, it will usually run more quickly in the computer.


This means that in general JIT compiled languages run faster than interpreted language.


Interpreter:
     With interpretation there is no compile stage at all. The code in interpreted line by line, much the same as a language interpreters converts between two languages. Memory hold the state of the application between lines being executed. The interpreter itself runs as the "executable" and is the "middle man" between the programming language being interpreted and the operating system. 

Example progams to throw our own exception.


In this particular blog we will see how to throw our own exception.

Source code:

public class MyOwnException {
    public static void main(String[] a){
        try{
            MyOwnException.Test(null);
        } catch(EmployeeException e){
            System.out.println("Inside catch block: "+e.toString());
        }
    }
    
    static void Test(String str) throws EmployeeException {
        if(str == null){
            throw new EmployeeException ("String val is null");
        }
    }
}
 class EmployeeException extends Exception {
     private String message = null;
      public EmployeeException (String message) {
        super(message);
        this.message = message;
    }
  }

   (or)

public class TestEmployeeException {
   public static void main(String[] args)throws Exception {
          int salary=120000;
           if(salary<20000){
               throw new MyOwnException(salary);
           }
           else{
               System.out.println("No exception");
           }
    }

}


public class MyOwnException extends Exception {

     private int salary;
     public MyOwnException(int salary){
         this.salary= salary;
     }
     public String toString(){
         String exception = "Salary Should be more than 20,000 "+salary;
         return exception;
     }
}


Note: The below two files should be different classes.

 
Thanks for reading !

Monday 21 April 2014

Expanding textarea width and height by default.


 Hi,

The below program will create a text area that dynamically resizes with the text the user enters in it.

Source code:


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Textarea dynamically increase </title>
    <style>
    textarea {
        overflow: hidden;
    }
    </style>
    <script>
    var te = document.querySelector('textarea');
    te.addEventListener('keydown', resizeTextarea);

    function resizeTextarea(ev) {
        this.style.height = '24px';
        this.style.height = this.scrollHeight + 12 + 'px';
    }
    </script>
</head>
<body>
    <textarea rows="3" cols="80"></textarea>
</body>
</html>


-------------------------------------@@@@@@@@@@@@@@@@----------------------------------

Thursday 17 April 2014

Log4j Example with MyEclipse

Log4j Example.

Logging is a very important part of programming that provides advanced debugging capabilities and structured organization of information recorded at the run time. System.out.println (SOP) is a powerful debugging technique that helps to troubleshoot all the errors at the time of development. But when you implement your application in a real time environment, unexpected results and exceptions might occur. Logging provides you an effective mechanism to track all the errors that occurs in your application after you deploy it, so that you can understand what went wrong with your application.

Kindly follow the below steps  for implementing logging with log4j in a simple Java Application using MyEclipse IDE with appropriate code and screenshots.

1) To get log4j jar file click here


2) Open MyEclipse IDE and create a Java Project and name it and click on next and finish button.


       

3)   Create a package , by right clicking on 'src' in Package Explorer > New > Package, I have named this package as 'test'.



4)   Now add the  log4j-xxx.jar you have downloaded to the application you have just created. To do this, right click on the project in Package Explorer > Build Path > Configure Build Path.




5)  In the Java Build Path dialogue, go to Library tab, Click Add External JARs and add the log4j-xxx.jar  and Click OK.


6)Now create a file named as "log4j.properties" in your default package . This is the file that is going to hold all the configuration settings for log4j implementation for all classes in your application. To do this, right click the default package, in this case 'src' in package explorer > New > File >File Name: log4j.properties.
 7) Copy the below code to the log4j.properties file . 
# Log levels
log4j.rootLogger=INFO,CONSOLE,R
# Appender Configuration
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
# Pattern to output the caller's file name and line number
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n
# Rolling File Appender
log4j.appender.R=org.apache.log4j.RollingFileAppender
# Path and file name to store the log file
log4j.appender.R.File=./logs/testlog.log
log4j.appender.R.MaxFileSize=200KB
# Number of backup files
log4j.appender.R.MaxBackupIndex=2
# Layout for Rolling File Appender
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %c - %p - %m%n

8)  Last step is to incorporate logging in your java class. To do this, Create a Class in the package you have created  Right Click the package > New > Class > Class Name:Simple.java





Now Copy and Paste the below code in Simple.java class.

package test;
import org.apache.log4j.Logger;
import java.io.*;
public class Simple{
 private static Logger logger=Logger.getLogger("Log4jExample");
  public static void main(String[] args){
   try{
      FileInputStream fstream = 
                         new FileInputStream("D:\\textfile.txt");
      DataInputStream in = 
                         new DataInputStream(fstream);
      BufferedReader br = 
                  new BufferedReader(new InputStreamReader(in));
      String strLine;
      while ((strLine = br.readLine()) != null){
    System.out.println (strLine);
      }
      in.close();
   }catch (FileNotFoundException fe){
    logger.error("File Not Existed",fe);
        logger.warn("This is a warning message");
        logger.trace("This message will not be logged since log  
                      level is set as DEBUG");
   }catch (IOException e){
    logger.error("IOEXception occured:", e);
  }
 }
}

n the above code I am trying to read a file which does not exist. The log that is generated
on the console is,

ERROR [main] (Simple.java:20) - File Not Found
java.io.FileNotFoundException: D:\textfile.txt (The system cannot find the path specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at test.Simple.main(Simple.java:9)
 WARN [main] (Simple.java:21) - This is a warning message


At the same time log file is generated at \workspace\Simple\logs\testlog.log with the following content,

2014-04-18 09:32:23,337 - Log4jExample - ERROR - File Not Found
java.io.FileNotFoundException: D:\textfile.txt (The system cannot find the path specified)
    at java.io.FileInputStream.open(Native Method)
    at java.io.FileInputStream.<init>(Unknown Source)
    at java.io.FileInputStream.<init>(Unknown Source)
    at test.Simple.main(Simple.java:9)
2014-04-18 09:32:23,342 - Log4jExample - WARN - This is a warning message.