*
*
|
|
Groovy Sample Code
Zamples® makes it easy for you to play with
Codehaus's Groovy interpreter.
You don't need to install any software, just click the 'Try It!'
buttons below.
Let
us know if there are any other languages that you would like us to support.
JSR 241 adopted Groovy as a Java-based scripting language.
This page lets you try Groovy without having to install any software.
After you click on a 'Try It!' button in a community posting, or after you press a 'New' button
to start a new discussion thread,
edit your code, select the type of program (Groovy, JDK 1.4/5.0 Fragment or Class, Perl or Python), and then 'Run It!' until it works (or
you give up). When you click on the 'Save' button, the New Posting Wizard will appear. The wizard will prompt
you for information about your code example, and then save it to the database. Each posting contains
a code example, plus comments about the code. Next time you refresh this page
your new posting will appear.
Learn more about Zamples and play with samples for other APIs.
Our live JDK 5.0 examples are very popular!
We would love to hear your feedback.
Array Creation
Peculiar Groovy behavior
Purpose: asdf
Description: asdf |
|
Peculiar Groovy behavior
Purpose: Modified the code example by removing unwanted comments.
Description: Modified the code example by removing unwanted comments. |
double[] values = new double[8]
i = 0
[1, 2, 3, 4, 5, 6, 7, 8].each {
values[i++] = it
println it
}
|
Peculiar Groovy behavior
Purpose: If you replace the values[i++] = it to values[i] = it and then do i++ it works perfectly and gives the required answer as 12345678!!
Also if you interchange the lines println it and values[i++] = it then also it works correctly.
hence the pgm may be modified as,
double[] values = new double[8]
i = 0
[1, 2, 3, 4, 5, 6, 7, 8].each {
values[i++] = it
println it
}
Description: It is a reply to the Groovy Peculiar behavior topic. i modified the given code example in a different way to make it run correctly as expected. |
double[] values = new double[8]
i = 0
[1, 2, 3, 4, 5, 6, 7, 8].each {
values[i++] = it
println it
// i++
// uncomment the next line and it works fine!!
//println it
}
|
Peculiar Groovy behavior
Purpose: This scriptlet throws an java.lang.ArrayIndexOutOfBoundsException: 8, as if the list has more than 8 element!!
But if you remove the comment for the second println it, then it work fine.
Any clue??
Description: Any clue? |
double[] values = new double[8]
i = 0
[1, 2, 3, 4, 5, 6, 7, 8].each {
println it
values[i++] = it
// uncomment the next line and it works fine!!
//println it
}
|
More friendly array creation and if-then-else
Purpose: After you have run the example, delete some elements of the array and rerun the example
Description: This version of the code example doesn't throw an exception when the array shrinks. |
x = [1, 2, 3, 4, 5, 6]
println(x)
if (x != null && x.size() > 5) {
println("Works!")
} else {
println("I'm smaller than I used to be")
}
|
Array creation and if-then-else
Purpose: Shows how to work with arrays and the if-then-else statement.
Description: An array is created and an if-then-else statement is used to display information depending on the contents of the arrayAfter you have run the example, delete some elements of the array and rerun the example. |
x = [1, 2, 3, 4, 5, 6]
println(x)
if (x != null && x.size() > 5) {
println("Works!")
} else {
assert false: "should never happen ${x}"
}
|
|
| to add a new posting or reply to an existing posting. |
|
Here Document
Here document
Purpose: Here documents are great for scripting languages.
Description: The assert doesn't do much. |
name = "big boy"
text = <<<FOO
Hello there, ${name}!
How are you today?
FOO
assert text != null
println(text)
|
|
| to add a new posting or reply to an existing posting. |
|
GStrings
GStrings
Purpose: OK, so the inventors of Groovy have a twisted sense of humor.
Description: Notice how the lazy bndings of the gstrings cause the output to change after the gstring is created. Definitey worth playing with. |
name = "Fred"
string = "My name is " + "${name}"
println(string)
name = "George"
string = "My name is " + "${name}"
println(string)
|
|
| to add a new posting or reply to an existing posting. |
|
Iterate over a Map
Iterate over a Map
Purpose: Maps are easily created and used.
Description: The map values are summed in the variable x, then printed. |
map = ['abc':1, 'def':2, 'xyz':3]
x = 0
for ( e in map ) {
x += e.value
}
println("Total is " + x)
|
|
| to add a new posting or reply to an existing posting. |
|
Iterate over the Characters in a String
Iterate over the characters in a string
Purpose: The documentation says that Groovy can iterate over the characters in a string, but this example appears to demonstrate a bug.
Description: If you figure out a way whereby you can make this work, please post a response. |
text = "Gimme your dough!"
i = 0
for (c in text) {
println("" + i + ": " + c)
i = i + 1
}
|
|
| to add a new posting or reply to an existing posting. |
|
Regular Expressions
Regular expressions
Purpose: As usual, play with the code example so you can get a personal experience with the language.
Description: If you are familiar with regular expressions this example is fairly straightforward. If not, it's probably very confusing! |
import java.util.regex.Matcher
import java.util.regex.Pattern
assert "cheesecheese" =~ "cheese"
// lets create a regex Pattern
pattern = ~"foo"
assert pattern instanceof Pattern
assert pattern.matcher("foo").matches()
// lets create a Matcher
matcher = "cheesecheese" =~ "cheese"
assert matcher instanceof Matcher
answer = matcher.replaceAll("edam")
println(answer)
// lets do some replacement
cheese = ("cheesecheese" =~ "cheese").replaceFirst("nice")
println(cheese)
|
|
| to add a new posting or reply to an existing posting. |
|
Closures
Closures
Purpose: Fix the broken code
Description: Add and initialize the variable last |
count = 0
last = 0
[1, 2, 3, 4].each { count += it; last = it }
println("The sum is ${count} and the last item was ${last}")
|
Closures
Purpose: To correct the code of closure throwing Null pointer exception
Description: This appears to be the same as the previous method 6. So, the solution as I have already posted is to initialize last to 0 before the beginning of the each loop. |
count = 0
last = 0
[1, 2, 3, 4].each { count += it; last = it }
println("The sum is ${count} and the last item was ${last}")
|
Closures
Purpose: The closures example was throwing NullPointerException when used as +=. Corrected the same.
Description: The problem was not with +=. Even if I breaked the code to count = count + it, NullPointerException was coming. So i declared or rather initialized the variable last to 0 before the each loop began and now it is working correctly as expected. |
count = 0
last = 0
[1, 2, 3, 4].each {
count = count + it
last = it
}
println("The sum is ${count} and the last item was ${last}")
|
Closures
Purpose:
Description: Breaking out the += to it's explicit assignment removes the error -- it looks like this might be a Groovy interpreter bug, but I'm not a Groovy expert.Working example of a closure in Groovy |
count = 0
[1, 2, 3, 4].each { count = count + it; last = it }
println("The sum is ${count} and the last item was ${last}")
|
Closures
Purpose: Closures are supposed to be like anonymous inner classes, but this example (taken straight from the docs) doesn't work.
Description: If you can figure out a way of making this work, please post a response. |
count = 0
[1, 2, 3, 4].each { count += it; last = it }
println("The sum is ${count} and the last item was ${last}")
|
|
| to add a new posting or reply to an existing posting. |
|
Add New Code Samples Here
If you have code samples that don't fit into any of the topics above which you would like to contribute,
please put them here.
We'll sort them out into their own sections as appropriate later.
|
| to add a new posting or reply to an existing posting. |
|
|