Tuesday, 30 December 2014

Father of Java James Gosling Joins Google

Father of Java James Gosling Joins Google



 Gosling is formerly of Sun Microsystems, though he left the company after their acquisition by Oracle, the company currently suing Google over claims of stolen code within the Android source. He said it was apparent from early stages of the merger that Oracle wanted to pursue legal action against Google, but for this and other reasons he parted ways with the software company. That is not to say he hasn’t had a few words to say of Google in the past. Speaking about Android, Gosling once said the OS “has pretty much played out the way that we feared: there is enough fragmentation among Android handsets to significantly restrict the freedom of software developers.”


Read Full
http://www.beingjavaguys.com/p/core-java-tutorials.html
Read Full

How to override equals() in Java - Example

How to override equals() in Java - Example

In our previous discussions we came across a quick introduction to Java’s Collection API and Implementation classes for List, Set and Map interface. In this particular blog we will discuss about a very useful topic i.e. "Why to override equals() in Java" and "How to override equals in Java".

We all know it very well that all classes in Java are descendent of Object class, or we can say every class inherits the methods and properties of Object class by default. There are a number of methods in Object class and hence is "public boolean equals(){}".

The public boolean equals(){}, compares two objects and return true or false accordingly. If we don’t override equals in our own class than one present in Object class is called and it compares the object using ‘==’ operator and hence two objects are equal only if their references are same.

Assume we have an class Apple, lets compare its objects using equals() and examine the result.
  1. class Apple {  
  2.   
  3.  private int id;  
  4.  private String name;  
  5.   
  6.  public Apple() {  
  7.  }  
  8.   
  9.  public Apple(int id, String name) {  
  10.   this.id = id;  
  11.   this.name = name;  
  12.  }  
  13.   
  14.  public int getId() {  
  15.   return id;  
  16.  }  
  17.   
  18.  public void setId(int id) {  
  19.   this.id = id;  
  20.  }  
  21.   
  22.  public String getName() {  
  23.   return name;  
  24.  }  
  25.   
  26.  public void setName(String name) {  
  27.   this.name = name;  
  28.  }  
  29. }  


No lets see what happened when we call an equals() method from Object class itself without overriding it.
  1. public class Implementation {  
  2.  public static void main(String args[]) {  
  3.   Apple greenApple = new Apple(1, "Apple");  
  4.   Apple redApple = new Apple(1, "Apple");  
  5.   
  6.   // returns a false  
  7.   System.out.println(greenApple.equals(redApple));  
  8.  }  
  9. }  
In the example above we can see that even if two instance of Apple are having same data in them but the equals() method from Object class is assuming them to be non equal. The reason is the default implementation of equals() check for references and two objects are same only if their reference is same. And certainly you would not want this kind of behavior in your application, hence we override equals.
Note: Two String object with same values returns true on equals() even if having different references, the reason is String itself override equals() and implement the functionally so that the String content to compare not their references. Hence we can do it in our very own class.

We can override equals() in our own class and give that our own implementation to compare objects considering some contract. The meaning of contract here is that when overriding equals() we must took care of certain rules and those rules should not violate.

If an class “Apple” has three instances “greenApple” , “redApple” and “yellowApple” than according to contract

1) greenApple.equals(greenApple) must be true always. Reflexive

2) If greenApple.equals(redApple) is true than redApple.equals(greenApple) must be true. Symmetric

3) If greenApple.equals(redApple) is true and redApple.equals(yellowApple) is also true than greenApple.equals(yellowApple) must be true. Transitive

4) For any two refrences say “redApple” and “yellowApple” the equals() method must return true or false consistently unill and unless the property of class that is used is equals() is not modified. Consistent

5) For any non-null reference value greenApple, greenApple.equals(null) should return false. Null Test



