Sunday, 22 December 2013

Underscores Between Digits in Numeric Literals

Underscores are permitted in numeric literals. You can place underscores where you feel required to increase readability; like between hundreds and thousands, thousands and lakhs etc.
This is used to group numbers in a bigger literal value (especially of long data type).
Note: Do not place underscore at the beginning or ending of the literal value.
public class Demo
{
  public static void main(String args[])
  {
    int flatCost = 48_87_653;

    float buildingCost = 6_47_812.25_67f;

    System.out.println("Flat cost Rs. " + flatCost);   
    System.out.println("Building cost Rs. " + buildingCost);   
   }
}


Note: But following does not work (cannot parse with underscores).
    String str ="12_34";
    int x = Integer.parseInt(str);
The above parsing raises NumberFormatException.


Friday, 20 December 2013

The Upcoming Scala Concept.

The pragmatist among JVM languages, Scala is a general-purpose programming language. It was conceived and is generally viewed as a “better Java,” and of all alternative JVM languages has the best acceptance in an enterprise setting.

Scala combines the familiar feel of object-oriented Java with strong language support for concurrency, XML and functional programming features: many of the tools that contemporary complex and scalable systems require. Scala also takes a lot of the awkwardness out of Java code, through features such as type inference and traits.
 object HelloWorld {   
 def main(args: Array[String]) {      
println("Hello, World!")    
}  

}

Longest Attributes Methods and Class names in java.

Please find the Longest Class , attributes and method names used in rt.jar that ran in jdk 1.6.

  • For class name the award goes to (92 chars)InternalFrameInternalFrameTitlePaneInternalFrameTitlePane
    MaximizeButtonWindowNotFocusedState
  • For method name the award goes to (66 chars)localizableRUNTIME_MODELER_PORTNAME_SERVICENAME
    _NAMESPACE_MISMATCH
     belonging to class ModelerMessages.
  • For attribute name the award goes to (60 chars)ER_INVALID_NAMESPACE_URI_VALUE_FOR_RESULT_PREFIX
    _FOR_DEFAULT
     belonging to class XSLTErrorResources.

Monday, 16 December 2013

BINARY LITERALS in JAVA 7

Before Java 7, if you wanted to manipulate a binary value, you’d have had to either engage in awkward (and error-prone) base conversion or utilize parseX methods. For example, if you wanted to ensure that an int x represented the bit pattern for the decimal value 102 correctly, you’d write an expression like:

                                        int x = Integer.parseInt("1100110", 2);

This is a lot of code just to ensure that x ends up with the correct bit pattern. There’sworse to come though. Despite looking fine, there are a number of problems with this approach:
■ It’s really verbose.
■ There is a performance hit for that method call.
■ You’d have to know about the two-argument form of parseInt().
■ You need to remember the details of how parseInt()behaves when it has
two arguments.
■ It makes life hard for the JIT compiler.
■ It represents a compile-time constant as a runtime expression, which means the
constant can’t be used as a value in a switch statement.
■ It will give you a RuntimeException (but no compile-time exception) if you
have a typo in the binary value.
Fortunately, with the advent of Java 7, we can now write this:

                                                int x = 0b1100110;

No one’s saying that this is doing anything that couldn’t be done before, but it has none of the problems we listed. If you’ve got a reason to work with binary, you’ll be glad to have this small feature.For example, when doing low-level handling of bytes, you can now have bit patterns as binary constants in switch statements.

Sunday, 15 December 2013

The Diamond Syntax.

Java 7 also introduces a change that means less typing for you when dealing with generics. One of theb problems with generics is that the definitions and setup of instances can be really verbose. Let’s suppose that you have some users, whom you identify by userid (which is an integer), and each user has one or more lookup tables specific to that user.

Map<Integer, Map<String, String>> usersLists = new HashMap<Integer, Map<String, String>>();

That’s quite a mouthful, and almost half of it is duplicated characters. Wouldn’t it be better if you could write something like this,

