How coding to Interface and Inheritance helped me reuse code

Before going into the details I will state the requirement:

  • I need to fetch certain records from 3 different tables into 3 ArrayLists.
  • I have 3 Classes which store the information: Lets name it- Class1, Class2, Class3.
  • All the above 3 classes implement the Interface, lets name it Interface1. The interface has a method called init(). The main task of init() is to initiate the values of the instance variables with the values obtained from the ResultSet (database). This instance is then added to one of the 3 lists define above depending on the type of the reference.

Read more…

Categories: Java Basics Tags: ,

Execute external process from within JVM using Apache Commons Exec library

Executing external command from within JVM often causes problems- be it in terms of the code to write and manage or in the ease of implementation. I had similar requirement in my Major project for my Under Graduate Degree, where in I had to launch a C program from the Java code. I ran into different issues like- the Main thread getting blocked, the GUI freezing, or reading the output streams and so on. Finally I had to give up the idea and stick with launching the external command externally ūüėõ Had I found the Exec library from Apache Commons then, my work would have been lot easier. Anyways better late then never. I will quickly go through how one can use Exec library to launch external programs from JVM- Its a wrapper over Java’s ProcessBuilder, Runtime.getRuntime().exe(). Read more…

Working with Java Enumerated types (Enums)

December 1, 2009 10 comments

In this post I would like to explain about Enums in Java. Though in my 2 years of coding in Java I have seldom used Enums but they do provide a lot of features when we are required to create a say limited instances of certain type. In this post I have made use of an example written out of inspiration from the example program given in “A Programmer’s Guide to Java SCJP certification” by Khalid A. Mughal and Rolf W. Rasmussen. The example is given in the Section Enumerated Types. I will be developing the Enum as we go through the article.

What is an Enumerated Type or Enum tpye? Enum Type defines a finite set of symbolic names and their values. Suppose we have to define 3 constants- LOW, MEDIUM and HIGH to denote the 3 speeds of Rotation. We can do it by declaring static final variables as follows-

class Speed{
   public static final int LOW=1;
   public static final int MEDIUM=2;
   public static final int HIGH=3;

Read more…

Null, null, Nil, Nothing, None, and Unit in Scala

Null– Its a Trait.
null– Its an instance of Null- Similar to Java null.

Nil– Represents an emptry List of anything of zero length. Its not that it refers to nothing but it refers to List which has no contents.

Nothing is a Trait. Its a subtype of everything. But not superclass of anything. There are no instances of Nothing.

None– Used to represent a sensible return value. Just to avoid null pointer exception. Option has exactly 2 subclasses- Some and None. None signifies no result from the method.

Unit– Type of method that doesn’t return a value of anys sort.

Note: Any is supertype of AnyRef and AnyVal. AnyRef is the supertype of all the reference classes (like String, List, Iterable) in scala. AnyVal is the supertype of all the value classes (like Int, Float, Double, Byte, Short..). Null is a subtype of all the reference classes. null is its only instance. Nothing is subtype of every other type i.e of reference and value classes.

Think- AnyRef == Object in Java.

The above is a breif summary of a wonderful post by Matt Malone where he has explained all these concepts in depth with examples. Read the blog post here.

Categories: Scala Tags: , , , , , , ,

Traits in Scala- Deep Dive

Traits are units of code reuse in Scala. Traits encapsulates methods and field definitions. Their role is similar to that of interfaces in Java- A workaround for Multiple Inheritance. But unlike Interfaces they can have method and field definitions. More features will be explained in the article.

Defining Traits:

A trait definition looks like a class definition but uses the keyword “trait.

trait Bounceable{

     def bounce():String="Bounce Method in Trait"


The above declared trait has a concrete method. The ability to declare concrete methods in an trait gives default implementation option. In interfaces one has to write/copy-paste the default declaration in each class which implements the interface or declare a class that implements that interface and let other classes extend the concrete class. The first method has code repition and the second method has the restriction that a class can extend only one class. So this feature of “trait” stands out best.

As in Java a class implements interface, in Scala classes traits are mixed into a class. This is done using either extends or “with” keywords.

class Ball(s: Int) extends Bouncable{

      var size:Int

      override def toString():String= Integer.toString(size)


In the above example we are using extends to mix in the trait- Here Ball is implicitly inherits trait’s superclass which is “AnyRef”. Lets try to use the class Ball to test the mixed in trait.

object Test{