Lets now look at our modified version of Apple with an override equals() method.
  1. class Apple {  
  2.   
  3.  private int id;  
  4.  private String name;  
  5.   
  6.  public Apple() {  
  7.  }  
  8.   
  9.  public Apple(int id, String name) {  
  10.   this.id = id;  
  11.   this.name = name;  
  12.  }  
  13.   
  14.  /* 
  15.   * One can use his own logic here unless the contract is being followed. 
  16.   */  
  17.  public boolean equals(Object o) {  
  18.   if (o instanceof Apple && ((Apple) o).getName() == name  
  19.     && ((Apple) o).getId() == id)  
  20.    return true;  
  21.   else  
  22.    return false;  
  23.  }  
  24.   
  25.  public int getId() {  
  26.   return id;  
  27.  }  
  28.   
  29.  public void setId(int id) {  
  30.   this.id = id;  
  31.  }  
  32.   
  33.  public String getName() {  
  34.   return name;  
  35.  }  
  36.   
  37.  public void setName(String name) {  
  38.   this.name = name;  
  39.  }  
  40. }  


Now let’s check if we did it right and does not violate the contract.
  1. public class Implementation {  
  2.  public static void main(String args[]) {  
  3.   Apple greenApple = new Apple(1, "Apple");  
  4.   Apple redApple = new Apple(1, "Apple");  
  5.   Apple yellowApple = new Apple(1, "Apple");  
  6.   
  7.   // Reflexive Test : true  
  8.   System.out.println("Reflexive Test : " + greenApple.equals(greenApple));  
  9.   
  10.   // Symmetric Test : true  
  11.   if (greenApple.equals(redApple)) {  
  12.    System.out.println("Symmetric Test : "  
  13.      + redApple.equals(greenApple));  
  14.   }  
  15.   
  16.   // Transitive Test : true  
  17.   if (greenApple.equals(redApple) && redApple.equals(yellowApple)) {  
  18.    System.out.println("Transitive Test : "  
  19.      + yellowApple.equals(greenApple));  
  20.   }  
  21.   
  22.   // Null Test : false  
  23.   if (greenApple != null) {  
  24.    System.out.println("Null Test : " + greenApple.equals(null));  
  25.   
  26.   }  
  27.  }  
  28. }  


And we are getting the expected result that passes the equals() override contract. Now the conclusion of the whole story is that:

1) The public boolean equals(){} is a method that resides in Object class and hence can be overridden in our own classes as well.

2) If one does not override it than the default behavior is being calles i.e. two objects are equal only if their references are same.

3) We can override equals() in our own class and can give own implementation to compare two objects until and unless we are not violating the equals() contract.

Big Big NOTE: If you override equals() in your own class than you must override hashCode() as well, unless it can violate hashCode() contract with equals() that results in Hash Based collections functionality and implementation.


In this particular blog we came across "why to override equals() in Java" and "How to override equals in Java". In our upcoming blog we will come across "how to override hashCode() in Java" and other tips and tricks about Java.








Thanks for reading !
Read Full

How to make a class Immutable in Java - Example & Explanation

How to make a class Immutable in Java - Example & Explanation

What is immutable class in Java? And How to make a class immutable in java? Are two very popular and hot topics as if today. In this particular blog we will look into these two in details and will try to understand benefits if immutable classes in context of Java Language.


What is Immutable class in Java ?

In Java an immutable class is a class whose object’s state can not be changes once created, or any modification on immutable object’s results in another immutable object. Even JDK itself contains a number of immutable classes like String, Float and other wrapper classes. To understand immutable class clearly we can take a simple example of String and StringBuffer classes, any modification on String object i.e. substring, concat ..etc results in a new immutable object while operations performed on StringBuffer class does not create a new object instead modifications are refleted on exiting object only.


How to make a class immutable in Java ?

Let us now discuss how to make a class immutable, there are a number of ways to get an immutable class. Even Java Documentation points out certain guidelines on the same, which we will follow here to get an immutable class.

1) Never provide a setter method for the class, setter methods are used to change the state of a class’s members. This is what we want to prevent here.

2) Make all fields private and final, this will make them non accesable outside the class and their values can not be changed because of being final.

