Thursday, June 07, 2007

Groovy Programming with Eclipse - 3

Let's continue our talk on Numbers and operations.

Arithmetic Operators

1. Addition (+) Operator
2. Subtraction (-) Operator
3. Multiplication (*) Operator
4. Division (/) Operator ( always returns a floating value )
5. Modulus (%) Operator

Example for each of this is shown below.

def num1 = 22;
def num2 = 11;
def add = 22+11; // alternative:;
def sub = 22-11; // alternative: 22.minus(11);
def mul = 22*11; // alternative: 22.multiply(11);
def div = 22/11; //alternative: 22.div(11);
def rem = 22 % 11; //alternative: 22.mod(11);

Note that div holds 2.0 but not 2 as you expect. If you want integral division, then you should do it as "22.intdiv(11)". intdiv() returns an Integer while a div or / returns a BigDecimal.

The same set of operators holds good for all types of numeric values - integral and non-integral.
Try this : 22.2 % 11; what do you expect would be returned. Well, this is an illegal operation. Since numbers are also objects, the operators +,-,*,etc work because they are "overloaded". Note that multiplicative operators have higher precedence over additive operators(+,-). Also, boolean operators(the comparison operators) have lower precendence over any arithmetic operators.

Other operators of interest are increment and decrement operators. Unary operators are available to increment/decrement a number by 1. For example,
def two = 3-1;
The above statement is perfectly valid. But most of us are already used to do the same using ++ unary operator, which I prefer over anything else if the increment/decrement is by 1. Most of us already know how ++ and -- works. To test if you know, try to guess the output of the simple program shown below:
def v = 10;
def op1 = v++;
def op2 = ++v;

Answers: 10 and 12.

As mentioned earlier, types are assigned at run-time! This is referred to as "dynamic-typing" and this is what makes Groovy a loosely-typed language.

As I mentioned earlier, numbers are objects too! So we have to deal with references. Consider the following snippet.

def num = 12;
def num2 = num;
num++; //will this reflect on num2 too???
println num;
println num2; //guess the output.

it prints 12 and 13. But why?? Both the identifiers refer to the same object. So if one object is modified then the other should be effected too. Isn't it? But the output tells something different The output infact makes sense. When you perform changes on the object itself, then a new object would be created and referred by that identifier. To understand my bad english, try the following code:
def num=12;
def num2 = num;
println num;
println num2;

Now you can expect the value to be 13 in both the cases! Well justified uh?? by using the "value" property, we are working on the same object! Sharing still maintained!

Boolean/Relational/Comparison Operators
Well as usual <,>,<=,>=,==,!=are comparison or relational operators(also includes the equality operators). Alternative way to do the above said operators is to use compareTo() and equals() methods. For example,
def v1 = 22;
def v2 = 21;
v1.compareTo(v2); //is > 0 in this case.(v1-v2 is ofcourse returned ;)
v1.equals(v2); // returns false.

Note: since the language is loosely typed, i prefer to use .class operator to test what functions/operators bind to what class especially when I try out some new methods. And one last thing to remember is that Garbage collector is always active even when working with plain simple numbers.(ofcourse they are objects !).

In the next post, let us talk about Strings in specific.

I hope atleast one in the world other than me will find this tutorial useful. If so, I appreciate your comments.

Groovy Programming with Eclipse - 2

In the current post, I would present how to work with Numbers and variables in Groovy. Before we move into the program, some Groovy fundas.
1. Groovy classes are binary-compatible with Java classes - the Groovy compiler generates the same byte codes as that of javac.
2. Groovy brings uniformity to Java language. Everything in Groovy is an object - including fundamental data-types.
3. Groovy is dynamically typed. For example, having the following statements in the same block would work in Groovy while fails in Java
def x = 10; // integer
x = "bhargav"; // string
Based on the value assigned to the variable, the type of the variable is determined.
4. Groovy provides "Properties" which are already present in C# and VB.NET. They are kind of mixture of both instance fields and methods.
5. Other interesting feature is the presence of data structures like Maps, List as native language constructs. In java we use ArrayList or LinkedList, while in Groovy, its just []. For example,
def names = []; //creates an empty names list.

Well as you have already seen, to create a variable we use the keyword "def" and if the variable name already exists then we can assign the value we wish to straight-away. Its just that simple.
Use the earlier post and create a new Groovy class in Eclipse. Then try to create a variable using "def" as shown.
def name = "Krishna";
Now since the RHS is a string, internally Groovy compiler picks java.lang.String. We can know what class an object belongs to using the ".class" property.

println name.class;

The above statement would now print "java.lang.String". Now try assigning a different value, now lets assign an integer and look at the class.

name = 100;
println name.class;

