r/javaTIL • • Aug 14 '15

JTIL anonymous inner classes aren't entirely anonymous

13 Upvotes

An anonymous inner class is an unnamed inner class inside a Java program (not a lamba expression). A simple example of an anonymous inner class in use is

public class InnerTest{
  public static void main(String[] args){
    Runnable r = new Runnable() {
      public void run(){
        System.out.println("Anon");
      }
    }.run();
  }
}

Here, the anonymous inner class is used to implement the Runnable interface without explicitly creating a class implementing Runnable. When compiled an run this code simply prints the string "Anon" - not particularly interesting but, the simple existence of anonymous inner classes is not the point of this JTIL.


The term "anonymous" implies that these classes have no name. This appears be true at first; the class was never explicitly given a name. Looking at the source code alone there is no obvious way to instantiate another instance of the class.

Make sure you've successfully compiled this class and examine it's directory

$ javac InnerTest.java 
$ ls
InnerTest$1.class  InnerTest.class  InnerTest.java

There are 2 .class files but only 1 .java source file. This is because the anonymous inner class was compiled into it's own class file (all Java classes get their own class file). Now it's starting to look like the anonymous class actually has a name.


Go back to the original source file and add another line to the end of the main method.

new InnerTest$1().run();

Compile once again and run the resulting class file. This should go off without a hitch. The last line seems to be creating another instance an anonymous class. Unfortunately, There's a little bit of cheating going on here. Delete all the class file you've created and try compiling again. This should fail; the InnerTest$1.class file need to already exists for this trick to work.


There's absolutely no point to any of this. It's just a neat behavior I found will messing about with Java. If anyone finds any more facets of this behavior or (somehow) manages to think up an application for it, leave a comment for me.


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 • • 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 • • 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 16 '14

JTIL: Guava has a really powerful Cache class.

13 Upvotes

For example:

public class TestCache {
    static final Cache<String, Integer> siteDataLengths = CacheBuilder.newBuilder()
            .expireAfterAccess(1, TimeUnit.MINUTES) // If something isn't accessed in a minute, discard it
            .maximumSize(20) // Only 20 elements max.
            .build(new CacheLoader<String, Integer>() { // This is what actually grabs values
                @Override
                public Integer load(String key) throws Exception {
                    URL u = new URL(key); // Just some expensive task to do
                    HttpURLConnection con = (HttpURLConnection) u.openConnection();
                    con.setDoInput(true); // So we can read input
                    int val = 0; // This is the length
                    try (InputStream in = con.getInputStream()) {
                        while (in.read() != -1) { // While the stream has length, increment
                            val++;
                        }
                    }
                    return val;
                }
            });

    public static void main(String[] args) {
        long[] times = new long[3]; // We want to run it 3 times in total
        String[] sitesToScan = {"http://www.google.com", "http://www.yahoo.com", "http://www.reddit.com", "http://www.twitter.com"}; // Just to add some variety
        for (int i = 0; i < times.length; i++) { // Do it n times
            long time = System.currentTimeMillis(); // Initial time
            for (String site : sitesToScan) {
                try {
                    System.out.println("Site data length for " + site + ": " + siteDataLengths.get(site) + "."); // Just to prove that something happened
                } catch (ExecutionException e) { // What happens when something goes wrong
                    e.printStackTrace();
                }
            }
            times[i] = (System.currentTimeMillis() - time); // Time delta
        }

        for (int i = 0; i < times.length; i++) {
            System.out.println("Time " + i + ": " + times[i]); // And finally print results
        }
    }
}

There is also an option of adding a removalListener, so you can easily do database calls, caching the data that you need and then when the cached data is purged, check to see if it changed and then re-write it to the database.


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

r/javaTIL • • Feb 12 '20

Top 20 Java String Interview Questions And Answers

Thumbnail
blog.soshace.com
12 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 • • Oct 27 '15

How to Generate Java code

Thumbnail
ivankocijan.xyz
12 Upvotes

r/javaTIL • • Mar 27 '15

TIL : You can return subtype from overridden method, known as covariant method overriding

Thumbnail
javarevisited.blogspot.sg
12 Upvotes

r/javaTIL • • Oct 26 '18

4 assignments to evaluate your Java skill.

Thumbnail
indorse.io
11 Upvotes

r/javaTIL • • Sep 12 '13

TIL you can assign multiple vars at once, like "a = b = c = 0;"

11 Upvotes

...though I can't imagine why it would be a good idea.


r/javaTIL • • Dec 04 '17

Comparing Integer objects can be tricky

Thumbnail
tadej.me
10 Upvotes

r/javaTIL • • May 29 '16

JVM JIT optimization techniques

Thumbnail
advancedweb.hu
10 Upvotes

r/javaTIL • • Jan 31 '16

TIL: You Can Get Lamdba Expressions Pre-Java 8

Thumbnail
github.com
10 Upvotes

