r/javaTIL • • May 12 '14

TIL enums can implement interfaces, and each enum value can be an anonymous class.

49 Upvotes

For example:

public enum MyEnum implements Runnable {
    PRINT_HELLO {
        @Override //Override is optional here, really.
        public void run( ) {
            System.out.println("hello"); //Action
        }
    }, //Comma for all but the last element
    PRINT_GOODBYE { //Some more examples
        @Override
        public void run( ) {
            System.out.println("goodbye");
        }
    },
    PRINT_FIZZ {
        @Override
        public void run( ) {
            System.out.println("fizz");            
        }
    }; //Semicolon here


    static {
        Executors.newCachedThreadPool().submit(PRINT_HELLO); //This is just an implementation. Executors will be in a future TIL.
    }
}

This can be very useful if you want a list of very simple implementations of your interface. Packet listeners, for example, or default arithmetic operations. With java 8 or guava, you can define your own Function and Predicate values if you want to re-use a simple predicate multiple times.

A predicate version:

public enum TestEnumPredicates implements Predicate<String> {
    IS_UPPER_CASE {
        @Override
        public boolean test(String s) {
            for (char c : s.toCharArray()) {
                if (!Character.isUpperCase(c)) {
                    return false;
                }
            }
            return true;
        };
    },
    IS_LOWER_CASE {
        @Override
        public boolean test(String s) {
            for (char c : s.toCharArray()) {
                if (!Character.isLowerCase(c)) {
                    return false;
                }
            }
            return true;
        };
    },
    IS_ODD_LENGTH {
        @Override
        public boolean test(String s) {
            return (s.length() % 2) != 0;
        };
    };

    public static void main(String[] args) {
        ArrayList<String> myStrings = new ArrayList<String>();
        myStrings.add("herp");
        myStrings.add("DERPA");
        myStrings.add("fIzZ");
        myStrings.add("$#!");
        for (String s : args) {
            myStrings.add(s);
        }
        myStrings.stream().filter(IS_UPPER_CASE).forEach(new Consumer<String>() {
            @Override
            public void accept(String t) {
                System.out.println("Upper case: " + t);
            }
        });
        myStrings.stream().filter(IS_LOWER_CASE).forEach(new Consumer<String>() {
            @Override
            public void accept(String t) {
                System.out.println("Lower case: " + t);
            }
        });
        myStrings.stream().filter(IS_ODD_LENGTH).forEach(new Consumer<String>() {
            @Override
            public void accept(String t) {
                System.out.println("Odd length: " + t);
            }
        });
    }
}

You'll notice that it's a very readable, and very compact way of defining very different, but related interfaces in a single class.

I'm officially going to try to do a once-per-day java TIL to make this subreddit more interesting. If you have any comments, or better examples, make sure to reply. I'll edit my posts if any of my information is incorrect or outdated.


r/javaTIL • • Jun 28 '14

JTIL: You can break to an outer loop with a label.

25 Upvotes

Let's say you have the following code:

for(int xl = minX; xl < maxX; xl++) { //Loop through X coordinates
    for(int yl = minY; yl < maxY; yl++) { //Loop through Y coordinates
        if(xl == x && yl == y) { //We've found a point that exactly matches the one we want
            System.out.println("Found our point!");
            //Now we need some way to exit this loop? a break; would only break the inner loop and we'd keep going.
        }
    }
}
//Continue execution

And you want to exit both loops when you find the point you were looking for. I've seen people add a boolean in the outer one and an && !exiting in the declaration of the for loop. There is a better way, however, with a Label. Consider the following code.

outerloop: //The label.
for(int xl = minX; xl < maxX; xl++) { //Loop through X coordinates
    for(int yl = minY; yl < maxY; yl++) { //Loop through Y coordinates
        if(xl == x && yl == y) { //We've found a point that exactly matches the one we want
            System.out.println("Found our point!");
            break outerloop; //Break to the label. Simple!
        }
    }
}
//Continue execution

You can also use a 'continue label' statement, which is just the 'continue' form of this tip:

outerloop:
for(int i = 0; i < 10; i++) {
    for(int j = 0; j < 10; j++) {
        if(i == 0 && j == 3) {
            continue outerloop; //This will skip the loop iterations where i=0 and j=3-9 exclusively.
        }
    }
}

There are two things to be aware of, however:

  1. You can only put labels on loops and if statements.

  2. You can make extremely confusing code if you use break or continue labels as a makeshift 'goto', and people subsequently reading your code will probably try to strangle you.


r/javaTIL • • Feb 11 '15

JTIL: You can cast null.

24 Upvotes

Example:

myMethod((Foo) null);

I just learned this today while following an Android development tutorial.

Apparently a use case for it is for when you need to specify a particular implementation of an overloaded method, while passing a null parameter.

Consider:

public void myMethod(String s) {/* ... */}

