Saturday, May 24, 2014

Boxing and Unboxing In Java

Before attempting to understand the concept of Boxing and UnBoxing in java, one needs to have an idea of the basic classification of datatypes in the language. The data types in java are broadly classified into two major types: 

1) Primitive types
2) Reference types/ object types

Primitive types include byte, short, int, long, float, double, char, boolean and String (String is not completely a primitive type but also reference type). Clear explanation of primitive types is given at this link.
Rest all the other types in java are classified as Reference types or objects types.

Some of the differences between primitive and reference types include:

  • It is not possible to create a primitive datatype of our own but it is possible in case of reference types or objects.
  • The variables of primitive types have a memory size that is fixed by the language specification etc. For example, a variable of type int is allocated a memory of 4 bytes. In case of reference types the size of object varies based on its class specifications.
  • The reference types are either core library defined or user defined. The value assigned to the variable of reference type will either be a reference to an object or a NULL value. The default values of primitive type variables can be zero but not NULL. A NULL value means that the variable is not referring to any current instance in the memory.

Boxing It is the process of placing a primitive datatype within an object so that it can be treated as an object.

What is the need of primitive datatype to be treated as an object ?
In Java, certain types are allocated on stack and others on heap (usually primitives types on stack and reference types on heap). The heap allocation is done during the run time. Sometimes there is a need to bring the stack allocated instances on to heap. In such cases, primitive types need to be converted into reference types. One of the examples for such kind of scenarios would be method invocations. Method invocations are done during run time and they require objects to perform this action, but if a primitive type is present then it must be converted into an object type. This conversion is known as Boxing.

Similarly in the statements involving increment or decrement operations, objects need to be converted into primitive types. This is because increment and decrement operations cannot be directly performed on objects. This kind of conversion is known as UnBoxing.

 
Many data structures in Java operate on objects (Example: Collections), so we cannot use primitive types with those data structures. To handle these situations java provides type wrappers which provide classes that encapsulate primitive types with in an object.

In the above figure, int is a primitive data type which is being wrapped in a Integer class so as to use it as a reference type. 

Simple examples of boxing and Unboxing

  1) Integer object_type = 3 ;    // boxing
  2) int primitive_value       =  object_type;    //unboxing
  3) List<Integer> integer_list = new ArrayList<>();

                    for(int i = 1; i < integer_list .size(); i++){
                    integer_list .add(Integer.valueOf(i));
                    }

In the above example the Collection ArrayList<> accepts only objects hence boxing is done by using the Integer wrapper class.

Monday, April 21, 2014

Concurrency, Parallelism, Multicore

There were considerate amount of updates to Java language, JDK & JVM in the recent release of 1.8. It was said that finally Java is addressing multi-core hugely in Java 8. So I got excited about multicore, concurrency, parallelism etc. Here I'm not going to talk about evolution of multicore or Moore's Law blah blah blah. I'm going to talk about what I learnt about concurrency & parallelism, especially in Java (may be about Go in future).

As Rob Pike said Concurrency is not Parallelism. Concurrency is about dealing with lot of things at ones whereas Parallelism is about doing lot of things at ones. Concurrency is to structure things so that we may use parallelism to do a better job. Parallelism is not the goal of Concurrency. Concurrency's goal is good structure. Parallelism can come from better concurrent expression of the problem. The parallelism performance by an application achieved varies with different hardware configurations, depending on number of cores, number of threads per core etc. But if we have a proper concurrent design we can get Parallelism whenever possible.

There are different types of approaches to concurrency, to name a few:

1) Memory Sharing - Java
2) Message Passing - Erlang, Go

There are different debates about different types of approaches. As of now there is no barometer to validate which one is better. We may measure & compare performances of different approaches though. Depending on the approach different languages uses different terminology, the rest of my discussion is more related to Java world. Though the final goal of any approach, given any programming language, is to take advantage of all the cores available on the processor to increase the performance of applications.

The number of cores on the processors are increasing year after year. Rather than waiting for the CPU clock speeds to increase, software applications should be fine tuned in order to use all the cores on the processor. Concurrency should be addressed at the design stage of the application. Each core usually has one thread (more than one in some cases like HyperThreading). The ultimate goal is to keep all the threads (in different cores) running at any given time. 

There are lot of issues that need to be dealt while creating multi-threaded applications like thread creation, thread life cycle management, scheduling etc. Luckily many programming languages provide us with necessary language features, frameworks in dealing with them. Multi-threaded applications should be designed very carefully because when different threads try to communicate it could lead to issues like dead locks, starvation etc. Each approach addresses them in respective ways. From the next post I will dive deep into concurrency in Java. How Java & JDK is evolved overtime to address concurrency, starting from Java 1.0 till Java 8.