Map<Integer, Map<String, String>> usersLists = new HashMap<>();

and have the compiler work out the type information on the right side? Thanks to the magic of Project Coin, you can. In Java 7, the shortened form for declarations like that is entirely legal. It’s backwards compatible as well, so when you find yourself revisiting old code, you can cut the older, more verbose declaration and start using the new type-inferred syntax to save a few pixels. We should point out that the compiler is using a new form of type inference for this feature. It’s working out the correct type for the expression on the right side, and isn’t just substituting in the text that defines the full type. This form is called “diamond syntax” because, well, the shortened type information looks like a diamond. The proper name in the proposal is “Improved Type Inference for Generic Instance Creation,” which is a real mouthful and has ITIGIC as an acronym, which sounds stupid, so diamond syntax it is.The new diamond syntax will certainly save your fingers from some typing.

Saturday, 14 December 2013

Try with resources.

This change is easy to explain, but it has proved to have hidden subtleties, which made it much less easy to implement than originally hoped. The basic idea is to allow a resource (for example, a file or something a bit like one) to be scoped to a block in such a way that the resource is automatically closed when control exits the block. This is an important change, for the simple reason that virtually no one gets manual resource closing 100 percent right.  The proposal submitted to Project Coin for this change includes the astounding claim that two-thirds of the uses of close() in the JDK had bugs in them! Fortunately, compilers can be made to produce exactly the sort of pedantic, boilerplate code that humans so often get wrong, and that’s the approach taken by this change This is a big help in writing error-free code. To see just how helpful, consider how you’d write a block of code that reads from a stream coming from a URL (url) and writes to a file (out) with Java 6. Here’s one possible solution.
InputStream is = null;
try {
 is = url.openStream();
 OutputStream out = new FileOutputStream(file);
 try {
 byte[] buf = new byte[4096];
 int len;
 while ((len = is.read(buf)) >= 0)
 out.write(buf, 0, len);
 } catch (IOException iox) {
 } finally {
 try {
 out.close();
 } catch (IOException closeOutx) {
 }
 }
} catch (FileNotFoundException fnfx) {
} catch (IOException openx) {
} finally {
 try {
 if (is != null) is.close();
 } catch (IOException closeInx) {
 }
}
InputStream is = null;
try {
 is = url.openStream();
 OutputStream out = new FileOutputStream(file);
 try {
 byte[] buf = new byte[4096];
 int len;
 while ((len = is.read(buf)) >= 0)
 out.write(buf, 0, len);
 } catch (IOException iox) {
 } finally {
 try {
 out.close();
 } catch (IOException closeOutx) {
 }
 }
} catch (FileNotFoundException fnfx) {
} catch (IOException openx) {
} finally {
 try {
 if (is != null) is.close();
 } catch (IOException closeInx) {
 }
}
Let’s look at the Java 7 code for performing the same task as listing 1.3. As before, url is a URL object that points at the entity you want to download, and file is a File object where you want to save what you’re downloading. Here’s what this looks like in Java 7.

try (OutputStream out = new FileOutputStream(file);
InputStream is = url.openStream() ) {
byte[] buf = new byte[4096];
int len;
while ((len = is.read(buf)) > 0) {
out.write(buf, 0, len);
}
}

You still have to be careful with try-with-resources, as there are cases where a resource might still not be closed. For example, the following code would not close its FileInputStream properly if there was an error creating the ObjectInputStream
from the file (someFile.bin).

try ( ObjectInputStream in = new ObjectInputStream(new
FileInputStream("someFile.bin")) ) {
...
}

Multi Language Virtual Machine.

Java is an open source and is also platform independent . Now the new release of java version prove to be multi - language virtual machine .Java 6 provided the capability to plug-in other languages in the
VM.  Java 7 to be strengthened to make the other languages run even better in the JVM. JVM to be optimized to make the language specific features run better (Ex: Closures).