3) Make the class final, so that the class can not be subclassed. This will prevent the class’s methods from overriden.

4) Special attention needs to be applied with mutable reference variables, with reference variables even final can not prevent their value to be changed. The simplest way to prevent reference variables’s vales is to not provide actual object and provide a copy of them.

5) Make the default constructor of the class private and provide instances with a factory method.

  1. package com.beingjavaguys.com;  
  2.   
  3. import java.util.Date;  
  4.   
  5. /** 
  6.  * @Author Nagesh Chauhan 
  7.  */  
  8. /* Making class final, prevents it's methods from overriden in subclasses */  
  9. public final class IAmImmutable {  
  10.   
  11.  private Integer id;  
  12.  private String name;  
  13.  private Date currentDate;  
  14.   
  15.  /* 
  16.   * private constructor ensured no unwanted object creation 
  17.   */  
  18.  private IAmImmutable(Integer id, String name, Date currentDate) {  
  19.   this.id = id;  
  20.   this.name = name;  
  21.   this.currentDate = currentDate;  
  22.  }  
  23.   
  24.  /* this hold the logic of object creation, only point to get an object */  
  25.  static IAmImmutable getInstance(Integer fld1, String fld2, Date fld3) {  
  26.   return new IAmImmutable(fld1, fld2, fld3);  
  27.  }  
  28.   
  29.  /* Integer is a immutable class, this can be served directly */  
  30.  public Integer getId() {  
  31.   return id;  
  32.  }  
  33.   
  34.  /* String is a immutable class, this can be served directly */  
  35.  public String getName() {  
  36.   return name;  
  37.  }  
  38.   
  39.  /* 
  40.   * Date class is mutable so we don't provide an direct object, instead we 
  41.   * provide a copy of it 
  42.   */  
  43.  public Date getCurrentDate() {  
  44.   return new Date(currentDate.getTime());  
  45.  }  
  46.   
  47. }  


  1. package com.beingjavaguys.com;  
  2.   
  3. import java.util.Date;  
  4.   
  5. public class ImmutableDemo {  
  6.   
  7.  /** 
  8.   * @Author Nagesh Chauhan 
  9.   */  
  10.  public static void main(String[] args) {  
  11.   /* 
  12.    * getting an instance of immutable class 
  13.    */  
  14.   IAmImmutable iAmImmutable = IAmImmutable.getInstance(2, "Andrew",  
  15.     new Date());  
  16.   System.out.println("Id: " + iAmImmutable.getId() + " Name: "  
  17.     + iAmImmutable.getName() + " Date:"  
  18.     + iAmImmutable.getCurrentDate());  
  19.   
  20.   /* 
  21.    * Try to modify object's states 
  22.    */  
  23.   // iAmImmutable.getId() = 5; not permitted  
  24.   // iAmImmutable.getName() = "Stuart" not permitted  
  25.   iAmImmutable.getCurrentDate().setDate(23);  
  26.   /* 
  27.    * Printing values again to test 
  28.    */  
  29.   System.out.println("Id: " + iAmImmutable.getId() + " Name: "  
  30.     + iAmImmutable.getName() + " Date:"  
  31.     + iAmImmutable.getCurrentDate());  
  32.  }  
  33.   
  34. }  


Benefits of making a class Immutable

1) Thread-safe hence can be used in concurrent environment without synchronization.
2) Immutable objcts can be used to boost memory, we can simply save them and serve again and again.


That’s all about immutable classes and objects in java, we cam across what is immutablity ? What are immutable classes in Java ?, How to create a class immutable in Java ? and benefits of immutable classes in Java. In upcoming blogs we will see more about Java and Other opensource technologies.








Thanks for reading !
Read Full

Create a Java Project in Maven and import it in Eclipse IDE

Create a Java Project in Maven and import it in Eclipse IDE

In this particular blog we will discuss ‘How to create a Java Project in Maven’, ‘Import maven java project in eclipse ’. and ‘create a jar from java maven project’.