public void myMethod(String... s) {/* ... */}

And I made the call:

myMethod(null);

Which implementation would be chosen?

You can specify which implementation by casting null:

myMethod((String[]) null);

Pretty cool if you ask me.


r/javaTIL • • Nov 18 '13

TIL you can pass optional or multiple arguments using '...'

23 Upvotes

It automatically puts the arguments into an array. So for example:

hello("Hello", "My", "Name", "Is", "Not", "Mangopearapples");

public void hello(String... s){
    // s is an array storing the all of the arguments
}

r/javaTIL • • Apr 11 '15

JTIL String.chars()

20 Upvotes

I was using Streams in one of my programs and I found myself wanting to create a Stream of a String. My first instinct of how to do this was to calls Stream.of("String".toCharArray()); , but there's a better way.

The class CharSequence provides the method chars() which returns a stream of characters (represented as integers).


This makes a few string operations quite a bit simpler. For instance, filtering a String on a predicate is as simple as

String test = "@te&st()in%g1*2$$3"
String filtered = test.chars()
                      .filter(Character :: isAlphaNum)
                      .reduce(Collectors.joining());

//filtered now holds "testing123"

r/javaTIL • • Oct 17 '14

TIL you can instantiate int i = 0; before a for loop and leave that space blank inside the for loop

19 Upvotes

Ex: for(; i< bar; i++){

//does something

}//end of for loop

Also you can omit the i++

for(;i< bar;){

//does something

i++;

}//end of for loop

Or you can just make an infinite for loop

for( ; ;){

//runs forever

}//end of for loop


r/javaTIL • • Oct 25 '18

Project Lombok – A Java Library to Reduce Boilerplate Code

Thumbnail
opencodez.com
17 Upvotes

r/javaTIL • • Jan 08 '16

JDK 9 Javadoc now has a search box

Thumbnail download.java.net
17 Upvotes

r/javaTIL • • Jul 20 '13

TIL that this sub-reddit is seriously lacking posts...

17 Upvotes

yeah...


r/javaTIL • • Apr 26 '19

101 Most Important Frequently Asked Core Java Interview Questions to Ace an Interview – Part 2

Thumbnail
opencodez.com
16 Upvotes

r/javaTIL • • Nov 06 '18

Enums can have interfaces

16 Upvotes

And interfaces can have default methods. And that means that enums with a similar use can avoid copy-pasting code, by implementing the appropriate interface.

Oh boy.

I love enums. They're a great tool for ensuring something exists exactly once, but maybe it has a few brothers and sisters.

What I hate about enums is that Java refuses to let us subclass them, and refuses to let us inherit from a class of our own choice, because it already inherits from a class by design, and Java refuses to allow multiple inheritance.

The pain is great and has led to duplicate code in my past.

Until today. Because today I learned from people on StackOverflow that enums can implement interfaces.

I should have realized that years ago. But I'm happy to know it now, and I hope some of you will be helped by this, as well.

Happy coding!


r/javaTIL • • Aug 08 '16

TIL: You Can Declare A Method To Look Like An Array!

16 Upvotes

Apologies if this is old news for everybody else.