Limitation of current I/O API
•Deletion is not guaranteed. Need to do a check to determine if the file is deleted.
•Operations on directory are not scalable and run on the parent thread
•Polling will need to be done for changes on files

New I/O APIs
• New File System API
• File Notifications
• Directory Operations
• Asynchronous I/0

Thursday, 12 December 2013

Multiple exception handling in a single catch block

The earlier versions of java had multiple catch block one after the other where we can handle several exceptions in one try and multiple catch block as follows:

try
{
//do someting;
}
catch(Exception1 e)
{
handleException(e)
}
catch(SQLException e)
{
handleException(e)
}

Java 7 has introduced the new feature of adding multiple exception objects in one catch block as below.

try
{
//do someting;
}
catch(Exception1, Exception2 e)
{
handleException(e)
}

This feature thereby reduces the overhead on the developer .

Tuesday, 10 December 2013

"String" datatypes in SWITCH : .

Switch statements are commonly applied in most of the programming languages and in java too . Switch statement accepts two datatypes , char and int till java 6. But now java 7 has added a feature where switch statement can accept string values too . It matches the string with the cases and executes the code. Please see the following program for more understanding .

String s = ….;
switch(s)
{
case "subbu": 
System.err.println("It is subbu man!");
break;
case "ryan": 
System.err.println("It is ryan man!");
 break;
case "john":
default: 
System.err.println("Default");
break;
}

Sunday, 8 December 2013

Infinity Logic in java Without Exception.

It is normal when we divide a integer number by 0 we get arithmetic exception in java . But you will be surprised to see that the following program does not throw exception rather prints Infinity .

Please have a look at the following code and the corresponding output.

public class TestInfinity {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
float f = 10.0f;
float g = 0.0f;
float z = f/g;
System.out.println(z);
}

}


Saturday, 7 December 2013

Location finder in Android

This article deals with accessing the location of the user using location providers, we need to set permissions in the android manifest file.
<manifest ... >
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <uses-permission android:name="android.permission. ACCESS_COARSE_LOCATION" />
   <uses-permission android:name="android.permission.INTERNET" />
</manifest>

ACCESS_COARSE_LOCATION is used when we use network location provider for our Android app. But, ACCESS_FINE_LOCATION is providing permission for both providers. INTERNET permission is must for the use of network provider.

package com;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;

import android.util.Log;

public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtLat = (TextView) findViewById(R.id.textview1);

locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
@Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}

@Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}

@Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}

XML files for layout and android manifest are as shown below

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textview1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.javapapers.android.geolocationfinder"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17"        />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppBaseTheme" >
        <activity
            android:name="com.javapapers.android.geolocationfinder.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Friday, 6 December 2013

Sample piece of code to handle connections in thread .

A Runnable class can be created to house the procedure for polling the database and creating the alerts. The following PGM1 shows that Runnable that will be used to create the managed thread. In this example, a class named ReservationAlerter. That class can then be made into a thread by calling a ManagedThreadFactory’s newThread() method, as shown in PGM2.
PGM1:
public class ReservationAlerter implements Runnable {

    @Override
    public void run() {

        while (!Thread.interrupted()) {
            reviewReservations();
            try {
                Thread.sleep(100000);
            } catch (InterruptedException ex) {
                // Log error
            }
        }
    }

    public Collection reviewReservations() {

        Connection conn = null;
        Properties connectionProps = new Properties();
        connectionProps.put("user", "user");
        connectionProps.put("password", "password");
        Collection reservations = null;
        try {
            // Obtain connection and retrieve reservations
            conn = DriverManager.getConnection(
                "jdbc:derby:acme;create=false",
                connectionProps);
            // Use the connection to query the database for reservations
        } catch (SQLException ex){
            System.out.println("Exception: " + ex);
        } finally {
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException ex) {
                    // Log error
                }
            }
        }
        return reservations;
    }

}

PGM2:
ReservationAlerter alerter = new ReservationAlerter();

alerterThread = threadFactory.newThread(alerter);
alerterThread.start();

