Showing posts with label Java Tips. Show all posts
Showing posts with label Java Tips. Show all posts

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.

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. 

Monday, December 30, 2013

Iterate Over a Map in Java

Most of the initial developers easily write iteration code  to iterate List and Set using for-each concept. Can we write the same to iterate over a map in java. The answer is yes.

Iterate Over a map.
This is most recommended and simple method to iterate map unlike getting the key set and get each value  from the map by  iterate the key set.

Map<Integer, Integer> map = new HashMap<Integer, Integer>();

for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println("Key::"+ entry.getKey()+ "::Value::" + entry.getValue());

}

Wednesday, December 18, 2013

How to make a java class immutable

Most of us know about mutable and  immutable concept and advantages of immutable class in java.
But many of those think we can not make our own java class as immutable  and it is by pre defined. It is not true, we can make our own classes as immutable.
Any way as we discussing immutability concept I want to discuss the advantages of  immutability concept here.

Benefits 
Immutable classes
  1. Are automatically thread-safe and have no synchronization issues
  2. Do not need a copy constructor
  3. Do not need an implementation of clone
  4. Allow hashcode to use lazy initialization, and to cache its return value
  5. Do not need to be copied defensively when used as a field
  6. Make good Map keys  and set elements (these objects must not change state while in the collection)
Making Class as Immutable 
Java Documentation as itself some notes on this concept you can find that here  

1) Don’t provide “setter” methods  
Setter methods are meant to change the state of object and this is what we want to prevent here.
2) Make all fields final and private 
Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them
3) Declare class as final
 Don’t allow subclasses to override methods
4) Attention with mutable instance variables in class
Always remember that you can have either mutable  or immutable instance variables, identify them and return new objects with copied content for all mutable objects. Immutable variables can be returned safely without extra effort.

Example :

Tuesday, December 17, 2013

Abstract Factory Pattern

Abstract Factory patterns works around a super-factory which creates other factories. This factory is also called as Factory of factories. This type of java design pattern comes under creational pattern as this pattern provides one of the best ways to create an object. 
In Abstract Factory pattern an interface is responsible for creating a factory of related objects, without explicitly specifying their classes. Each generated factory can give the objects as per the Factory pattern.

Implementation of Abstract Factory Pattern

We're going to create a Shape and Color interfaces and concrete classes implementing these interfaces. We creates an abstract factory class AbstractFactory as next step. Factory classesShapeFactory and ColorFactory are defined where each factory extends AbstractFactory. A factory creator/generator class FactoryProducer is created.
AbstractFactoryPatternDemo, our demo class uses FactoryProducer to get a AbstractFactory object. It will pass information (CIRCLE / RECTANGLE / SQUARE for Shape) to AbstractFactory to get the type of object it needs. It also passes information (RED / GREEN / BLUE for Color) to AbstractFactory to get the type of object it needs.

Factory Pattern

Factory pattern is one of most used design pattern in Java. This type of java design pattern comes under creational pattern as this pattern provides one of the best ways to create an object.
In Factory pattern, we create object without exposing the creation logic to the client and refer to newly created object using a common interface.

Implementation of Factory Pattern

We're going to create a Shape interface and concrete classes implementing the Shape interface. A factory class ShapeFactory is defined as a next step.
FactoryPatternDemo, our demo class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE / RECTANGLE / SQUARE) to ShapeFactory to get the type of object it needs.


Friday, December 13, 2013

Proxy Pattern

In Proxy pattern, a class represents functionality of another class. This type of design pattern comes under structural pattern.
In Proxy pattern, we create object having original object to interface its functionality to outer world.
Implementation
We're going to create a Person interface and concrete classes implementing the Person interface.ProxyPerson is a a proxy class to reduce memory footprint of RealPerson object loading.
ProxyPatternDemo, our demo class will use ProxyPerson to get a Person object to load and display  Name as it needs.

Thursday, December 12, 2013

static keyword in java

The static keyword is used in java mainly for memory management. We may apply static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class

Tuesday, December 10, 2013

Job scheduling with Quartz

 Quartz can be used to create simple or complex schedules for executing tens, hundreds, or even tens-of-thousands of jobs.

Job Scheduling

Jobs are scheduled to run when a given Trigger occurs. Triggers can be created with nearly any combination of the following directives:

Modifiers In Java

It is possible to modify classes, methods, etc., by using modifiers. There are two categories of modifiers:

  • Access Control Modifiers : default, public, protected, private
  • Non Access Modifiers : static, final, abstract, synchronized

Identifiers in Java

Identifiers are the names of variables, methods, classes, packages and interfaces. Unlike literals they are not the things themselves, just ways of referring to them.
In the HelloWorld program, HelloWorld, String, args, main and println are identifiers.

Monday, December 09, 2013

Difference between length and length() in Java

length - This is a instance variable of array in java. It returns the length of an array, number of elements stored in an array.

length() -  This is a method in java. It is a static method of String class. It returns the length of a string object.

Friday, December 06, 2013

Flyweight Design Pattern

Flyweight pattern is primarily used to reduce the number of objects created, to decrease memory footprint and increase performance. This type of design pattern comes under structural pattern as this pattern provides ways to decrease objects count thus improving application required objects structure.
Flyweight pattern try to reuse already existing similar kind objects by storing them and creates new object when no matching object is found. We'll demonstrate this pattern by drawing 10 Rectangle  of different locations but we'll creating only 2 objects. Only 2 types are available so type property is used to check already existing Rectangle objects.

Thursday, December 05, 2013

What's new in Java 7

I have been reading  about Java 1.7. There are articles about what's new,I have read them and compromised to write the language changes with examples.
So the normal developer can understand the changes easily by examples.Here I am mainly focusing on language  changes  I have taken these language changes from wikipedia https://en.wikipedia.org/wiki/Java_version_history#Java_SE_7_.28July_28.2C_2011.29. You can see all other changes here.

Language Changes 
  • Strings in switch
  • Automatic resource management in try-statement 
  • Improved type inference for generic instance creation, aka the diamond operator <>
  • Language  Support for Collections.
  • Binary integer literals
  • Allowing underscores in numeric literals
  • Catching multiple exception types and re throwing exceptions with improved type checking

There is a list of other features available on the OpenJDK 7 features page.

Creating JSON data in Java


Download JAR file json-rpc-1.0.jar (75 kb)
import org.json.JSONObject;

JSONObject json = new JSONObject();
json.put("city", "Mumbai");
json.put("country", "India");

String output = json.toString();

Java Application without a main method

Can you write a java program which does not have main but it should be executable with out any errors and exception?

Think for a while before read this post....


Yes, You can write a runnable java program which does not have main method at all. This can be done using the static block of the class.

Wednesday, December 04, 2013

Types of Inner Classes in Java

Static Inner Classes:

Syntax for static inner class is as follows:
<access-specifier> class OuterClassName {
    public static class <StaticInnerClassName> {
        . . .
    }
    . . .
}

Tha 𝗔𝗣𝗜 Design 𝗛𝗮𝗻𝗱𝗯𝗼𝗼𝗸

 Here is the 𝟮𝟬𝟮𝟲 𝗔𝗣𝗜 𝗛𝗮𝗻𝗱𝗯𝗼𝗼𝗸 broken down by architecture: 𝟭. 𝗧𝗵𝗲 "𝗥𝗲𝗾𝘂𝗲𝘀𝘁-𝗥𝗲𝘀𝗽𝗼𝗻𝘀𝗲" 𝗧𝗿𝗶𝗼: ...