           def main(args:Array[String])={

                    var ball = new Ball(33)

                    var ball2:Bounceable= new Ball(400)

                    println(ball.bounce()) //This prints "Bounce Method in Trait"

                    println(ball) //This prints "33"





Note: Output written as comment.

Regarding the ball2 instance being declared as type “Bounceable”. Its a valid declaration cause supertype references can refer to the instances of its subtypes. But they cannot access the methods/fields declared by the subtypes (different with the overriding case).

Read more…

How’s Scala different from Java?

  • Scala is statically type like Java but with Type Inferencing support. Which means that the scala compiler analyzes the code deeply to determine what type a particular value is.
  • In Scala its not required to use semicolons to terminate a statement if the termination is obvious by line ending. If there are more than one statements on the single line then they have to be separated by using semicolon.
  • Scala doesnot require the file containing a class definition to mirror the name of the class.
  • In Scala there’s no use of static all together. This is replaced by use of singleton object. Singleton objects are declared by using the keyword “object” and not “class”.
  • In Scala, arrays are instances of Array class and uses square brackets ([]) instead of angle brackets (<>) to indicate parameterized types.
  • In Scala the variable declaration is: “name: type”
  • Scala uses keyword “Unit” to represent functions which return “non-value” value.
  • In Scala the syntax for method declaration is different. It uses the “=” before the method body preceeded by the identifier/name of the method along with the parameter list and return type. Functions are treated like variables and constants.
  • Scala supports the use of closures, Annonymous functions- Which makes longer code simpler and shorter.

These were few things i have noted. There are lot more differences. If u know any please add it as a comment. Will upadate my post accordingly.

Categories: Scala Tags: , ,

Control Structures in Scala- A brief overview

If Statements:

Lets consider a first entry example of If statments, without using much of Scala’s features.


println("You are wrong in calculations")


println("Keep it up")


This is a pretty simple and straight forward examples. Now lets add some Scala flavor in the If-Statement. In Scala If-Statements are expressions, which means that the value from If-Statements can be assigned to some variable. Lets consider another example- Finding greatest of two numbers.

Note: I am using the scala interpreter.

scala>var num1=54
scala>var num2=76

I have created 2 variables. We will have to write a If-Statement for finding out the greatest value and assign it to another variable.

scala>var big=if(num1>num2){ num1}else{num2}

One can see how the result from a if-expression is assigned to a variable. This feature of If construct has removed the need of a Select case construct. Also note that the Type Inference coming into play there- I haven’t mentioned tat big is a Int but it has inferred based on the If-Statement that it will hold an Int. If we had missed the else part then it would have inferred the type to be Unit (void in Java).

For Loops

In the Scala world they are also referred to as the “For Comprehension” or “For Expression”. Let’s consider a example list.

scala> var cities=List(“Bangalore,India”, “Delhi, India”, “Chennai, India”,”Tokyo, Japan”, “New York, USA”, “London, UK”, “Paris, France”)

The above code will create a List of Cities along with their countries.¬† Now lets use a for loop to “comprehend” the list.

scala> for(city <- cities)println(city)


Straight forward and simple. The left arrow operator (&lt;-) is called as "<strong>generator</strong>" as it is used to generate elements from the list. Now lets print the cities in India with the help of the Scala's features

scala>for(city <- cities if city.contains("India"))println(city)


Delhi, India

Chennai, India


The above technique is called "<strong>Filtering</strong>". One can add multiple filers (if condition) and the filers have to be seperated by using ";".  Now suppose we want to store the Indian cities in a separate list, what do we do? Scala does have a solution to that as well. Lets look at the code:

scala> var indianCities=for(city <- cities if city.contains("India"))yield city

scala>for(city <-indianCities)println(city)


Delhi, India

Chennai, India


The type of the yielded list has not been mentioned. Scala infers the type from the Type of the Collection being used to yeild a new List.

<strong>While and Do-While Loops:</strong>

While loops, as in other languages, execute the code in the block until the condition is true. Do-While is similar to While the only difference being that the loop is executed at least once and checks to see if the condition is true or not.

Example to find sum of first 10 natural numbers

scala> var i=1

scala>var sum=0

scala>while(i<=10){ sum=sum+i;i=i+1}


An example to show do while loop:


scala>do{ sum +=i;i+=1}while(sum<100)


That was a brief overview of If, For, While and Do-While constructs.

Categories: Scala Tags: , , , , , ,