PGM3 shows the complete code for obtaining a reference to the ManagedThreadFactory via @Resource injection, creating the new Thread instance, and then starting it.

PGM3:

public class AcmeAlerterContextListener implements ServletContextListener {
    Thread alerterThread = null;
    @Resource(name="concurrent/__defaultManagedThreadFactory")
    ManagedThreadFactory threadFactory;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ReservationAlerter alerter = new ReservationAlerter();
        alerterThread = threadFactory.newThread(alerter);
        alerterThread.start();
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        if(alerterThread!=null){
            alerterThread.interrupt();
        }
    }
   
   
}

l y a g �� д 0pt;margin-right:.5in;margin-bottom: 6.0pt;margin-left:0in;line-height:normal;mso-pagination:none;mso-layout-grid-align: none;text-autospace:none'>        Properties connectionProps = new Properties();

        connectionProps.put("user", "user");
        connectionProps.put("password", "password");
        Collection reservations = null;
        try {
            // Obtain connection and retrieve reservations
            conn = DriverManager.getConnection(
                "jdbc:derby:acme;create=false",
                connectionProps);
            // Use the connection to query the database for reservations
        } catch (SQLException ex){
            System.out.println("Exception: " + ex);
        } finally {
            if (conn != null){
                try {
                    conn.close();
                } catch (SQLException ex) {
                    // Log error
                }
            }
        }
        return reservations;
    }
}

Function as Argument in Lambda


package com;

The following is an example of how method is implemented by passing the functionitself as an argument.
We have got couple of implementations for the circle interface and they two different operations with respect to context. Those anonymous class implementations itself are passed as argument to another generic method, thus achieving a level of generic function.
public class LambdaFunctionArgument {

  interface Circle {
    double get(double radius);
  }

  public double circleOperation(double radius, Circle c) {
    return c.get(radius);
  }

  public static void main(String args[]){
    LambdaFunctionArgument reference = new LambdaFunctionArgument();
    Circle circleArea = (r) -> Math.PI * r * r;
    Circle circleCircumference = (r) -> 2 * Math.PI * r;
    
    double area = reference.circleOperation(10, circleArea);
    double circumference = reference.circleOperation(10, circleCircumference);
  
    System.out.println("Area: "+area+" . Circumference: "+circumference);
  }
}

Sunday, 1 December 2013

Crack your JVM

Wanna crash you JVM ? Just try the following code but only at your own risk . Ensure that you have tools.jar in your classpath both at compile time and run time . This not only crashes the   just the JVM it was deployed to, but also the virtual and/or physical machine underneath.

public class Crash {
  public static void main(String... args) throws Exception {
    com.sun.tools.attach.VirtualMachine.attach("-1");
  }

}

We are trying to attach ourselves to an already existing Java process specifying -1 as the process id. Instead of failing nicely you get something similar to the blue screen of death.

Saturday, 30 November 2013

Precompiling JSP from Command prompt (contd)

As a continuation of the previous article let us see how to compile the JSP files from command prompt .
<project name="Webapp Precompilation" default="all" basedir=".">
   <import file="${tomcat.home}/bin/catalina-tasks.xml"/>
   <target name="jspc">
<jasper
             validateXml="false"
             uriroot="${webapp.path}"
             webXmlFragment="${webapp.path}/WEB-INF/generated_web.xml"
             outputDir="${webapp.path}/WEB-INF/src" />
  </target>
  <target name="compile">
    <mkdir dir="${webapp.path}/WEB-INF/classes"/>
    <mkdir dir="${webapp.path}/WEB-INF/lib"/>
    <javac destdir="${webapp.path}/WEB-INF/classes"
           optimize="off"
           debug="on" failonerror="false"
           srcdir="${webapp.path}/WEB-INF/src"