Before we start lets make sure you have a working Maven Package and Java installation in your machine. To make sure if you have Java installed in your system supply following command:





To make sure you have a correctly configured Maven package supply following command.





Create Java project in Maven

To create a java project in maven open your command prompt and navigate to the folder where you want to create the project. Now supply following command.

C:\Users\nagesh.chauhan>cd maven-project
C:\Users\nagesh.chauhan\maven-project>mvn archetype:generate -DgroupId=com.beingjavaguys.java -DartifactId=SimpleJavaProject -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false


You will see a screen creating Maven a specified Java Project for you.



Make Maven – Jave project to work with Eclipse IDE

Here we are done with creating a Java Project in Maven, now lets make it working with eclipse IDE. Now to convert this maven-java project to work with Eclipse IDE navigate to the parent directory of your project and supply following command.

C:\Users\nagesh.chauhan>mvn eclipse:eclipse




Now import the converted project in your Eclipse IDE, the project structure in Eclipse will look like the image shown below:



Create a jar file from maven-java project in Eclipse

Now lets see how to create a jar from java-maven project, update your pom.xml a little bit to make it package your java application.

SimpleJavaProject\pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  2.  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.  <modelVersion>4.0.0</modelVersion>  
  4.  <groupId>com.beingjavaguys.java</groupId>  
  5.  <artifactId>SimpleJavaProject</artifactId>  
  6.  <packaging>jar</packaging>  
  7.  <version>1.0-SNAPSHOT</version>  
  8.  <name>SimpleJavaProject</name>  
  9.  <url>http://maven.apache.org</url>  
  10.  <dependencies>  
  11.   <dependency>  
  12.    <groupId>junit</groupId>  
  13.    <artifactId>junit</artifactId>  
  14.    <version>4.11</version>  
  15.    <scope>test</scope>  
  16.   </dependency>  
  17.  </dependencies>  
  18.   
  19.  <build>  
  20.   <plugins>  
  21.    <plugin>  
  22.     <groupId>org.apache.maven.plugins</groupId>  
  23.     <artifactId>maven-compiler-plugin</artifactId>  
  24.     <version>2.3.2</version>  
  25.     <configuration>  
  26.      <source>1.6</source>  
  27.      <target>1.6</target>  
  28.     </configuration>  
  29.    </plugin>  
  30.   </plugins>  
  31.  </build>  
  32.   
  33. </project>  

Now navigate to your project parent directory and supply following command.

C:\Users\nagesh.chauhan\maven-project\SimpleJavaProject>mvn install -Dmaven.test.skip=true

We have skipped all junit classes from packaging because those are not configured yet. You will get following output screen showing packaging process.


Now go to your Eclipse IDE and expand target folder, you will get your generated jar file there as shown in following figure.


Run the java project from eclipse IDE and you will see the output like :



In this particular blog we came across ‘How to create a Java Project in Maven’, ‘Import maven java project in eclipse ’. and ‘create a jar from java maven project’. In upcoming blogs we will see more about 'Maven', 'Spring', 'Java' and other opensource technologies.






Thanks for reading
Read Full

Java - Introduction and Overview of Language

Java - Introduction and Overview of Language

This is the very first part of our 'Core Java programming tutorials' series. Today we will cover a quick overview of Java History, its properties and a quick introduction to overall language structure.

Java is a High Level computer programming language that was initially invented by James Gosling. In June 1991 James introduces Java with an initial name ‘oak’, the purpose behind ‘Oak’ invention  was to implement an virtual machine with an language much familier with c/c++ but a simple way of understanding and implementation.





Quick History

The very first public implementation came in 1995 i.e. Java 1.0. The tagline behind the launch was ‘Write once and Run everywhere’. The release was platform independent and quit secure and configurable.

As the time passes Java got popular and it was assumed as the best programming language for web programming. In November 2006 Sun launches Java as open source project under GNU General Public License. Sun introduces Java 2 with a better and advanced security configurations and broken the launch in three main subsidiaries, J2SE, J2ME and J2EE.