This would now print "Integer" on the console. Similary, let us create a list and then see what class internally it uses.

def names = ["Bhargava", " loves ", " Programming."];
println names.class;

Guess what this would print? This prints java.util.ArrayList !! So lists of Groovy internally uses "ArrayList". As we can see everything here is a class and its basically appears as top-layer on Java to make programmers lazy. So other language rules/regulations are still applicable to Groovy. For example, you cannot call non-static methods from a static method directly. Now that we are talking about methods, let us write a simple method. This method should now return us what class the argument passed belongs to. Well, for not-so-experienced but good programmers, one question raises. What should be the return type? Well the class property is of type "Class".
So is name.class.class a valid one?? Definitely! it would be java.lang.Class. Now let us get back to a simple program showing methods in Groovy.
class VariablesAndMethods
static main(args) //notice with groovy even the main args is not specified as String[]
println className(5);
println className("Bhargava");
println className(100.00);
println className(true);
println className(true.class);
static Class className(object)

Wait! where is the "return" statement? Well in groovy, there is no need to specify return explictly. Kind of bad! Well atleast for me. Now the output looks like this:

class java.lang.Integer
class java.lang.String
class java.math.BigDecimal
class java.lang.Boolean
class java.lang.Class

Well let me confuse you more. Shown below is a small method. Tell me what it prints.
static increment(value)
Well this returns "value" itself. ( Post Increment operator ).
How about this?
static increment(value)
If we notice the return value of this method, we can notice that if there are multiple statements which are like "value;"(equi to return value;) then only the last statement would be equivalent to "return value;".

If you already know, in Java 0 is not False and 1 or more is not true. But in Groovy, the old ways are back. Try this statement ( well for simple statements you can use Groovy console. (From rt click on project->Groovy->Groovy Console. Type in a statement and press CTRL + R ).
println 0==false;

When you run the above statement you would end up getting ClassCastException. But try this:
println someFunction();
where someFunction is defined as
Boolean someFunction()
return 0; //return zero.
This would print "false" and for any +ve number returned, this prints "true". Kind of confusing, isnt it??

Well enough of methods, in the next post I would continue my talk on numbers and we will see how to perform operations on numbers and stuff.

Groovy Programming with Eclipse - 1

In this short series of Groovy posts, I intend to cover some Groovy fundas and at the same time myself learn the platform. I will work on Eclipse and would not work at console level and instead use Groovy plugin on Eclipse.
1. Installing Groovy Plugin for Eclipse.
  • Start Eclipse. Go to Help->Software Updates->Find and Install.
  • Select "Search for new features to install" and click Next.
  • Click on "New Remote Site"
  • Give a name say "Groovy Plugin" and in the URL put ""
  • Click Ok. Now select the newly added remote site and then click Finish. Follow the on-screen instructions and majorly you need to click "Install All" and then restart Eclipse for the changes to be effected.

2. Testing your Groovy installation on Eclipse.

  • Create a new project in Java.
  • Now in the Package Explorer right click on the project. You should see a "Groovy" item in the context menu.
  • So go to the Groovy item in the context menu and go to "Groovy->Add Groovy Nature".
  • Doing this would kind of convert our Java project to Groovy project. We can now run and test our Groovy programs.
  • Now right click on the project and create a new package. Say "groovy.learning.samples".
  • Then right click on the project and click on "New->Other". Type Groovy in the "type filter text" textbox. Now select "Groovy Class" and give it a name.(Tutorial1).
  • Type the following line inside the code block already generated. Essentially you see a main already inserted.
    "println("Welcome to Groovy World");
  • Save the file. Now go to the menu "Run->Run As->Groovy Application". You should be able to see the message printed in the console. If so , you have successfully installed Groovy plugin on eclipse and good to write your Groovy programs.

This post, I hope, gives a quickstart to get started working with Groovy on Eclipse. In the subsequent posts, I hope to cover other basic programming constructs in Groovy.

Monday, June 04, 2007

Changing default editor for GreaseMonkey

[Using GreaseMonkey with Visual Studio Web Developer - Orcas Express Edition]
Currently, I am working on GreaseMonkey. I intend to use it as a platform my research on web script anomaly detection. And when we create a new user script, it opens in the dirtiest text editor on earth - the Notepad. And I was wondering on how to change the Default text editor for GreaseMonkey. I wanted to set it to Visual Studio Web Developer Express - Orcas, since it has intellisense for Javascript and that would speed up my job. After searching here and there, I could not find any information on where to change. But I just figured it out on how to change the default editor. Just type "about:config" in firefox address bar to go Firefox preferences. Then, filter for the key "greasemonkey.editor" and change the value to that of the editor you like !!
All set to go.