excludes="**/*.smap">
      <classpath>
        <pathelement location="${webapp.path}/WEB-INF/classes"/>
        <fileset dir="${webapp.path}/WEB-INF/lib">
          <include name="*.jar"/>
        </fileset>
        <pathelement location="${tomcat.home}/lib"/>
        <fileset dir="${tomcat.home}/common/lib">
          <include name="*.jar"/>
        </fileset>
        <fileset dir="${tomcat.home}/bin">
          <include name="*.jar"/>
        </fileset>
      </classpath>
      <include name="**" />
      <exclude name="tags/**" />
    </javac>
  </target>
  <target name="all" depends="jspc,compile">
  </target>
  <target name="cleanup">
   <delete>
        <fileset dir="${webapp.path}/WEB-INF/src"/>
        <fileset dir="${webapp.path}/WEB-INF/classes/org/apache/jsp"/>
   </delete>
  </target>
</project>
Add the above code in the ant script and execute the following command to pre compile JSP files from command prompt:
$ANT_HOME/bin/ant -Dtomcat.home=<$TOMCAT_HOME> -Dwebapp.path=<$WEBAPP_PATH>

Friday, 29 November 2013

Precompile your JSP's

The Jsp Pages are normally not pre-compiled for deployment . But We can pre-compile the JSP pages if neccessary specific to the application server(tomcat/weblogic server) . The file will just be compiled and the request will not be served . Hence it can be considered to be pre-compiled. The jsp_precompile parameter may have no value, or may have values true or false. It should not have any other values like ?jsp_precompile=yes – this will result in HTTP error 500.
So the example for query strings to pre compile jsp files are
?jsp_precompile
?jsp_precompile=true
?jsp_precompile=false
?foobar=foobaz&jsp_precompile=true
?foobar=foobaz&jsp_precompile=false

There are no special features available for this in the JSP specification. But the application servers (JSP containers) provide methods to do this on their own way. At the end of this tutorial we will see how to pre compile JSP files for Apache Tomcat 6. But if you want to pre compile in server independent manner you have to use jsp_precompile request parameter and no other option available. To do it for the whole application, you can custom write a servlet or jsp file which will raise a request for all the JSPs available with jsp_precompile added as parameter.


<%@ page import="javax.servlet.*,javax.servlet.http.*,javax.servlet.jsp.* "%>
<%@ page import="java.util.Set,java.util.Iterator,java.io.IOException"%>
<%!
  private void preCompileJsp(PageContext pageContext, JspWriter out,
   HttpServletRequest request, HttpServletResponse response, String uripath)
   throws IOException, ServletException {

     // getting jsp files list for pre compilation
     Set jspFilesSet = pageContext.getServletContext().getResourcePaths(uripath);
     for (Iterator jspFilesSetItr = jspFilesSet.iterator(); jspFilesSetItr.hasNext();) {
         String uri = (String) jspFilesSetItr.next();
         if (uri.endsWith(".jsp")) {
             RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
             if (rd == null) throw new Error(uri +" - not found");
             rd.include(request, response);
         }
         else if (uri.endsWith("/")) {
             preCompileJsp(pageContext, out, request, response, uri);
         }
     }
   }
%>
<html><head><title>Pre Compile JSP Files</title></head>
<body>
<%
  HttpServletRequest req = new HttpServletRequestWrapper(request) {
      public String getQueryString() {
          // setting the pre compile parameter
          return "jsp_precompile";
      };
  };
  preCompileJsp(pageContext, out, req, response, "/");
%>
JSP files Pre Compile Completed.

</body></html>

Concurrency utilities for JavaEE