But today, while thumbing through the Java SE Language Specification [as I do sometimes whenever I'm in the mood for some light reading] I stumbled across this enthralling stanza of prose...


"...For compatibility with older versions of the Java SE platform, the declaration of a method that returns an array is allowed to place (some or all of) the empty bracket pairs that form the declaration of the array type after the formal parameter list. This is supported by the following obsolescent production, but should not be used in new code..."


MethodDeclarator:
    MethodDeclarator [ ]

Translation: This is legal Java code...


public int learnSomethingNewEveryDay( )[][]  {

    int[][] whoKnew = {{612, 777}, {93, 11}};

    return whoKnew;
}

Has anybody ever seen this mentioned in this forum before?


r/javaTIL • • Oct 18 '18

Oracle's Java 11 trap - Use OpenJDK instead!

Thumbnail
blog.joda.org
15 Upvotes

r/javaTIL • • Apr 20 '16

Stop converting time units the wrong way

Thumbnail
ivankocijan.xyz
15 Upvotes

r/javaTIL • • Mar 30 '15

[TIL] Calling static methods on null instances doesn't result in a NPE

15 Upvotes
public static void main(String[] args)
{
	((NullThing) null).printThing();
}

public static class NullThing
{
	public static void printThing()
	{
		System.out.println("Hai");
	}
}

This is valid code that will not throw an exception. We discovered this today as we have been dealing with static methods and inheritance.

The question came up "Can we call static methods on null" The answer is a resounding yes.

(Please don't do this. Please use the class the call static methods).


r/javaTIL • • Jun 06 '14

JTIL: You can use static blocks to execute code when a class is loaded.

15 Upvotes

I thought it would be better to separate this tip from my last one, if you for example wanted to use /u/king_of_the_universe's suggestion and wanted to use the return void Arrays.fill method to fill a character array, you could do this:

private static final char[] VERTICAL_LINES = new char[100];

static { //This is the static block, it will only be executed once.
    Arrays.fill(VERTICAL_LINES, '|');
}

The only note I have for this is that you can't set final fields in these blocks, you HAVE to use a method to set final fields.


r/javaTIL • • May 15 '14

JTIL: The java compiler turns all primitives not in arrays into ints, longs, floats, doubles, and objects.

15 Upvotes

Which means behind the scenes there is no memory footprint difference between these two classes:

public class ClassOne {
    byte bval;
    short sval;
    public ClassOne(byte val) {
        this.bval = val;
        this.sval = val;
    }
}

and this one:

public class ClassTwo {
    int val1;
    int val2;
    public ClassTwo(int val) {
        this.val1 = val;
        this.val2 = val;
    }
}

(This information is incorrect, as there is actually a difference for fields, but not for local variables or parameters on the stack.)

Better example:

public void doSomething( ) {
    int a = 9; //These are both pushed onto the stack as ints
    byte b = 9;
}

If you use a conversion, however, it adds another instruction that will limit the size of your variable artifically. (byte)i will still be -128 to 127, even though it uses the entire 4 byte memory space.


r/javaTIL • • May 13 '14

JTIL: Java 7 has a really simple way of automatically closing things in a try block.

15 Upvotes

It's called try-with-resources

An example would be:

try(FileReader fr = new FileReader(new File("my/file/path")); InputStreamReader in = new InputStreamReader(System.in)) { //You can add as many resources as you want here.
    in.read();
    fr.read();
} catch (IOException e) {
    e.printStackTrace( );
}  //No need for a finally { block here, both readers will be automatically closed.

You can even define your own classes with this functionality, with the AutoCloseable interface:

public class MyCloseable implements AutoCloseable {
    @Override
    public void close( ) {
        //Free resources
    }
}

r/javaTIL • • Apr 26 '19

101 Most Important Frequently Asked Core Java Interview Questions to Ace an Interview – Part 1

Thumbnail
opencodez.com
14 Upvotes

r/javaTIL • • Sep 18 '16

TIL Java BigInteger was made for RSA cryptography

Thumbnail nayuki.io
14 Upvotes

r/javaTIL • • Jan 27 '15

TIL there is an easy alternative to the finally when it comes to closing resources

14 Upvotes

Automatic resource management was implemented in java 7

try( // The resources you want to use seperated by a semicolon) { ... } // rest of the code

for more information: here


r/javaTIL • • May 30 '14

TIL: You can write the main function like this: public static void main(String... args)

14 Upvotes

r/javaTIL • • May 13 '14

TIL The ?: Operator

14 Upvotes

I didn't learn about this today, but recently a lot of people in my Java class have asked questions about it upon seeing it in my code.
The ?: operator, also known as the Ternary If, is used as a shortcut for conditional statements, and is most commonly used when assigning a value based of a Boolean, for example, finding the maximum of two numbers.

For both cases, lets assume we have num1 and num2 like this:

    int num1 = 10;
    int num2 =  8;

This code uses or ?: operator to assign the maximum of the two values to num3 in one line.

    int num3 = (num1>num2)?num1:num2;

The following code would do the same operation without the use of this operator.

    int num3;
    if(num1>num2)
        num3=num1;
    else
        num3=num2;

The first option, is much shorter, but more importantly, it is more readable. I'm sure some people don't agree with me about the readability, so if you're one of those people, just do whatever you think makes your code better.

Another trick I've found for this is displaying text where you might have plurals.

   Random rand = new Random();
   int numCats = rand.nextInt(10);
   System.out.println("I have " + numCats + ((numCats>1)?"cats.":"cat.")); 

This display looks better than the way many people might go:

   System.out.println("I have " + numCats + "cat(s).");

Of course, you can use this to display whatever text you want. It can be great if you have a message you want to display when you print a null object, rather than 'null'.

   String str = null;
   System.out.println("The String says: " + (str==null?"nothing!":str));

Ending notes: I typed all the code samples directly into reddit, so if something is wrong tell me and I'll fix it.

While you can nest these statements ,((x>y)?((x>z)?x:z):((y>z)?y:z)), please don't do it; it is impossible to read.

Edit: Included the actual name of the operator as mentioned by /u/TheOverCaste
Added link to the wikipedia article, Ternary Operator


r/javaTIL • • Jan 09 '18

TIL I've been making a mistake that the guidelines specifically tell us not to:

Post image
13 Upvotes

r/javaTIL • • Mar 03 '17

TIL that the ArrayList returned by Arrays.asList(T...) is not java.util.ArrayList but its own version

13 Upvotes

If you want an ArrayList that can add objects etc, then use new ArrayList()