Wednesday, October 29, 2014

Making Executable Jar File


Creating an executable JAR file. Here is the general procedure for creating an executable JAR:

1. Compile your java code (for ex: Hello.java), generating all of the program's class files.

2. Create a manifest file containing the following 2 lines: (named as Hello.mf)
Manifest-Version: 1.0
Main-Class: Hello  (name of the main class)

Note: The name of the file should end with the .mf suffix. It is important that the file ends with a blank line.

3. To create the JAR, open command prompt and type the following command:
jar cmf manifest-file jar-file input-files
Ex: jar cmf Hello.mf Hello.jar *.java *.class

Note: The input-files must include any class files, images, sounds, etc. that your program uses. Optionally, you can include the program's .java files in the JAR. See below for adding directories to  the JAR.

4. To view the contents of the JAR, type:
jar tf jar-file
Ex: jar tf Hello.jar

5. Execute the application from the command line by typing:
java -jar jar-file

Ex: java -jar Hello.jar

Monday, October 13, 2014

Try-with-resources in Java 7

Try-with-resources in Java 7

Try-with-resources in Java 7 is a new exception handling mechanism that makes it easier to correctly close resources that are used within a try-catch block.

Resource Management With Try-Catch-Finally, Old School Style 

Managing resources that need to be explicitly closed is somewhat tedious before Java 7.
private static void printFile() throws IOException {
    InputStream input = null;

    try {
        input = new FileInputStream("file.txt");

        int data = input.read();
        while(data != -1){
            System.out.print((char) data);
            data = input.read();
        }
    } finally {
        if(input != null){
            input.close();
        }
    }
}
The code marked in bold is where the code can throw an Exception. As you can see, that can happen in 3 places inside the try-block, and 1 place inside the finally-block.

The finally block is always executed no matter if an exception is thrown from the try block or not. That means, that the InputStream is closed no matter what happens in the try block. Or, attempted closed that is. TheInputStream's close() method may throw an exception too, if closing it fails.

Thursday, September 11, 2014

Method Overriding with Exception Handling

Method Overriding with Exception Handling

There are many rules if we talk about method overriding with exception handling. The Rules are as follows:
  • If the super class method does not declare an exception
    • If the super class method does not declare an exception, subclass overridden method cannot declare the checked exception but it can declare unchecked exception.
  • If the super class method declares an exception
    • If the super class method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. 

Monday, June 09, 2014

What's New in Java 8 - Method References

Method references provide easy-to-read lambda expressions for methods that already have a name.
We have seen lambda expressions to crate anonymous methods in my post What's New in Java 8 - Lambda Expressions. Sometimes a lambda expression does nothing but call an existing method (will see example in detail). In those cases, we use method references instead lambda expressions. Method references are compact and easy to read lambda expressions for methods that already have a name.

Example  :

To better understand, consider the same car example discussed in my previous post, but here a extra compareByEngineCC static method.

public class Car{
    public enum Color {
        BLACK, WHITE, RED
    }
    public String modelName;
    public Color color;
    public int engineCC;
    public void printModelName() {
        // ...
    }
    
    public static int compareByEngineCC(Car c1, Car c2) {
        if( c1.engineCC  == c2.engineCC) return 0;
        return c1.engineCC > c2.engineCC?1:-1;
    }
}

The requirement is sort the array of cars by engineCC, so that I added a static method to  compare the cars.
We can use sort method which is static in Arrays class to meat this requirement, but in order to use this static method we need to provide Comparator, So we implemented a CarEngineCCComparator class as shown below

Thursday, May 01, 2014

What's New in Java 8 - Lambda Expressions

Introduction :

Lambda Expressions enable us to treat functionality as a method argument or code as data . Well, What is functionality as a method argument? Did we already use this before? Yes, the answer is yes, we already used this concept before with anonymous classes. In anonymous classes case, we are usually trying to pass functionality as an argument to another method. Lambda expressions are also to do this. Although  anonymous classe is often more concise than a named class, for classes with only one method, even an anonymous class seems a bit excessive and cumbersome.

Usage :

First let us  discuss the usage of  the Lambda Expressions then will go through the syntax of Lambda Expressions.Suppose that you are creating an application for car sellers. You are asked to create a feature that search cars by certain criteria.
Car class can be represented as follows.
public class Car{
    public enum Color {
        BLACK, WHITE, RED
    }
    public String modelName;
    public Color color;
    public int engineCC;
    public void printModelName() {
        // ...
    }
}
Now you need to implement a feature that search for cars that match one characteristic such as engine cc.One simplistic approach is  create a method that  searches for cars that match one characteristic, such as engine cc. The following method prints Model name that are greater than the specified engine CC.

What's New in Java 8

I posted a post with title 'What's New in Java 7', so I am posting the same for Java 8 also but I will post separate on each new feature of Java 8, this post is something introduction of Java 8  features, will discuss each feature separate with detailed examples and usages of the feature.