Poor performance can be detrimental to an application’s success. Performance can be measured in many ways. Whether application users can initiate tasks and then move onto others without waiting, or whether a database needs to be queried and return results without blocking a user interface, the bottom line is that waiting for tasks to be completed can become a user nightmare, making a poorly performing application difficult to use. In Java SE, the idea of threading is a standard technique that is used to help prevent bad user experiences,because it allows for long-running tasks to be spawned into a separate thread and executed  in the background without waits occurring. Java EE 7 includes the concurrency utilities for Java EE, which standardize a solution for using application components and Java EE services in an asynchronous manner. The API provides an easy path for those familiar with Java SE concurrency to use it for enterprise applications. Before Java EE 6, it was more difficult to perform concurrent tasks with server side applications,because application server containers typically ran application component code on a thread that was managed by the container, and container supplied object access occurred within the same thread. It is unwise to spawn new threads in an application server environment using java.lang.Thread or java.util .Timer, because that can lead to unreliable results. The situation improved when asynchronous Enterprise JavaBeans (EJB) was introduced with Java EE 6, which allowed processing to occur asynchronously on a thread other than the request handling thread. The concurrency utilities for Java EE build upon asynchronous EJB, and introduce a set of application server concurrency services that assist in the asynchronous execution of tasks in an effort to provide a more complete concurrency solution for Java enterprise applications.

Tuesday, 26 November 2013

A simple program using Lambda Expression

In the process of understanding Lambda expression in java 8 , let us try to understand the simple program given below.  The HelloWorld interface is given an implementation in the main method . After implementation, we use that instance and invoke its single methods. There will be always only one method and so the lambda expression need not specify the method name.

package com
public class LambdaHelloWorld {
  interface HelloWorld {
    String hello(String name);
  }
   public static void main(String[] args) {       
     HelloWorld helloWorld = (String name) -> { return "Hello " + name; };
     System.out.println(helloWorld.hello("Joe"));
  }
}

Monday, 25 November 2013

Progress in JSR

This article holds a discussion on the important changes implemented by JCP.next.  JSRs 348, 355, and 358 are collectively referred to as JCP.next. These JSRs address a number of important issues related to openness, agility, and governance.There used to be a perception that Expert Groups operated secretly, working  behind closed doors for months or even years, after which a new specification would mysteriously appear. JSR 348, which is now in effect, changes that paradigm substantially. It requires Expert Groups to conduct their business transparently via public mailing lists and a public Issue Tracker. The JSR explicitly states that all JCP members, and members of the public, must have the opportunity to view, comment on, and participate in the process. Transparency and participation are the keys to running an effective standards-development process in a world where open source practices are becoming increasingly ubiquitous. JSR 348 facilitates these practices. JSR 355, also complete, was fairly simple. We previously had two separate Executive Committees, one for Java ME and one for Java SE/EE. Now those have been merged into one. With Java ME and Java SE/EE convergence on the horizon, it no longer makes sense to maintain two Executive Committees. This change will streamline operations considerably. JSR 358 is still in progress. It will take transparency and participation to the next level, mandating the use of open source development processes and open source licenses for virtually all JSRs. This is a complex task, because it involves changes to the Java Specification Participation Agreement (JSPA), the legal contract that JCP members sign when they join the organization. It is difficult to modify the JSPA because it contains complex legal language dealing with issues such as intellectual property and licensing models. We have to be very careful when changing it, because the repercussions can be far-reaching. So, JSR 358 is going to take some time. 

Sunday, 24 November 2013

Accessing Local and instance variable in Java 8 using Lambda .

The following code helps us understand the concept of accessing local and instance variables in java 8.
In the following code , "wildAnimal" is the instance variable and "domesticAnimal"  is the local variable declared in the program.The thread constructor is overrided to start the thread using the -> expression .

package com;
public class LambdaVariableAccess {
  public String wildAnimal = "Lion";

  public static void main(String[] arg) {
    new LambdaVariableAccess().lambdaExpression();
  }
public void lambdaExpression(){
        String domesticAnimal = "Dog";
        
        new Thread (() -> {
            System.out.println("Class Level: " + this.wildAnimal);
          System.out.println("Method Level: " + domesticAnimal);
       }).start();       
    }
}

Friday, 22 November 2013

Scope Resolution operator in java

