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.