Java Properties

1) Platform Independent

Java is most known for it Platform Independent nature, one can write a program in any environment and that can be run on a variety of Hardware and Platforms. Java is compiled and run within JDK(Java Development Kit). JDK includes JRE(Java Runtime Environment) in it. JRE is what makes java program run, this JRE can be different for different platforms but java code will run on each JRE..

2) Object Oriented

Java is fully object oriented or not, it is still a debate among programmers and communities. In java everything is an object except that of Primitive Types(int, char…) so this can be assumed that java is not a pure object oriented language, On the other hand Java supports Wrapper classes (Integer, Float …), so all primitive types can be represented as objects using wrapper classes, this is also true that java is an pure object oriented language.

3) Secure

Java is well known for its security features, java implements security API’s that makes is fully secured programming language. Java security API covers Platform security, Cryptography, Public key infrastructure, Authentication and Access Control that provides the programmers a secured framework to develop applications.

4) Simple

Java was intended to build a simple programming language with much similar that C/C++ syntax and functionality.  Java is a easy to learn and implement programming language with a clear understanding of its useful features. One can be a master in java with a quick understanding of its basic syntax and data flow across the applications.

5) Portable

Portability is again a big concern in Java popularity and wide usage. Being platform independent and architecture neutral makes java a efficient and idle language in portability aspects.

6) Robust

JVM is the root of Java, JVM is said to be the best virtual machine made till data. JVM enables a strong debugging and compilation capabilities that makes Java a error free and easy to detect errors mechanism implementation. Java is very strong in its robust part by providing a efficient mechanism against error detection at compile time and run time.

7) Architectural Neutral

Java compilation is a two step process, all java codes are converted to byte codes first. This makes java to run everywhere and architecturally neutral programming language.

8) Multithreaded

Java supports a fully integrated multithreaded environment, this feature makes the developers to utilize bandwidth and reduce idle cpu time. Multithreading makes it easy to divide the task in multiple parts to make the application more productive and safe to develop.

9) Distributed

Java support distribution of its code across the internet, its platform independent nature and byte code make it easy to distribute easily.

10) Dynamic

Java is being called more dynamic than c/c++, the reason behind its strong dynamic support is the capabilities of run time implementation and easy to adopt dynamic features.


Development Environment

A java program can be written on a simple text editor with a .java file extension. A .class file is generated after compilation that is nothing but a byte code file. This .class file is than run on JVM to see the expected output.

Being a very popular and widely used programming language Java enables a wide range of development capabilities. To start programming in java one need to install a JDK package on the machine and that’s it, JDK comes with a Java compiler, debugger and JVM to run and deploy java applications on.

Till date a number of Development IDE’s are available for java, Eclipse and Netbeans are most popular and widely used IDE’s for Java as of today.


Programming Syntax of Java

Java is based on c/c++ languages as in syntax perspective, Java’s syntax is easy and easy to learn. In java everything is written inside classes and that methods are declared to complete the tasks. In java everything is based on objects. More detailed overview of Java syntax will be covered in Simple Hello World in java section.


Install Java and Environment Settings

Start programming with java is simple, just install a JDK from a variety of providers and set JAVA_HOME path. More details can be get from Install Java and Set Environment section.


In this particular blog we came across a quick introduction of Java programming language and its properties. In upcoming tutorials we will cover Set Java Development environment , Start programming in Java and step by step introduction to all basic concepts of Java programming language.










Thanks for reading !
Read Full

Jsp and Servlet Tutorials - Request-Response Model (Part 1 of 8)

Jsp and Servlet Tutorials - Request-Response Model (Part 1 of 8)

Today we are living in an era where java is being used at its best, we have very efficient frameworks and tools to make web development easy and stable. To make software development more useful and productive its important to implement industry best practices and clean coding implementations. Good naming conventions and easy to implement algorithms is not enough to make smart development done. 
No matters how improved frameworks and techniques we are using in our development process the key feature to write smart code is always stick to basics.