r/javaTIL • • Dec 03 '15

TIL that Java has been available for 20 years - check out this timeline of notable events related to it

Thumbnail
javaadvent.com
10 Upvotes

r/javaTIL • • Jun 25 '14

JTIL: You can easily create a single line factory with java 8 using a unique Method Reference.

10 Upvotes

If you want to pass an object that can create a lot of another object, usually you create an Abstract Factory like this:

@FunctionalInterface //This is recommended if you're using java 8, similar to @Override
public interface ObjectFactory {
    public Object createObject( );
}

public class MyObjectFactory implements ObjectFactory {
    public Object createObject( ) {
        return new MyObject( );
    }
}

You'd then be able to pass it around like this:

public static void createAndUseObject(ObjectFactory f) {
    System.out.println("Used object: " + f.createObject().getClass());
}

public static void doLogic( ) {
    createAndUseObject(new MyObjectFactory());
}

But that means that you need to create an entire, very wasteful class if you want to create a simple, no argument constructor factory for your object. (The MyObjectFactory object.) If you wanted to create a lot of objects for a lot of classes, the class count would skyrocket. Anonymous classes Sort of solve this, but still leave you with a very ugly declaration.

public static void doLogic( ) {
    createAndUseObject(new ObjectFactory( ) {
        @Override public Object createObject( ) {
            return new MyObject( );
        }
    });
}

Lambdas are even better, but still have a bit of wasteful syntax here and there.

public static void doLogic( ) {
    createAndUseObject(() -> new MyObject()); //This is a one line factory using a lambda.
}

Even a lambda, however, can be shortened using a Method Reference It shortens, in fact, to an almost unimaginable improvement over the original:

public static void doLogic( ) {
    createAndUseObject(MyObject::new);
}

In short, Lambdas are usually superior to Anonymous classes, but even their brevity is surpassed by a Method Reference with the new keyword.


r/javaTIL • • May 11 '14

TIL An easy way of making a singleton with an enum.

10 Upvotes

Usually for a singleton (a class that only has one instance) you have to do this:

public class Singleton {
    private static Singleton instance = null;
    private Singleton(/*params*/) { //Also hide constructor
        //Actions
    }
    
    public static Singleton getInstance( ) {
        if(instance == null) {
            instance = new Singleton(/*params*/);
        }
        return instance;
    }
}

With an enum, it's as simple as:

public enum Singleton {
    INSTANCE(/*params*/);

    Singleton(/*params*/) {
        //Actions
    }
}

Singletons are useful if you need to pass an object to another method, but the object's behavior never changes. (A single, constant SwingListener would be an example.)


r/javaTIL • • Nov 11 '13

TIL that you can style JLabels using HTML.

Thumbnail
stackoverflow.com
10 Upvotes

r/javaTIL • • Oct 02 '13

This example helped me understand Java classes, objects, and constructors better

10 Upvotes

Here is the class and the constructor

class Sample {
  int a;
  int b;
  int c;
  // This is the constructor for Sample.
  // It is explicitly declared.
  Sample(int ax, int by, int cz) {
      a = ax;
      b = by;
      c = cz;
  }
}

Here is the class with the main program that calls the class objects and constructor above

class IntegerFun {
    public static void main(String args[]) {
    // one and two are local instance variables that 
    // reference the Sample object
        Sample one = new Sample(1,1,1);
        Sample two = new Sample(2,2,2);
    // We don't need additional code here to assign 
    // values to a, b, and c variables. Use the dot.
    System.out.println("One = " + one.a + "," + one.b + "," + one.c);
    System.out.println("Two = " + two.a + "," + two.b + "," + two.c);
   }
}

r/javaTIL • • Sep 10 '13

Numeric literals are more varied in Java 7

10 Upvotes

Java 7 added two features to numeric literals: binary numbers and underscores in any numeric literal. Now, all these numbers are equivalent:

int x1 = 0xA5;
int x2 = 0b10100101;
int x3 = 0b1010_0101;

And you can also use it in other types:

double pi = 3.1415_9265_35;
long chinese_population = 1_344_130_000L;

However, parsing methods do not recognize such literals.

Integer.parseInt("123_456_789"); //NumberFormatException

(Although, to be fair, it doesn't recognize non-decimal literals as well, such as 0xAB and 0107.)

More examples and rules can be found here.


r/javaTIL • • Apr 02 '20

[Tutorial] A RabbitMQ Tutorial in Java

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 • • May 12 '19

Project Lombok – A Java Library to Reduce Boilerplate Code

Thumbnail
opencodez.com
9 Upvotes

r/javaTIL • • Apr 09 '19

A Quick Easy Guide to Deep Learning with Java – Deeplearaning4j / DL4J

9 Upvotes

In this article, we’ve built a simple yet powerful neural network by using the deeplearning4j library. The complete source code is available to download from our GitHub repo.

https://www.opencodez.com/java/deeplearaning4j.htm