Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Friday, May 02, 2014

Java 8 New Features: Lambda Expressions Part 1

Java is an object-oriented programming language which we all know very well but with Java 8 (released on 18th March, 2014) it goes functional. What does that means? Functional Programming was there way before Java came out but still Java adopted the object-oriented paradigm. Why? Well one simple answer to this is, its popular back then, Why Java wants to adopt Functional Programming now? Well again, simple answer to this question is Modern Hardware now runs more than one CPU Core and as a Programmer we should put them to good use rather then using a single core. Concurrent Programming provides us coarse-grained parallelization that helps Programmers to write code that can put all Cores to good use.

Still accessing a large collection of data is a sequential process well we can make parallel using concurrent programming but thats not an easy task to do at all and even we can't guarantee the performance gains, if any or our data is not in a fragile state or how to design such things that we can reuse it in other projects as well.

If every major Java release since Java 5 adds something to the Java Concurrency API, same way after Java 5, Collections API now makes it easy for accessing the collection of data either sequential or parallel.

Secondly, While doing Event-Driven Programming many of our object instantiation are done via ad-hoc Anonymous Inner Classes and if the code is big the amount of class files it generates with '$' sign is quite a mess. In case, a project deadline is near and there is still a lot of code to write, many developer(s) self question including me "Why the hell we have to write so much boilerplate code and we still achieve very less as compared to other programming languages which runs on the Java Virtual Machine (JVM) like Scala, Groovy etc.. and other which don't run on the JVM but still very less boilerplate code like Python etc.."

As discussed, Java is an object-oriented programming language with exception to having primitives at language level we can either pass an Abstract Data Type (ADT) or Primitives as parameters.
Lets start with a question that we should ask our self before we know whats really changed in Java 8.

Q What are interfaces in Java?

A Very simple answer to this basic question can be  "An interface is 100% Abstract Classes that can only declare abstract methods or may have constant(s)."

If you have plans to move to Java 8 or preparing for an interview etc.., then think once Again?