Scope resolution operator is commonly used in C++ , but none of us ever thought of using scope resolution operator in java . Here come Java 8 with options unthought  Ideas being implemented. Method reference in Java 8 is the ability to use a method as an argument for a matching functional interface. :: (double colon) is the operator used for method reference in Java. An interface with only one method is called a functional interface. For example, Comparable, Runnable, AutoCloseable are some functional interfaces in Java.
Its there all through the Internet saying Java does not have the scope resolution operator (::), in comparison with C++. Its on the way and it will be here with Java 8. Between Java and C++, only the operator :: (double colon) is same, the way it is implemented is different. So we cannot call it as scope resolution operator in Java. It is used for method referencing and not for scope resolution.Method reference using :: is a convenience operator. Method reference is one of the features belonging to Java Lamda Expressions. Method reference can be expressed using the usual lambda expression syntax format using –>In order to make it more simple :: operator can be used.

                      Syntax: <classname or instancename>::<methodname>

Thursday, 14 November 2013

Java Hotspot VM.

Java HotSpot VM has an extremely advanced justin-time (JIT) compiler, which enables Java HotSpot VM to produce very highly optimized machine code for any platform that Java HotSpot VM runs on. In this article, we will lift the curtain on an important aspect of Java HotSpot VM’s JIT compiler: the code cache. Understanding the code cache provides insight into a range of performance issues that are otherwise difficult to track down.

Lifecycle of a Java Method:

The smallest unit of new code that the Java platform will load and link into a running program is a class. This means that when a new method is being onboarded, it must go through the class-loading process (as part of the class that contains it). The class-loading process acts as a pinch point: a place where a lot of the Java platform’s security checks are concentrated. The lifecycle of a Java method, therefore, starts with the class-loading process that brings a new class into the running Java Virtual Machine (JVM).

Monday, 4 November 2013

The Code Model for a java compiler API

This is a big project, so let’s start small. Everything in the tool works on an abstraction of the source codebase,so we need to build a core model. The actual tree structures provided by the Java Compiler API contain all the
information we need, but they are not in a convenient package, so we will build our own wrapper classes. First is the MethodModel, which represents everything we know about a single method. A method has a name, the body (the actual statements inside the method), and a list of parameter
variables and their types.
public class MethodModel implements Comparable<MethodModel> {
public String name = "";
public String body = "";
public CompilationUnitTree compUnit;
public long start;
public long end;
private List<String> varTypes = new ArrayList<String>();
private List<String> varNames = new ArrayList<String>();

I’ve also included two longs for start and end as well as a reference to the
CompilationUnitTree. I will explain these later. Next is the class model,
which represents a single class in the codebase. It has a class name and two collections of MethodModel representing the methods within this class. I am using both a list and a method map because I need the methods
to be ordered (which the list provides) and also addressable by name (which the map provides). Next is the ClassModel definition
public class ClassModel implements Comparable<ClassModel> {
public String name;
private List<MethodModel> methods = new ArrayList<MethodModel>();
private Map<String,MethodModel> methodMap = new HashMap<String, MethodModel>();
There are also accessor and utility methods for getting a particular method by name or index and for sorting the methods.These accessors are
not shown. See the full source for details. The methodMap also ensures that the methods are unique. Java allows two methods to have the same name,
so we can’t use just the name as the key for the hash map. We need something unique. To fix this, MethodModel.getUniqueName()
will return a unique key based on the method name as well as the
names of the parameters, which must be unique. The PackageModel and
CodebaseModel classes look very similar to the ClassModel; they are just higher levels
 public class PackageModel {
public String name;
public Set<ClassModel> classSet = new HashSet<ClassModel>();
public List<ClassModel> classList = new ArrayList<ClassModel>();
public Map<String,ClassModel> classMap = new HashMap<String, ClassModel>();
public class CodebaseModel {
List<String> packageList = new ArrayList<String>();
Map<String,PackageModel> packageMap = new HashMap<String, PackageModel>();
PackageModel represents a single package. The CodebaseModel represents

the entire codebase full of packages. Again, utility and accessor methods are not shown.