There is no doubt that a lot of effort and experience is behind today's java web frameworks and these stuffs has been made web development very flexible and advanced, but we must not forget about those old but gold concepts so called jsp and servlets. Whenever there is something related to web development in java the first thing that comes in our mind is servlets and jsp's. So its never wrong to say that a good java developer must have a very good command on basics of servlet and jsp's.     

In this series of jsp-servlet tutorials we are going to talk about servlet ans jsp's to make you guys understand the basics of what web development is all about. In today's discussion lets starts with an introductory part of Servlets. By the end of this tutorial we will be able to understand things like : What is a Request ?, What is a Response and What is Request-Response model exactly.

Although this series of jsp-servlet tutorials is written for extremely start level readers, but we assumes that you guys have a little knowledge of oops concepts and java language in general. First of all lets starts with a quick and brief introduction to data flow model of web to better understand the things that are exactly happening behind the screen.

Request-response model

jsp-servlet-tutorials

Whenever a software guy enters in web development world the first thing that he comes to know is, client and server, client makes an request and server sends a response back to client. So let's first discuss how basically communication takes place in web world and what exactly the terms client and server means.

Client: A client in basically something(web browser) or someone(user) who requests some resource from server.

Server: A server is a combination of a hardware machines and a number of softwares running on that machine. The one and only duty of server is to serve resources that are being requested by the client.

Servers itself are capable of serving static resources only. To serve a dynamic response servers needs some extra technologies like servlets running on them. 
How servlets helps server in serving dynamic contents, we will come to know about it in later part of this blog.
Now to get client and server in contact and make communication possible we needs some set of rules so called http(Hyper text transfer protocol). In web there are a number of protocols other than http that does the communication work done, but almost in 99% of applications the requests being made are http requests.

Http: Http can be assumed as a common interface of interaction that both client and server understands.

Request/Response circle
 
Web flow starts from a request being made by user's browser, the request is made as http request so that server can understand it. Based on request the server searches for an appropriate resource and sends it back to client in form of http response.

Http Request: A http request basically have three major components.
1 - HTTP method, there are 7 methods defined in java servlets but most of the time you will see either a get or post method. We will get to know about these methods and their usage in later part of this blog.
2 - The requesed page URL, the page to access like www.google.com.
3 - Parameters, parameters(as id, name, email.. etc.) are being send as part of request on which the response is being generated.

Http Response: A http request basically have three major components.
1 - A status code, this code tells the browser wheather the request is successfull or not.
2 - Content type, it tells the browser about the type of content that response web page contains in it (text, picture, html...etc).
3 - The content, the important and last information that is the served resource that the user was requested.

Till now we are much famelier with the request-response cycle and client-server model over the web. Now the next things that would be coming in your mind is "Where does the Servlet comes into the picture". As we said before that the server can serve static pages or response by itself. In case we need to serve some dynamic pages the served must have something that provides dynamic contents to serve. And this is what servlets does exactly.
Servlets are nothing but helper applications that helps the server to response back dynamic pages. How servlets prepares dynamic response and what exactly happened in the process we will come to know about this thing in a moment, be cool.

A static resource is a page whose contents are static in nature as a simple text file, on the other hand dynamic pages are being prepared according to user's request parameters.

For example lets assume a user requests a page having some text information written on some topic. This page content is never going to change and the same page is sended back to every user request.
But if a user requests something like profile information of his own account this time server needs to create a page of that user's information based on id or username the user provided. This page is going to contain different profile information for different users. These username, email are called parameters and the response id being generated dynamically based on user's request parameter. These are called dynamic pages.

The existence of servlets came into picture because, most of the time client needs dynamic contents and not static contents always. So in java when we need some dynamic content rather that static content we go for a servlet. 

In this part of jsp-servlet tutorial series we came across a basic introduction of Servlet and come to know about request, response and request-response model in web development. In upcoming blogs of this tutorial series we will come to know about Servlet Architecture and other topics related to Servlet ans Jsp's.









Thanks for reading !
Read Full