Interfaces are there since the beginning and even a person who is introduced to Java Programming Language was told the same thing. With Java 8, which is the biggest release after Java 5 has changed things (I won't say a little, you will see it in a bit) so its better to be aware of, what interface were before Java 8 and what they have become Java 8 onward.

So whats really changed in Java 8 with respect to interface?

A new keyword added to the language 'default',
Interface can have default, static and abstract methods,
abstract methods cannot have body but default, static methods have body,
If an interface contains only one abstract method, other than overriding method(s) of Object class as abstract are considered functional interface,
There is a new annotation added in the language, @FunctionalInterface, it's optional, i.e., you can either mark an interface with this annotation or you can leave it, as far as it comply to the definition of @FunctionalInterface, Java treats it as functional interface, whereas, if you mark an interface with the annotation and later on add another abstract method, you will get compilation error.

Things covered so far...

Till Java 7,

lots of boilerplate code,
sequential access to data inside a collection,
Not much of parallel computing (except concurrency API, provides coarse-grained parallelization),
Event-driven Programming is a mess,
Strong typing,
Either we can pass a primitive or ADT as a parameter

Java 8 onward,

concise syntax,
sequential/parallel access to data inside a collection - out-of-the-box,
fine-grained parallelization,
No more Anonymous classes while doing Event-driven programming
type inference,
Now apart from passing primitives or ADT as a parameter, we can do pass lambdas or "code-as-data" as parameters.

Lambda Expressions

Lets now start with an exercise where we can see how things are done till Java 7 and how its improved in terms of syntax, performance etc..

Saturday, June 01, 2013

Groovy Basics: Hello World Example

In Dynamic Language, always remember one Rule of Thumb.

* When you're unsure what type you want your Object, always use the 'dynamically typed' keyword.

In Groovy, def simply means 'dynamically typed'.

As the Groovy Site says a dynamic language for the VM you must always remember Groovy Syntax feels Dynamic whereas once it's compiled it's the same Class File that Java Compiler (javac) Generates as Groovy runs on the VM and VM doesn't have a support for dynamic language. You will find Groovy Syntax Much Clear and More Readable as you write less code.

A Groovy File can either Contain Scripts, Class Definition or both. I usually don't prefer mixing Scripts and Class Definitions in a same file. I will come to this later.

You can check one-liner on the Groovy Shell instead of writing a Script file.

On Console/Prompt Type:

groovysh // It will open a Groovy Shell.

groovy:000> println "Hello, World."
Hello, World.
===> null
groovy:000>

OR Simply,

groovy:000> "Hello, World."
===> Hello, World.
groovy:000>

You will see the shell doesn't exit after the execution instead it's asking for your input again. This is called REPL - Read Evaluate Print Loop. You can type exit, quit, \q or \x to exit the shell.

You can also use the groovy command instead of going into the shell.

groovy -e "println 'Hello, World.'"

Here, -e <script> specify a command line script.

You can write that line in a new file and save it as HelloWorldScript.groovy try to run it,

groovy HelloWorldScript.groovy

OR

groovy HelloWorldScript

A Groovy File can have any of the below mentioned extension. You can run the groovy command without extension in which case groovy will look for all the files in your CLASSPATH with one of the below mentioned extention and .class extention as well once it's found, it will execute that or will throw an error in case file with the same name doesn't exist in the CLASSPATH.

.groovy
.gvy
.gy
.gsh

The groovy command runs your code without generating .class files. If you use groovyc compiler to explicitly compile your files first and then run them using the groovy command. You can do it. What if you made changes to your groovy source file and forgot to compile them? What will happen? No Worries! The groovy command is smart enough to load and run the right files for you that means suppose you make any changes to your source file but forgot to generate the .class file using the groovyc command (groovyc). the groovy command will ignore the .class file present in the path and will run the source file instead.

Now, Lets write a first HelloWorld.groovy program using the class definition,

You might notice that there are no import statements, parentheses, package prefix or a semi-colon.
Point to Remember: Like Java imports java.lang.* package by default Groovy imports the following packages by default. groovy.lang.*, groovy.util.*, java.lang.*, java.util.*, java.net.*, java.io.* and classes java.math.BigInteger and java.math.BigDecimal.

Another Point to remember here that Script files don't have a main method but they are still executed, As Each Script file turned into a Java class with the same name as filename that extends the groovy.lang.Script which contains the main method so the runtime can execute it.

As, I discussed earlier not to mix Scripts and Class Definitions in a Single file. Here is why,

Let me explain if the above error is still not clear. What Groovy does here is when it sees a Script inside a source file, it tries to create a class with the same name as source filename which in this case is HelloWorld. Their is a class definition inside the source file which has a same name i.e., HelloWorld for which a class will be created but when it comes to the Script it will fail to create as the class HelloWorld already exist.

How to fix?

You can fix this either by changing the Source Filename or Change the Class Name to make it run. Always try not to mix the Class Definition and Script in a same file.

As, I mentioned above that you need a Java VM to run the Groovy code you can run them directly using the Java Command. All you require is a single Groovy Jar in your classpath.

Compile and Run

First you have to generate a .class file using the Groovy Compiler.

Window Users:

C:\GROOVY-DEMOS>groovyc HelloWorld.groovy

Linux Users:

$ groovyc HelloWorld.groovy

To Run,

Window Users:

C:\GROOVY-DEMOS>java -classpath %CLASSPATH%;%GROOVY_HOME%\embeddable\groovy-all-2.1.3.jar HelloWorld

Linux Users:

$ java -classpath %CLASSPATH%:%GROOVY_HOME%/embeddable/groovy-all-2.1.3.jar HelloWorld


Note: Never put the groovy-all-<VERSION>.jar in your classpath, it will effect the groovysh command. If you get an error while running the groovysh command make sure you don't have groovy-all-<VERSION>.jar in your classpath.

If you are looking for editors/IDE with Groovy Support try Sublime Text 2 or IntelliJ Idea.

Hope this Helps!
Please leave your comments

Running Java And Groovy on Windows And Linux

Groovy, Another Language that runs on Java Virtual Machine. It supports both Static and Dynamic Typing. If you haven't heard about this language till now. No Problems!

As, Groovy runs on VM so you must install Java first. Groovy doesn't require you to be a Java Programmer but some hands-on will help you learn it fast. Those who already have installed Java must set the JAVA_HOME Environment Variable. Here is how you do.

On Windows Machine:

Right-Click My Computer -> Properties -> In Windows XP (Advanced) | In Windows 7 (Advanced System Settings) ->  Environment Variable -> New

Here You will see Two Panes. If you select the New on the First One it will set User-Specific Setting i.e., Only the Currently Logged In User can use Java and Groovy.

If you Choose the New from the System Variables, It will be available to all the existing users as well all users that you create later. Choose what you prefer.

Note: System Variables already Contains PATH Key/value pair. Never remove the existing value instead append to it or you end you with an unstable machine. If you are unsure always create the NEW PATH Key/value in the First Pane that way you are sure that your System Settings remains untouched.

Create a New Variable anywhere you prefer.

Variable Name:  JAVA_HOME
Variable Value:  PATH\TO\JAVA\FOLDER\WITHOUT\SEMI-COLON\AT\THE\END

For Example: I have installed Java in C:\jdk1.6

Variable Name:  JAVA_HOME
Variable Value:  c:\jdk1.6 \\ Never put a Semi-Colon at the end.

Once Done Press OK.

Now Create one more Environment Variable. Again by Clicking New any place you prefer:

Variable Name:  CLASSPATH
Variable Value:  .;%JAVA_HOME%\lib;

Note: You must put a Semi-Colon at the End. Press OK. The Reason to put a Semi-Colon here is a good practice as you might in near future append a new library to your CLASSPATH just to separate one from another you put a Windows PATH Separator.

Again, If you are unsure which pane to choose for this one always prefer the first one and add the below Key instead of updating your existing System Variable PATH key in global/system settings that way it will remain untouched.

Variable Name:  PATH
Variable Value:  %JAVA_HOME%\bin;

Note: Never Override a Key's Value always append to it.

On Linux Machine:

There is a ~/.bash_profile that is a start-up script which generally runs once. People find it common place to add environment variables such as PATH, JAVA_HOME, create aliases, etc.

Please remember the file ~/.bashrc is similar but ~/.bash_profile runs for Bash Shell whereas, ~/.bashrc runs for every Bash Shell.

Similarly, You can setup for all users i.e., Global Settings to do so you need to add the following entries mentioned below in /etc/profile.

Fire your Terminal or Console: I'm using ~/.bash_profile you can choose what you prefer.

Type: $ vi ~/.bash_profile

export JAVA_HOME=/PATH//TO/JAVA/FOLDER/WITHOUT/COLON/AT/THE/END
export PATH=$PATH:$JAVA_HOME/bin
export CLASSPATH=.:$JAVA_HOME/lib

You have to logout and login back to see the new changes in effect. Alternatively you can type the below command to see the changes immediately.

$ source ~/.bash_profile

OR

$ . ~/.bash_profile

Always Remember always place Binary files i.e., files that are executable in the PATH variable irrespective you are working on Windows or Linux OS. CLASSPATH is for libraries.

Now it's time to download Groovy. Please head over to their Site to download it and all we need is to extract it and add/update some Environment Variables. The same way we did for Java.

Groovy Site: http://groovy.codehaus.org/

You need to Add a New Environment Variable.

Variable Name:  GROOVY_HOME
Variable Value:  PATH//TO/GROOVY/FOLDER/(IN WINDOWS WITHOUT SEMI-COLON OR IN LINUX WITHOUT COLON)/AT/THE/END

Append to PATH Variable,

Windows Users: %GROOVY_HOME%\bin;
Linux Users: $GROOVY_HOME/bin

Make sure that there is a Semi-Colon (Windows), Colon (Linux Users) at the end before you append these values to it. You can confirm this using the echo command which works on both windows and Linux.

Windows Users: echo %PATH%
Linux Users: echo $PATH

If it's not present you must provide it otherwise it will not work. For Example: Instead of doing $GROOVY_HOME/bin
you do :$GROOVY_HOME/bin.

Remember Colon is a Linux Path Separator whereas, Semi-Colon is Windows.

Now As all the installations are done now we head over to test if everything is working fine or not.

Windows Users, Please open Command Prompt close any if already Opened. Linux Users either use the source command to make the settings available to existing Console or login again.

Now, Before we proceed any further we must check our installation.

At prompt or Terminal or Console,

Type:

javac -version // To See if the Java Compiler is Working or not.
java -version // To See if the java execution environment is ready to run anything you throw at it.

groovyc -version // To See if the Groovy Compiler is Working or not.
groovy -version // To See if the Groovy execution environment is ready to run anything you throw at it.

groovysh -version // It's something that only Groovy had not Java. It can execute commands you throw at it. It's a REPL - Read Evaluate Print Loop.

groovyConsole // It's a GUI Version.

I hope you don't ran into any problem. Next Article is coming up on Groovy.

Hope this Helps!
Please leave your comments.

Thursday, April 18, 2013

Howto Use Java Comparator and Comparable by Example

In Java, there are some built-in methods that provides basic sorting of Primitive types array or Wrapper classes but what If we wanted to sort a custom class that we have written for use in one of our Projects? Well the answer is to write a sorting algorithm of our own and use it wherever it's required.

In Java, there are two interfaces that can help us achieve our goal. The reason the language provides two interfaces instead of one giving code developers enough flexibility to choose the one that they find suitable to their requirement.

The first Interface which I prefer to call is the Simple Handy Internal Sorter is available in java.lang.Comparable  . The Second Interface which I prefer to call is the Highly Flexible External Sorter is available in java.util.Comparator.

The former one is Simple and Internal as it needs to be implemented on the class itself and it's simple as it allows the code developers to write only single sorting implementation. The latter one is Highly Flexible and External that means it allows the code developer the flexibility to write as many as required sorting implementation for their custom class as it's declaration and implementation is in a separate class.

Let's start with the Below Example where Custom Class CarMake have both Simple Handy Internal Sorter and Highly Flexible External Sorter.

CarMake.java

As you can see below the Simple Handy Internal Sorter is already implemented on the Custom Class.


CarMakeComparatorAsc.java

Custom Class CarMake's Highly Flexible External Sorter Implementation.




CarMakeComparatorDesc.java

Custom Class CarMake's Highly Flexible External Sorter Implementation.


And, Finally the only thing required is to test both the implementation using a CarMakeSortTest.java.

CarMakeSortTest.java


I Hope this post helps you learn basics of Custom Class Sorting. Please do write your feedback...

You can download the complete code from Github

Tuesday, April 03, 2012

Favor Composition to Inheritance

As we all know Java is an Object-Oriented Programming Language. OOP was developed in first place to increase code reuse and maintainability.

The Myth

Programmers introduced to OOP Language(s) have a mindset that code reuse can be achieved only by Inheritance (extends) in Java. But are not aware of the alternatives even if they came across them.

For Example:

List<Car> carRef = new ArrayList<Car>();  //Generic List of Car References

Q.  Why Inheritance is considered bad?

A.  Experienced Programmers are aware of the fact and even the Design Patterns states the same using Inheritance across boundaries are considered bad as author of that library may change the internal implementation details which might break our abstraction that depends on it blowing up the whole stack.


Better Alternative - Prefer Composition to Inheritance




-------------------------
I will soon add more on this. Please do post your comments if your thinking differs from me. I will try to incorporate you questions/suggestion here so everyone has a better idea on this concept.


Hope this Helps! Please write your comments it will help me improve.



Monday, February 14, 2011

Java in Practice: Coding and UML Aggregation v/s Composition



Aggregation [ 'HAS-A' Relationship ]

class StereoSystem {
    private boolean state ;
    StereoSystem() {}
    StereoSystem(boolean state) {
        this.state = state ;
        System.out.println("Stereo System State: " + (state == true ? "On!" : "Off!")) ;
    }
}

class Car {
    private StereoSystem s ;
    Car() {}
    Car(String name, StereoSystem s) {
        this.s = s ;
    }
    public static void main(String[] args) {
        StereoSystem ss = new StereoSystem(true) ;  // true(System is ON.) or false (System is OFF)
        Car c = new Car("BMW", ss) ;
    }
}


In UML Aggregation is Expressed as


Composition [ 'Contains' Relationship ]

import java.util.Date ;

class Piston {
    private Date pistonDate ;
    Piston() {
        pistonDate = new Date() ;
        System.out.println("Manufactured Date :: " + pistonDate) ;
    }
}

class Engine {
    private Piston piston ;
    Engine() {
        piston = new Piston() ;
    }
    public static void main(String[] args) {
        Engine engine = new Engine() ;
    }
}

In UML Composition is Expressed as 






I originally posted this here: http://www.coderanch.com/t/443002/java/java/Java-Coding-UML-Aggregation-Composition


Hope this Helps! Please write your comments it will help me improve.