Java 8  Features:
  • Lambda Expressions: These are the expression like any other expressions and enable us to treat functionality as a method argument, or code as data. Lambda expressions let us express instances of single-method interfaces more compactly. These single abstract method interfaces are also called as functional interfaces. Here you may get one question, Why It is being specified  abstract method though all methods in interface are abstract. Well, these functional interfaces may have implemented methods they are called  default (new feature in java 8).
  • Default Methods: As we discussed  Default methods are methods in an interface that have an implementation. They enable new functionality to be added to the interfaces of libraries. New Package has been added for this functional interfaces to library 
  • Aggregate Operations: Aggregate operations  enable us to perform functional-style operations on streams of elements, in particular, bulk operations on collections, such as sequential or parallel map-reduce transformations. New methods and inter faces added in collection frame work.
  • Date-Time APIs: These new APIs enable us to represent dates and times and manipulate date and time values. They support the International Organization for Standardization (ISO) calendar system as well as other commonly used global calendars.
There are other features added to Java 8 like type annotations, enhanced security etc. But I will be discussing above four features in detail.  In my  next post I will discuss Lambda Expressions. 

Friday, January 31, 2014

What is different between web server and application server?

The different between web server and application server :

A web server responsibility is to handler HTTP requests from client browsers and respond with HTML response. A web server understands HTTP language and runs on HTTP protocol.

Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as servlet container, for example Tomcat.

Application Servers provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc. So we can say that Application server is a web server with additional functionalities to help developers with enterprise applications.

Wednesday, January 29, 2014

Android layout types

Android Layout Types

There are number of Layouts provided by Android which you will use in almost all the Android applications to provide different view, look and feel.

S.N.
Layout & Description
1
Linear Layout
LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally.
2
Relative Layout
RelativeLayout is a view group that displays child views in relative positions.
3
Table Layout
TableLayout is a view that groups views into rows and columns.
4
Absolute Layout
AbsoluteLayout enables you to specify the exact location of its children.
5
Frame Layout
The FrameLayout is a placeholder on screen that you can use to display a single view.
6
List View
ListView is a view group that displays a list of scrollable items.
7
Grid View
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.



Android manifest file

The Android Manifest File

Whatever component you develop as a part of your application, you must declare all its components in a manifest file called AndroidManifest.xml which ressides at the root of the application project directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS. For example, a default manifest file will look like as following file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.helloworld"
   android:versionCode="1"
   android:versionName="1.0" >
   <uses-sdk
      android:minSdkVersion="8"
      android:targetSdkVersion="15" />
   <application
       android:icon="@drawable/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >
       <activity
           android:name=".MainActivity"
           android:label="@string/title_activity_main" >
           <intent-filter>
               <action android:name="android.intent.action.MAIN" />
               <category android:name="android.intent.category.LAUNCHER"/>
           </intent-filter>
       </activity>
   </application>
</manifest>

Here <application>...</application> tags enclosed the components related to the application. Attributeandroid:icon will point to the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the drawable folders

The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified class name of the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify multiple activities using <activity> tags.

Android application components


Android application components are the essential building blocks of an Android application. These components are loosely coupled by the application manifest file AndroidManifest.xml that describes each component of the application and how they interact.

There are following four main components that can be used within an Android application:

Components
Description
Activities
They they dictate the UI and handle the user interaction 
to the smartphone screen
Services
They handle background processing associated with an application.
Broadcast Receivers
They handle communication between Android OS and applications.
Content Providers
They handle data and database management issues.

Activities

An activity represents a single screen with a user interface. For example, an email application might have one activity that shows a list of new emails, another activity to compose an email, and another activity for reading emails. If an application has more than one activity, then one of them should be marked as the activity that is presented when the application is launched.
An activity is implemented as a subclass of Activity class as follows:
public class MainActivity extends Activity {

}

Services

A service is a component that runs in the background to perform long-running operations. For example, a service might play music in the background while the user is in a different application, or it might fetch data over the network without blocking user interaction with an activity.
A service is implemented as a subclass of Service class as follows:
public class MyService extends Service {

}

Android Architecture

Android operating system is a stack of software components which is roughly divided into five sections and four main layers as shown below in the android architecture diagram.


Linux kernel
At the bottom of the layers is Linux - Linux 2.6 with approximately 115 patches. This provides basic system functionality like process management, memory management, device management like camera, keypad, display etc. Also, the kernel handles all the things that Linux is really good at such as networking and a vast array of device drivers, which take the pain out of interfacing to peripheral hardware.

Libraries

On top of Linux kernel there is a set of libraries including open-source Web browser engine WebKit, well known library libc, SQLite database which is a useful repository for storage and sharing of application data, libraries to play and record audio and video, SSL libraries responsible for Internet security etc.

Distributed Transactions

What is a distributed transaction?  Transactions that span over multiple physical systems or computers over the network, are simply termed D...