Sunday, April 6, 2014

Configuring Java Environment JRE/ JDK in Eclipse

Devoid of what version of JDK you install on your machine, Eclipse comes with a JDK and it uses it unless we configure it manually to use a different one. We can simply direct Eclipse by specifying -vm option in the  eclipse.ini file which you can find in the directory where you unzip the downloaded eclipse zip file. There are different ways of specifying the -vm option depending on the operating systemwhich are described in detail here. The following worked for me on windows. Specify the option at the top of the file.

-vm
C:/Program Files (x86)/Java/jdk1.7.0_51/jre/bin/client/jvm.dll

Alternately we can install different versions of JREs on Eclipse manually as follow:
Click Eclipse menu named Window -> select menu option Preferences, the following window pops up.



Select Java from the left panel and click on Installed JREs. We can select one the JREs by checking the checkbox, add more versions of JREs which are available for selection while creating a new project.

Different versions of Eclipse support different versions of Java Development. In order to find out which versions of Java does an Eclipse version supports. Click the Compiler from the left panel from the above window. We can see a drop down list with all Java versions that Eclipse version supports. 


We may have to update or install patches in order to make Eclipse support later versions of Java Development. For example, Eclipse Kepler supports Java 7 by default, if we need Java 8 support in Kepler, we have to install this patch.

In certain scenarios, we may want to change an existing  project to a different version of Java. We may do that as follows:

Right click on the Project from Project Explorer, Click Properties, the following window pops up. Click Java Compiler from the left panel. There we can change the Compiler Compliance Level. We may have to build the project when ever we change the JDK/ JRE.


Next in order the update the JRE/ JDK associated with the project, we have to manually edit it from the project BuildPath as follows:
Right Click on Project from the Package Explorer, select BuildPath, then select Configure BuildPath from the sub menu. The following Properties window pops up. 


Select Libraries tab. You should see a version of JRE System Library. Select that and click Remove and then click on Add Library. The following window pops up. Select JRE System Library.


You will have 3 options to select the desired JRE library. Select a JRE/ JDK and click Finish. You should see the relevant JRE/ JDK added to your project BuildPath.

  

Tuesday, April 1, 2014

Creating Android XMPP Client using locally installed XMPP Server

I wanted to develop an XMPP client as a part of some Android app which needs messaging capability, various XMPP servers are available for free download. I chose Ejabberd 2.1.11 because it has a windows version. I installed it, created a server named 'xmpp-server' and 'admin' user. We can start the server by double clicking the start-ejabberd icon created on desktop. It pops up a web page with a link for admin interface where we can manage the server and do stuff like creating more users etc.

I found this link very useful to develop the android app and it also provides the source code for an app named XMPPClient. I downloaded it and tried to run it. It was developed in IntelliJ, I just imported it in Eclipse and made changes where needed. I USB connected my Samsung Galaxy 3 and ran the app from eclipse directly into my mobile. 

The XMPPClient app worked perfectly, I was able to log-in (with gmail credentials) using the details provided in the screen shots in that link. I was able to send and receive messages to another google account by providing another gmail address. But my goal was to use my own XMPP server instead of gmail server. So while creating ConnectionConfiguration, I used my IP address for HOST, the port will remain same as 5222 and the service has to be modified to the XMPP server instance I created while installation (xmpp-server in my case).

ConnectionConfiguration conConfig = new ConnectionConfiguration(host, Integer.parseInt(port), service);

Both of my android device & laptop where XMPP server is running are connected to my WIFI network, so I used my LOCAL WiFi IP address of my laptop as host (make sure the XMPP server is up and running). The XMPPClient app in the above link aims to connect to gmail server so it uses smack.jar, whereas in our case we are trying to connect to an XMPP server from Android, so we have to use ASmack jar instead of Smack jar which can be downloaded here. Make sure you add the ASmack jar in lib folder of the app, add it to build path and remove smack jar.

In case if you want to use your external IP address which we can find by simply searching for IP address in google, we will have to make sure that we forward all XMPP requests received by our router to the computer where XMPP server is installed. We can achieve this with simple configurations on the router. Firstly make sure that your computer receives a static IP address (not dynamic) assigned by the router internally. We can do that by visiting the LAN setup on your router configuration link, there simply specify a allowed unused local IP address and hook it with your mac address. It should look something like the following image.


