Are there any extensions for the Java programming language that make it possible to create nested functions?
There are many situations where I need to create methods that are only used once in the context of another method or for-loop. I've been unable to accomplish this in Java so far, even though it can be done easily in JavaScript.
For example, this can't be done in standard Java:
for(int i = 1; i < 100; i++){
times(2); // Multiply i by 2 and print i
times(i); // Square i and then print the result
public void times(int num){
i *= num;
System.out.println(i);
}
}
Java 8 introduces lambdas.
java.util.function.BiConsumer<Integer, Integer> times = (i, num) -> {
i *= num;
System.out.println(i);
};
for (int i = 1; i < 100; i++) {
times.accept(i, 2); //multiply i by 2 and print i
times.accept(i, i); //square i and then print the result
}
The () -> syntax works on any interface that defines exactly one method. So you can use it with Runnable but it doesn't work with List.
BiConsumer is one of many functional interfaces provided by java.util.function.
It's worth noting that under the hood, this defines an anonymous class and instantiates it. times is a reference to the instance.
The answer below is talking about the closest you can get to having nested functions in Java before Java 8. It's not necessarily the way I'd handle the same tasks which might be handled with nested functions in JavaScript. Often a private helper method will do just as well - possibly even a private helper type, which you create an instance of within the method, but which is available to all methods.
In Java 8 of course, there are lambda expressions which are a much simpler solution.
The closest you can easily come is with an anonymous inner class. That's as close as Java comes to closures at the moment, although hopefully there'll be more support in Java 8.
Anonymous inner classes have various limitations - they're obviously rather wordy compared with your JavaScript example (or anything using lambdas) and their access to the enclosing environment is limited to final variables.
So to (horribly) pervert your example:
interface Foo {
void bar(int x);
}
public class Test {
public static void main(String[] args) {
// Hack to give us a mutable variable we can
// change from the closure.
final int[] mutableWrapper = { 0 };
Foo times = new Foo() {
#Override public void bar(int num) {
mutableWrapper[0] *= num;
System.out.println(mutableWrapper[0]);
}
};
for (int i = 1; i < 100; i++) {
mutableWrapper[0] = i;
times.bar(2);
i = mutableWrapper[0];
times.bar(i);
i = mutableWrapper[0];
}
}
}
Output:
2
4
10
100
Is that the output you get from the JavaScript code?
I think that the closest you can get to having nested functions in Java 7 is not by using an anonymous inner class (Jon Skeet's answer), but by using the otherwise very rarely used local classes. This way, not even the interface of the nested class is visible outside its intended scope and it's a little less wordy too.
Jon Skeet's example implemented with a local class would look as follows:
public class Test {
public static void main(String[] args) {
// Hack to give us a mutable variable we can
// change from the closure.
final int[] mutableWrapper = { 0 };
class Foo {
public void bar(int num) {
mutableWrapper[0] *= num;
System.out.println(mutableWrapper[0]);
}
};
Foo times = new Foo();
for (int i = 1; i < 100; i++) {
mutableWrapper[0] = i;
times.bar(2);
i = mutableWrapper[0];
times.bar(i);
i = mutableWrapper[0];
}
}
}
Output:
2
4
10
100
Such methods are sometimes called closures. Have a look at Groovy – perhaps you will prefer it to Java. In Java 8 there will probably be closures as well (see JSR335 and deferred list).
For non-argument method you can create Runnable object
private static void methodInsideMethod(){
Runnable runnable = new Runnable(){
#Override
public void run(){
System.out.println("Execute something");
}
};
for(int i = 0; i < 10; i++){
runnable.run();
}
}
Consider making an anonymous local class and using its initializer block to do the work:
public class LocalFunctionExample {
public static void main(final String[] args) {
for (final int i[] = new int[] { 1 }; i[0] < 100; i[0]++) {
new Object() {
{
times(2); //multiply i by 2 and print i
times(i[0]); //square i and then print the result
}
public void times(final int num) {
i[0] *= num;
System.out.println(i[0]);
}
};
}
}
}
Output:
2
4
10
100
(The "final wrapper trick" is not automatically required with this technique, but was needed here to handle the mutation requirement.)
This works out to be almost as concise as the lambda version, but you get to use whatever method signatures you want, they get to have real parameter names, and the methods are called directly by their names - no need to .apply() or whatnot. (This kind of thing sometimes makes IDE tooling work a little better too.)
I don't know if anyone else has figured this out, but apparently you can do magic with the var keyword that comes with Java 10 and above. This saves you from having to declare an interface if you don't have one that will work for you.
public class MyClass {
public static void main(String args[]) {
var magic = new Object(){
public void magic(){
System.out.println("Hello World!");
}
};
magic.magic();
}
}
I have tested it and it works. I haven't found a Java compiler that lets you do a simple share yet.
I hate to use the forbidden word but you could use a goto statement to create an an effective subroutine inside the method. It is ugly and dangerous but much easier than what was shown in previous answers. Although the private method with a call inside of the first method is much better, and serves you needs just fine. I don't know why you would want to use a nested method for something as simple as this.
Related
I would like to pass a reference to a primitive type to a method, which may change it.
Consider the following sample:
public class Main {
Integer x = new Integer(42);
Integer y = new Integer(42);
public static void main(String[] args) {
Main main = new Main();
System.out.println("x Before increment: " + main.x);
// based on some logic, call increment either on x or y
increment(main.x);
System.out.println("x after increment: " + main.x);
}
private static void increment(Integer int_ref) {
++int_ref;
}
}
The output running the sample is:
x Before increment: 42
x after increment: 42
Which means int_ref was past to the function by value, and not by reference, despite my optimistic name.
Obviously there are ways to work around this particular example, but my real application is way more complex, and in general one would imagine that a "pointer" or reference to integer would be useful in many scenarios.
I've tried to pass Object to the function (then casting to int), and various other methods, with no luck. One workaround that seems to be working would be to define my own version of Integer class:
private static class IntegerWrapper {
private int value;
IntegerWrapper(int value) { this.value = value; }
void plusplus() { ++value; }
int getValue() { return value; }
}
Doing this, and passing a reference to IntegerWrapper does work as expected, but to my taste it seems very lame. Coming from C#, where boxed variable just remain boxed, I hope I just miss something.
EDIT:
I would argue my question isn't a duplicate of Is Java "pass-by-reference" or "pass-by-value"?, as my question isn't theoretical, as I simply seek a solution. Philosophically, all method calls in all languages are pass-by-value: They either pass the actual value, or a reference to the value - by value.
So, I would rephrase my question: What is the common paradigm to workaround the issue that in java I'm unable to pass a reference to an Integer. Is the IntegerWrapper suggested above a known paradigm? Does a similar class (maybe MutableInt) already exist in the library? Maybe an array of length 1 a common practice and has some performance advantage? Am I the only person annoyed by the fact he can store a reference to any kind of object, but the basic types?
Integer is immutable, as you may notice.
Your approach with private static class IntegerWrapper is correct one. Using array with size 1 is also correct, but in practice I have never seen using array for this case. So do use IntegerWrapper.
Exactly the same implementation you can find in Apache org.apache.commons.lang3.mutable.MutableInt.
In your example you also can provide Main instance to the static method:
public class Main {
private int x = 42;
public static void main(String[] args) {
Main main = new Main();
incrementX(main);
}
private static void incrementX(Main main) {
main.x++;
}
}
And finally, from Java8 you could define an inc function and use it to increment value:
public class Main {
private static final IntFunction<Integer> INC = val -> val + 1;
private int x = 42;
public static void main(String[] args) {
Main main = new Main();
main.x = INC.apply(main.x);
}
}
The title can easily be misunderstood, but it boils down to that I most likely require a design-pattern to eliminate redundant code. To make my question as clear as possible I made a code example instead of writing a vague explanation.
Basically, I have the following functions:
getValue1(), getValue2(), getValue3(), ... , getValue12()
These functions could look as follows (though all differ slightly from each other and are not editable by means of making them implement an interface for a strategy pattern):
public int getValue1()
{
return 1 + 2;
}
Next we have a secondary class myClass which requires the values returned by the getValue() functions. A function from myClass would then look as follows (each differ in the fact that they make use of a different getValue() function):
public int getMyValues1()
{
int[] values = new int[10];
for (int i = 0; i < 10; i++) {
int[i] = getValue1() // NOTE: getValueX() may output differently each time.
}
}
We have arrived at our problem.
If we would make a getMyValues() function for each respective getValue(), we would have to copy and then paste the same code several times.
This goes against everything OOP languages stand for - that's why I require your help.
Any suggestion is much appreciated!
EDIT:
I reopened the question, because I didn't have Java 8 supported on the IDE I am to use.
Basically I have the following setup:
getValueClass
getValue1()
getValue2()
etc.
myClass
getMyValues1()
getMyValues2()
etc.
implemetingClass
private myClass mc = new MyClass()
main()
getLowestValue(int[] values)
And so main() could look as follows - if i'd wish to output the lowest value:
public static void main(String[] args)
{
...
System.out.print(getLowestValue(mc.getMyValues1()));
...
}
This edit goes to show that a strategy pattern isn't viable, since I have my functions in one class.
Hopefully this clears up any confusion and I really hope you guys can help me solve this issue!
Assuming these methods are public, then in Java 8, you should be able to use a functional interface (in this trivial example it would be a java.util.function.IntSupplier) and pass a reference to these methods as a lambda expression.
Something like (compilation not tested):
public int[] getMyValues(IntSupplier supplier) {
int[] values = new int[10];
for (int i = 0; i < 10; i++) {
int[i] = supplier.getAsInt()
}
return values;
}
Called using:
int[] values = someobject.getMyValues(someobject::getValues1)
This is more or less using those methods as strategies without the need to make an actual interface and multiple implementations: the strategy interface is the functional interface itself and the method references generate the implementation.
EDIT: if you can't use Java 8, then you can just define your own interface with just 1 method that returns the int. The calling just becomes longer because of the lack of support for method references:
int[] values = someobject.getMyValues(new MyIntProducer() {
public int getValue() { return someobject.getValues1(); };
}
Note that the someobject local variable will need to be made final for this to work.
You can use reflection. I don't recommend doing it this way but there is a time place for this type of thing.
import java.util.Map;
import java.util.HashMap;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
public class ReflectiveGetter {
private final Object theObject;
private final String methodPattern;
private final Map<Integer, Method> methodsByIndex = new HashMap<Integer, Method>();
public ReflectiveGetter(Object theObject, String methodPattern) {
this.theObject = theObject;
this.methodPattern = methodPattern;
String patternToMatch = methodPattern + "\\d+";
for(Method m : theObject.getClass().getMethods()) {
String name = m.getName();
if(name.matches(patternToMatch)) {
m.setAccessible(true);
int i = Integer.parseInt(name.substring(methodPattern.length()));
methodsByIndex.put(i, m);
}
}
}
public int getValue(int index)
throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
Method m = methodsByIndex.get(index);
if(m != null) {
return (Integer)m.invoke(theObject);
}
throw new NoSuchMethodException(methodPattern + index);
}
}
Usage is:
ReflectiveGetter rg = new ReflectiveGetter(theValueObject, "getValue");
System.out.println(rg.getValue(1)); // prints as if theValueObject.getValue1()
Reflection is clumsy and you should not use it if you do not know what you are doing or there are more convenient options.
For example, perhaps the value class should be using a Map to begin with.
https://stackoverflow.com/a/572550/1165790
I want to use this feature in Java because the function that I'm designing is called rarely (but when it is called, it starts a recursive chain) and, therefore, I do not want to make the variable an instance field to waste memory each time the class is instantiated.
I also do not want to create an additional parameter, as I do not want to burden external calls to the function with implementation details.
I tried the static keyword, but Java says it's an illegal modifier. Is there a direct alternative? If not, what workaround is recommended?
I want it to have function scope, not class scope.
I want it to have function scope, not class scope.
Then you are out of luck. Java provides static (class scoped), instance and local variables. There is no Java equivalent to C's function-scoped static variables.
If the variable really needs to be static, then your only choice is to make it class scoped. That's all you've got.
On the other hand, if this is a working variable used in some recursive method call, then making it static is going to mean that your algorithm is not reentrant. For instance, if you try to run it on multiple threads it will fall apart because the threads will all try to use the same static ... and interfere with each other. In my opinion, the correct solution would be either to pass this state using a method parameter. (You could also use a so-called "thread local" variable, but they have some significant down-sides ... if you are worrying about overheads that are of the order of 200 bytes of storage!)
How are you going to keep a value between calls without "wasting memory"? And the memory consumed would be negligible.
If you need to store state, store state: Just use a static field.
Caution is advised when using static variables in multi-threaded applications: Make sure that you synchronise access to the static field, to cater for the method being called simultaneously from different threads. The simplest way is to add the synchronized keyword to a static method and have that method as the only code that uses the field. Given the method would be called infrequently, this approach would be perfectly acceptable.
Static variables are class level variables. If you define it outside of the method, it will behave exactly as you want it to.
See the documentation:
Understanding instance and Class Members
The code from that answer in Java...
public class MyClass {
static int sa = 10;
public static void foo() {
int a = 10;
a += 5;
sa += 5;
System.out.println("a = " + a + " sa = " + sa);
}
public static void main(String[] args) {
for (int i = 0; i < 10; i++) {
foo();
}
}
}
Output:
$ java MyClass
a = 15 sa = 15
a = 15 sa = 20
a = 15 sa = 25
a = 15 sa = 30
a = 15 sa = 35
a = 15 sa = 40
a = 15 sa = 45
a = 15 sa = 50
a = 15 sa = 55
a = 15 sa = 60
sa Only exists once in memory, all the instances of the class have access to it.
Probably you got your problem solved, but here is a little more details on static in Java. There can be static class, function or variable.
class myLoader{
static int x;
void foo(){
// do stuff
}
}
versus
class myLoader{
static void foo(){
int x;
// do stuff
}
}
In the first case, it is acting as a class variable. You do not have to "waste memory" this way. You can access it through myLoader.x
However, in the second case, the method itself is static and hence this itself belongs to the class. One cannot use any non-static members within this method.
Singleton design pattern would use a static keyword for instantiating the class only once.
In case you are using multi-threaded programming, be sure to not generate a race condition if your static variable is being accessed concurrently.
I agree with Bohemian it is unlikely memory will be an issue. Also, duplicate question: How do I create a static local variable in Java?
In response to your concern about adding an additional parameter to the method and exposing implementation details, would like to add that there is a way to achieve this without exposing the additional parameter. Add a separate private function, and have the public function encapsulate the recursive signature. I've seen this several times in functional languages, but it's certainly an option in Java as well.
You can do:
public int getResult(int parameter){
return recursiveImplementation(parameter, <initialState>)
}
private int recursiveImplementation(int parameter, State state){
//implement recursive logic
}
Though that probably won't deal with your concern about memory, since I don't think the java compiler considers tail-recursive optimizations.
The variables set up on the stack in the recursive call will be function (frame) local:
public class foo {
public void visiblefunc(int a, String b) {
set up other things;
return internalFunc(a, b, other things you don't want to expose);
}
private void internalFunc(int a, String b, other things you don't want to expose) {
int x; // a different instance in each call to internalFunc()
String bar; // a different instance in each call to internalFunc()
if(condition) {
internalFunc(a, b, other things);
}
}
}
Sometimes state can be preserved by simply passing it around. If required only internally for recursions, delegate to a private method that has the additional state parameter:
public void f() { // public API is clean
fIntern(0); // delegate to private method
}
private void fIntern(int state) {
...
// here, you can preserve state between
// recursive calls by passing it as argument
fIntern(state);
...
}
How about a small function-like class?
static final class FunctionClass {
private int state1; // whichever state(s) you want.
public void call() {
// do_works...
// modify state
}
public int getState1() {
return state1;
}
}
// usage:
FunctionClass functionObject = new FunctionClass();
functionObject.call(); // call1
int state1AfterCall1 = functionObject.getState1();
functionObject.call(); // call2
int state1AfterCall2 = functionObject.getState1();
What I'm asking is whether there is a difference between doing this:
public Something importantBlMethod(SomethingElse arg) {
if (convenienceCheckMethod(arg)) {
// do important BL stuff
}
}
private boolean convenienceCheckMethod(SomethingElse arg) {
// validate something
}
And this:
public Something importantBlMethod(SomethingElse arg) {
if (convenienceCheckMethod(arg)) {
// do important BL stuff
}
}
private static boolean convenienceCheckMethod(SomethingElse arg) {
// validate something
}
I actually use option 1 as it seems more natural to me.
So is there a style/convention/performance difference between the first and the second way ?
Thanks,
As suggested in the comments I tested it, in my benchmarks the dynamic method is faster.
This is the test code:
public class Tests {
private final static int ITERATIONS = 100000;
public static void main(String[] args) {
final long start = new Date().getTime();
final Service service = new Service();
for (int i = 0; i < ITERATIONS; i++) {
service.doImportantBlStuff(new SomeDto());
}
final long end = new Date().getTime();
System.out.println("diff: " + (end - start) + " millis");
}
}
This is the service code:
public class Service {
public void doImportantBlStuff(SomeDto dto) {
if (checkStuffStatic(dto)) {
}
// if (checkStuff(dto)) {
// }
}
private boolean checkStuff(SomeDto dto) {
System.out.println("dynamic");
return true;
}
private static boolean checkStuffStatic(SomeDto dto) {
System.out.println("static");
return true;
}
}
For 100000 iterations the dynamic method passes for 577ms, the static 615ms.
This however is inconclusive for me since I don't know what and when the compiler decides to optimize.
This is what I'm trying to find out.
Performance wise: The difference, if any, is negligible.
The rule of thumb is to declare your method static if it doesn't interact with any members of its class.
If the result of the function does not depend on anything but the arguments, it should be static. If it depends on an instance, make it an instance member.
It's not about performance; it's about semantics. Unless you're calling this function a million times a second, you will not notice a performance difference, and even then the difference won't be significant.
It all depends on the context. Generally static methods/variables are declared in a class so that an external class can make use of them.
If you are making a call to a local method then you should generally use instance methods rather than making static calls.
FYI, your syntax for calling the static method from an instance method is wrong. You have to supply the class name.
If your method requires instance data or calls to other instance methods, it must be an instance method.
If the function only depends on its arguments, and no other static data, then it might as well be an instance method too - you'll avoid the need to repeat the class name when you invoke the static function.
IMHO, there's no particular need to make the function static unless:
it's callable from other classes (i.e. not private), and
it doesn't refer to instance variables, and
it refers to other static class data
It might, it might not. It might be different between different executions of your code.
Here's the only thing that you can know without digging into the Hotsport code (or the code of your non-Hotspot JVM):
The static method is invoked with invokestatic, which does not require an object reference.
The instance private method is invoked with invokespecial, which does require an object reference.
Both of those opcodes have a process for resolving the actual method to invoke, and those processes are relatively similar (you can read the specs). Without counting the instructions of an actual implementation, it would be impossible to say which is faster.
The invokespecial pushes an extra value onto the stack. The time to do this is counted in fractions of a nanosecond.
And making all of this moot, Hotspot has a wide range of optimizations that it can perform. It probably doesn't have to do the actual method resolution more than once during your program's run. It might choose to inline the method (or it might not), but that cost would again be roughly equivalent.
According to me NO binding of static method is same as non-static private i.e early binding.
.
Compiler actually adds code of method (static or non-static private) to your code while creating it's byte code.
Update : Just came through this article. It says instance methods binding is dynamic so if method is not non-static private then. Your static method is faster.
I checked, I hope it does what you wanted to know, the code won't be beautiful:
public class main {
#SuppressWarnings("all")
public static void main(String[] args) {
main ma = new main();
int count = Integer.MAX_VALUE;
long beg = (new Date()).getTime();
for (int i = 0; i < count; i++) {
ma.doNothing();
}
System.out.println("priv : " + new Long((new Date()).getTime() - beg).toString());
beg = (new Date()).getTime();
for (int i = 0; i < count; i++) {
doNothingStatic();
}
System.out.println("privstat : " + new Long((new Date()).getTime() - beg).toString());
}
private void doNothing() {
int i = 0;
}
private static void doNothingStatic() {
int i = 0;
}
}
results:
priv : 1774
privstat : 1736
priv : 1906
privstat : 1783
priv : 1963
privstat : 1751
priv : 1782
privstat : 1929
priv : 1876
privstat : 1867
It doesn't look like dependent on static - nonstatic private method. I am sure the differences are coming from the current burden of the machine.
I take part in coding competitions and I have observed, that non-static methods are faster(however minimal) than the static methods. Of course, it depends on your use and the what the situation demands, but the static methods gives poorer performance as compared to non-static ones. By convention, you can use static methods for the ease of code, but creating an instance of the class and calling the method will give better performance.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
After reading Hidden Features of C# I wondered, What are some of the hidden features of Java?
Double Brace Initialization took me by surprise a few months ago when I first discovered it, never heard of it before.
ThreadLocals are typically not so widely known as a way to store per-thread state.
Since JDK 1.5 Java has had extremely well implemented and robust concurrency tools beyond just locks, they live in java.util.concurrent and a specifically interesting example is the java.util.concurrent.atomic subpackage that contains thread-safe primitives that implement the compare-and-swap operation and can map to actual native hardware-supported versions of these operations.
Joint union in type parameter variance:
public class Baz<T extends Foo & Bar> {}
For example, if you wanted to take a parameter that's both Comparable and a Collection:
public static <A, B extends Collection<A> & Comparable<B>>
boolean foo(B b1, B b2, A a) {
return (b1.compareTo(b2) == 0) || b1.contains(a) || b2.contains(a);
}
This contrived method returns true if the two given collections are equal or if either one of them contains the given element, otherwise false. The point to notice is that you can invoke methods of both Comparable and Collection on the arguments b1 and b2.
I was surprised by instance initializers the other day. I was deleting some code-folded methods and ended up creating multiple instance initializers :
public class App {
public App(String name) { System.out.println(name + "'s constructor called"); }
static { System.out.println("static initializer called"); }
{ System.out.println("instance initializer called"); }
static { System.out.println("static initializer2 called"); }
{ System.out.println("instance initializer2 called"); }
public static void main( String[] args ) {
new App("one");
new App("two");
}
}
Executing the main method will display:
static initializer called
static initializer2 called
instance initializer called
instance initializer2 called
one's constructor called
instance initializer called
instance initializer2 called
two's constructor called
I guess these would be useful if you had multiple constructors and needed common code
They also provide syntactic sugar for initializing your classes:
List<Integer> numbers = new ArrayList<Integer>(){{ add(1); add(2); }};
Map<String,String> codes = new HashMap<String,String>(){{
put("1","one");
put("2","two");
}};
JDK 1.6_07+ contains an app called VisualVM (bin/jvisualvm.exe) that is a nice GUI on top of many of the tools. It seems more comprehensive than JConsole.
Classpath wild cards since Java 6.
java -classpath ./lib/* so.Main
Instead of
java -classpath ./lib/log4j.jar:./lib/commons-codec.jar:./lib/commons-httpclient.jar:./lib/commons-collections.jar:./lib/myApp.jar so.Main
See http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html
For most people I interview for Java developer positions labeled blocks are very surprising. Here is an example:
// code goes here
getmeout:{
for (int i = 0; i < N; ++i) {
for (int j = i; j < N; ++j) {
for (int k = j; k < N; ++k) {
//do something here
break getmeout;
}
}
}
}
Who said goto in java is just a keyword? :)
How about covariant return types which have been in place since JDK 1.5? It is pretty poorly publicised, as it is an unsexy addition, but as I understand it, is absolutely necessary for generics to work.
Essentially, the compiler now allows a subclass to narrow the return type of an overridden method to be a subclass of the original method's return type. So this is allowed:
class Souper {
Collection<String> values() {
...
}
}
class ThreadSafeSortedSub extends Souper {
#Override
ConcurrentSkipListSet<String> values() {
...
}
}
You can call the subclass's values method and obtain a sorted thread safe Set of Strings without having to down cast to the ConcurrentSkipListSet.
Transfer of control in a finally block throws away any exception. The following code does not throw RuntimeException -- it is lost.
public static void doSomething() {
try {
//Normally you would have code that doesn't explicitly appear
//to throw exceptions so it would be harder to see the problem.
throw new RuntimeException();
} finally {
return;
}
}
From http://jamesjava.blogspot.com/2006/03/dont-return-in-finally-clause.html
Haven't seen anyone mention instanceof being implemented in such a way that checking for null is not necessary.
Instead of:
if( null != aObject && aObject instanceof String )
{
...
}
just use:
if( aObject instanceof String )
{
...
}
Allowing methods and constructors in enums surprised me. For example:
enum Cats {
FELIX(2), SHEEBA(3), RUFUS(7);
private int mAge;
Cats(int age) {
mAge = age;
}
public int getAge() {
return mAge;
}
}
You can even have a "constant specific class body" which allows a specific enum value to override methods.
More documentation here.
The type params for generic methods can be specified explicitly like so:
Collections.<String,Integer>emptyMap()
You can use enums to implement an interface.
public interface Room {
public Room north();
public Room south();
public Room east();
public Room west();
}
public enum Rooms implements Room {
FIRST {
public Room north() {
return SECOND;
}
},
SECOND {
public Room south() {
return FIRST;
}
}
public Room north() { return null; }
public Room south() { return null; }
public Room east() { return null; }
public Room west() { return null; }
}
EDIT: Years later....
I use this feature here
public enum AffinityStrategies implements AffinityStrategy {
https://github.com/peter-lawrey/Java-Thread-Affinity/blob/master/src/main/java/vanilla/java/affinity/AffinityStrategies.java
By using an interface, developers can define their own strategies. Using an enum means I can define a collection (of five) built in ones.
As of Java 1.5, Java now has a much cleaner syntax for writing functions of variable arity. So, instead of just passing an array, now you can do the following
public void foo(String... bars) {
for (String bar: bars)
System.out.println(bar);
}
bars is automatically converted to array of the specified type. Not a huge win, but a win nonetheless.
My favorite: dump all thread stack traces to standard out.
windows: CTRL-Break in your java cmd/console window
unix: kill -3 PID
A couple of people have posted about instance initializers, here's a good use for it:
Map map = new HashMap() {{
put("a key", "a value");
put("another key", "another value");
}};
Is a quick way to initialize maps if you're just doing something quick and simple.
Or using it to create a quick swing frame prototype:
JFrame frame = new JFrame();
JPanel panel = new JPanel();
panel.add( new JLabel("Hey there"){{
setBackground(Color.black);
setForeground( Color.white);
}});
panel.add( new JButton("Ok"){{
addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
System.out.println("Button pushed");
}
});
}});
frame.add( panel );
Of course it can be abused:
JFrame frame = new JFrame(){{
add( new JPanel(){{
add( new JLabel("Hey there"){{
setBackground(Color.black);
setForeground( Color.white);
}});
add( new JButton("Ok"){{
addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent ae ){
System.out.println("Button pushed");
}
});
}});
}});
}};
Dynamic proxies (added in 1.3) allow you to define a new type at runtime that conforms to an interface. It's come in handy a surprising number of times.
final initialization can be postponed.
It makes sure that even with a complex flow of logic return values are always set. It's too easy to miss a case and return null by accident. It doesn't make returning null impossible, just obvious that it's on purpose:
public Object getElementAt(int index) {
final Object element;
if (index == 0) {
element = "Result 1";
} else if (index == 1) {
element = "Result 2";
} else {
element = "Result 3";
}
return element;
}
I think another "overlooked" feature of java is the JVM itself. It is probably the best VM available. And it supports lots of interesting and useful languages (Jython, JRuby, Scala, Groovy). All those languages can easily and seamlessly cooperate.
If you design a new language (like in the scala-case) you immediately have all the existing libraries available and your language is therefore "useful" from the very beginning.
All those languages make use of the HotSpot optimizations. The VM is very well monitor and debuggable.
You can define an anonymous subclass and directly call a method on it even if it implements no interfaces.
new Object() {
void foo(String s) {
System.out.println(s);
}
}.foo("Hello");
The asList method in java.util.Arrays allows a nice combination of varargs, generic methods and autoboxing:
List<Integer> ints = Arrays.asList(1,2,3);
Using this keyword for accessing fields/methods of containing class from an inner class. In below, rather contrived example, we want to use sortAscending field of container class from the anonymous inner class. Using ContainerClass.this.sortAscending instead of this.sortAscending does the trick.
import java.util.Comparator;
public class ContainerClass {
boolean sortAscending;
public Comparator createComparator(final boolean sortAscending){
Comparator comparator = new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
if (sortAscending || ContainerClass.this.sortAscending) {
return o1 - o2;
} else {
return o2 - o1;
}
}
};
return comparator;
}
}
Not really a feature, but an amusing trick I discovered recently in some Web page:
class Example
{
public static void main(String[] args)
{
System.out.println("Hello World!");
http://Phi.Lho.free.fr
System.exit(0);
}
}
is a valid Java program (although it generates a warning).
If you don't see why, see Gregory's answer! ;-) Well, syntax highlighting here also gives a hint!
This is not exactly "hidden features" and not very useful, but can be extremely interesting in some cases:
Class sun.misc.Unsafe - will allow you to implement direct memory management in Java (you can even write self-modifying Java code with this if you try a lot):
public class UnsafeUtil {
public static Unsafe unsafe;
private static long fieldOffset;
private static UnsafeUtil instance = new UnsafeUtil();
private Object obj;
static {
try {
Field f = Unsafe.class.getDeclaredField("theUnsafe");
f.setAccessible(true);
unsafe = (Unsafe)f.get(null);
fieldOffset = unsafe.objectFieldOffset(UnsafeUtil.class.getDeclaredField("obj"));
} catch (Exception e) {
throw new RuntimeException(e);
}
};
}
When working in Swing I like the hidden Ctrl - Shift - F1 feature.
It dumps the component tree of the current window.
(Assuming you have not bound that keystroke to something else.)
Every class file starts with the hex value 0xCAFEBABE to identify it as valid JVM bytecode.
(Explanation)
My vote goes to java.util.concurrent with its concurrent collections and flexible executors allowing among others thread pools, scheduled tasks and coordinated tasks. The DelayQueue is my personal favorite, where elements are made available after a specified delay.
java.util.Timer and TimerTask may safely be put to rest.
Also, not exactly hidden but in a different package from the other classes related to date and time. java.util.concurrent.TimeUnit is useful when converting between nanoseconds, microseconds, milliseconds and seconds.
It reads a lot better than the usual someValue * 1000 or someValue / 1000.
Language-level assert keyword.
Not really part of the Java language, but the javap disassembler which comes with Sun's JDK is not widely known or used.
The addition of the for-each loop construct in 1.5. I <3 it.
// For each Object, instantiated as foo, in myCollection
for(Object foo: myCollection) {
System.out.println(foo.toString());
}
And can be used in nested instances:
for (Suit suit : suits)
for (Rank rank : ranks)
sortedDeck.add(new Card(suit, rank));
The for-each construct is also applicable to arrays, where it hides the index variable rather than the iterator. The following method returns the sum of the values in an int array:
// Returns the sum of the elements of a
int sum(int[] a) {
int result = 0;
for (int i : a)
result += i;
return result;
}
Link to the Sun documentation
i personally discovered java.lang.Void very late -- improves code readability in conjunction with generics, e.g. Callable<Void>