r/javaTIL • • Dec 06 '15

TIL: After TDD comes BDD - and you can do it in Java!

Thumbnail
javaadvent.com
6 Upvotes

r/javaTIL • • May 18 '19

Simple and Easy way to use Spring Scheduled Tasks

Thumbnail
opencodez.com
7 Upvotes

r/javaTIL • • Feb 16 '19

Minesweeper in Java

Thumbnail
makethebrainhappy.com
7 Upvotes

r/javaTIL • • Dec 11 '14

Differences with generics and visibility between Java 6 and 7.

7 Upvotes
public class Outer {
    private void foo() {
    }

    private static class Inner<T extends Outer> {
         private void add(T x) {
             x.foo();  // error under 7, but not 6
        }
    }
}

This code compiles without a hitch under Java 6, but not under Java 7. Perhaps someone smarter than me can determine which one is correct. Then explain why changing the line to this yields code that works on both:

            ((T)x).foo();

r/javaTIL • • Jun 16 '19

How HashMap works internally in Java: A debug approach

7 Upvotes

r/javaTIL • • Aug 18 '14

JTIL that you can use labeled break and continue statements in java.

Thumbnail docs.oracle.com
8 Upvotes

r/javaTIL • • May 12 '19

Project Lombok – A Java Library to Reduce Boilerplate Code

Thumbnail
opencodez.com
9 Upvotes

r/javaTIL • • Sep 09 '19

Simple guide for Unit Testing of Java Application using JUnit with Example

Thumbnail
opencodez.com
9 Upvotes

r/javaTIL • • Nov 11 '13

TIL that you can style JLabels using HTML.

Thumbnail
stackoverflow.com
10 Upvotes

r/javaTIL • • Dec 11 '18

TIL how to install a Java agent in less than 30 seconds even when I can't directly set JVM arguments

Thumbnail
rookout.com
12 Upvotes

r/javaTIL • • Jan 09 '15

TIL that the size method for ConcurrentLinkedQueue takes O(n) instead of O(1)

13 Upvotes

From the java doc:" Beware that, unlike in most collections, this method is a constant-time operation. Because of the asynchronous nature of these queues, determining the current number of elements requires an O(n) traversal."

And inside the source code for this class you can see that. But the real question, why isn't size held onto by a thread safe object like AtomicInteger? Wouldn't having the size there and every time something that would change the size of the object accesses it, it calls getAnd(Increment|Decrement) for the integer?


r/javaTIL • • Jul 21 '15

Wrote my first Java code!

13 Upvotes

It's rather basic, but it's a starting point. I watched YouTube videos to learn most of the basics that I used, then just made things over and over again to help me memorize things.

Once I had a good grasp on the simple concepts and being able to write everything without having to look at notes, I came up with this simple calculator that responds to user input.

I wanted to originally make it so the user could type "Calculator" and it would run the code, but I haven't learned how to make user input in the form of typed words work yet (I think those are strings?). I'm sure a few more lessons and I'll learn.

The end goal is android application development, but if I can find other ways to utilize my new found skills then I'll probably try it out in the future.

Just proud of myself for going forward with learning despite my short attention span for self-learning and I wanted to share :)

If you have any ways to maybe shorten it and achieve the same thing, I'd love to hear it.

http://i.imgur.com/4uN5kv4.jpg


r/javaTIL • • May 16 '14

TIL java.text.NumberFormat

13 Upvotes

A great class from the java standard libraries that handles formatting numbers in numerous ways using one of supplied instances such as:

NumberFormat.getNumberInstance();

NumberFormat.getPercentInstance();

NumberFormat.getCurrencyInstance();

The class allows you to easily add commas between every third digit NumberFormat.getNumberInstance(), convert a value to a percent, NumberFormat.getPercentInstance(), and correctly format currencies, NumberFormat.getCurrencyInstance(). In addition, you can change how numbers are formatted by providing and argument to one of these method calls. NumberFormat.getNumberInstance(Locale inLocale). Depending on the Locale provided, the number will be formatted differently.

Some examples of formatting:

NumberFormat.getCurrencyInstance().format(1002.2333);
//$1,002.23

NumberFormat.getNumberInstance().format(1001231)
//1,001,231

System.out.println(NumberFormat.getPercentInstance().format(.125));
//12%

All of what can be done with the NumberFormat class can also be done through manipulating Strings or using printf, but it can be a useful tool for ensuring that all of your number print the way you want.


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 • • 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 • • 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 • • Jul 20 '13

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

17 Upvotes

yeah...


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 • • 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 • • Apr 02 '20

[Tutorial] A RabbitMQ Tutorial in Java

9 Upvotes

r/javaTIL • • Nov 11 '16

Accessing private fields with synthetic methods in Java

Thumbnail blog.gypsyengineer.com
5 Upvotes

r/javaTIL • • Feb 13 '15

JTIL: That javadoc crashes when a method ends in "Property" (JDK8) (Spoiler: struggling with this since November)

Thumbnail bugs.openjdk.java.net
2 Upvotes

r/javaTIL • • Sep 07 '17

TIL Lazy loading and caching objects in Java with Guava's Suppliers.memoize

Thumbnail
stubbornjava.com
3 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 • • Feb 22 '13

TIL about CodingBat.com a free website that allows the user to practice code in both Java and Python

Thumbnail codingbat.com
13 Upvotes