Secondly ask the router to forward the XMPP requests to your static IP (your computer) address when ever it receives a request on its 5222 port, which you can do by visiting virtual servers configurations in the Firewall settings of your router, which should look like the image below.


The updated app worked perfectly well for me. I was able to connect to my XMPP server and successfully logged in as admin & as other users too. I was able to send/ receive messages to another XMPP client. We can create more users using the XMPP admin interface, login to the server by installing app in other android devices to test it. Or we may use any XMPP client like pidgin (available for windows here), login as some user and send messages to the admin. You will be able to send & receive messages using the XMPPClient android app to Pidgin. I tested the app installing on two different android devices, was able to login as different users and was able to send/ receive messages between the two devices. Make sure the computer where XMPP server is running and the android devices are all using the same Wi-Fi network if you are working with Local IP address else if working with external IP address you may be on any network. Also make sure the recipient id should be mentioned as userID@XMPPServerInstanceName, in my case it would be hari@xmpp-server.

If you did everything correctly and still not able to connect to locally installed XMPP server using local/ external IP, you should probably check your Firewall settings which should be enabled to receive requests. On Windows make sure you turn on Network Discovery, try to troubleshoot Incoming Connections (image below) and allow to receive requests on erl.


I made lot of changes to the app and published it on the Google Play. I plan to make even more changes to it in near future. You may install it for free on any android device at this link.

The complete source code for the app (Eclipse project) is available on GitHub at this link. Feel free to download. Contributions are welcomed.

If you find any of this useful, feel free to share the blog post on twitter, G+ etc and rate the android app :)

Sunday, February 23, 2014

Using JCalender with Visual Swing in Eclipse

Visual Swing doesn't allow new components to be added to palette like Window Builder does. So I couldn't just drag and drop JDateChooser like I did other Swing components. These are steps to add a simple Date Picker to your Visual Swing JFrame. I used JCalender 1.4.


Note: Link to install Visual Swing on Eclipse.

1) Download and add JCalender JAR to classpath.

2) In your class that extends JFrame class, add a private variable along side the list of other variables (components like JLabel, JTextField, JComboBox etc) that Visual Swing auto creates when you drag and drop them onto the visual JFrame window.
private JDateChooser myDateChooser;
Visual Swing uses Getter to instantiate the compenents whereas Window Builder instantiates directly in the initComponents() method. Use the following getter for visual swing.
private JDateChooser getMyDateChooser(){
if(myDateChooser ==null) {
myDateChooser = new JDateChooser();
                        myDateChooser.setDate(new Date());  }
return myDateChooser;
}
You can register for any events here or set some default date like I did above.

3) Now we need to add this myDateChooser to the JFrame. This is done in the initComponents() method where Visual Swing adds all the other components to the JFrame. The following piece of code will do, make sure you are using proper coordinates inorder to place the Date Picker in the right place on JFrame.
add(getToDateChooser(), new Constraints(new Leading(550, 110, 12, 12), new Leading(60, 12, 12)));
That's it. Now your Date Picker is ready. Make sure to grab the date chosen by the user using some action event listener say a button click in my case. In order to grab the date, all you need is
Calender selectedDate = myDateChooser.getCalendar();
That's it, you can set a default date  and grab the user selected date simply by the getter and setter of JDateChooser.

Sunday, February 12, 2012

Compilation in Java & .NET

The translation of source code written in a programming language to an other machine readable language by a Compiler is known as Compilation.

I will discuss the compilation processes in both Java and .NET (supported languages say C#, VB etc). .NET supportive development is mainly focused for Windows operating system (but the languages supported by .NET are inter-operable) whereas Java development is supported by multiple platforms which means java code written once on any platform can be run on any other platform. This is ONLY possible because of the compilation process both implements underneath.

.NET implements a two-step compilation process. In the first step the respective compilers compile the source code to an intermediate language called MSIL/ CIL. In the second step the Just-In-Time compiler of CLR (common language run-time) converts the CIL to native code for the operating system. So code written in any .NET supportive language is compiled to CIL in the first step which gives the possibility of language inter-interoperability, that means classes written in C# can talk to classes written in VB or vice versa.     


Java also implements a two-step compilation process. In the first step the java compiler compiles the java source code (*.java) into java byte code (*.class). This byte code can be run on any platform using their respective JVM (java virtual machine). Thus by using platform specific JVM java achieves its platform in-dependency. Furthermore there are more languages that run on JVM like Scala, Groovy, JRuby, Jython etc making Java language inter-operable in a way.

Images source: Google Images.
Fork me on GitHub