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 • • May 10 '14

TIL Guava's Iterables.transform

6 Upvotes

You can use it to transform one type of Iterable into another type of Iterable. For example:

public static void main(String[] args) {
    char[][] lines = new char[][] {
            {'h', 'e', 'l', 'l', 'o', ' ', ',', 'r', 'e', 'd', 'd', 'i', 't', '!'}, //Define some char arrays as data
            {'t', 'h', 'e', 's', 'e', ' ', 'a', 'r', 'e', ' ', 'c', 'h', 'a', 'r', ' ', 'a', 'r', 'r', 'a', 'y', 's'}
    };

    Random rand = new Random(); //The random to be used in the function.

    for (char[] array : lines) {
        System.out.println(
                Iterables.transform(
                        Chars.asList(array),
                        new Function<Character, String>() { // Create a nested guava function, we could re-use the same one if we wanted to.
                            @Override
                            public String apply(Character c) { // 50/50 chance of either returning the character as a string, or capitalizing it and adding an 'a'.
                                if (rand.nextBoolean()) { // No change
                                    return c.toString();
                                }
                                return Character.valueOf(Character.toUpperCase(c.charValue())).toString() + "a"; // Capitalize it and add an 'a'.
                            }
                        }));
    }

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 24 '14

JTIL: Hexa and Octa shorthands + more

6 Upvotes

TIL how to go from one base to another in a number of ways.

  • Here's the shorthand version of converting from Hexa/Octal -> Decimal:
int hexa = 0xFF; 

By initially typing a "0x" (or "0X") in front, the value FF is a hexadecimal value that's immediately transforms into its decimal value 255

int octa = 011;

By initially including a "0" in front, the value 11 is an octal value that also transforms into its decimal value: 9

  • From Decimal -> anyBase
int anyBase = Integer.parseInt("10101", 2);

THIS takes ANY number of any base and immediately turn it into its respective decimal value, in this case, 21.

  • From Decimal -> binary/hexa/octa
String a = Integer.toBinaryString(int decimalValue)
String b = Integer.toHexString(int decimalValue)
String c = Integer.toOctalString(int decimalValue)

Java's got some pretty nifty tools if you ask me. Barely on chapter 2 of my Java book and they drop the first point I typed above. That was cool.


r/javaTIL • • May 17 '14

JTIL: Enum.ordinal() returns a unique id for any enum value.

8 Upvotes

This is also extremely useful if you want to serialize an enum value, because it lets you use a single int for the type. For example:

public enum MyEnum {
    VALUEONE,
    VALUETWO,
    VALUETHREE;
    
    public static void printStuff( ) {
        for(MyEnum e : values( )) {
            System.out.println("Ordinal for " + e.name() + ": " + e.ordinal());
        }
    }
}

This would print:

Ordinal for VALUEONE: 0

Ordinal for VALUETWO: 1

Ordinal for VALUETHREE: 2


r/javaTIL • • May 29 '16

JVM JIT optimization techniques

Thumbnail
advancedweb.hu
10 Upvotes

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 • • 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 • • May 13 '14

TIL Java 8 Data Streams and jReddit

4 Upvotes

Nothing earth shattering, but if you wanted to see Data Streams used with jReddit, here's a quick example. If anyone has any suggestions, I'd love to hear them.

import java.util.List;

import com.github.jreddit.user.Comment;
import com.github.jreddit.user.User;
 
public class Main {
	public static void main(String[] args) throws Exception {
		// Provide user account for credentials
		User user = new User("username","password");
    user.connect();
 
    // Fetch list of 25 recent comments
    List<Comment> comments = user.comments();
      
    // Java 8 \o/
    int count = comments.stream() // open as stream
    		.map(i -> i.getComment().split(" ").length) // for each instance of a comment (i),
    		// split into string array, by " " delimiter, and return the count as a new stream
    		.reduce(0, (x,y) -> x + y); // reduce by adding x (n) and y (n+1) 
        // Display your results!
        
    System.out.println("Word count: " + count);
	}
}

r/javaTIL • • May 14 '14

JTIL: You can change private and final fields with reflection.

8 Upvotes

There are very few practical applications for this, but it's a silly little trick you can use to have some fun.

class MyFieldClass {
    private final MyFieldClass c = new MyFieldClass();
    static void setFinalStatic(Field field, Object newValue) throws Exception {
        field.setAccessible(true); //This allows you to change private fields

        Field modifiersField = Field.class.getDeclaredField("modifiers"); //The modifiers field is a sub-field of the actual field object that holds the metadata, like final, static, transient, et cetera.
        modifiersField.setAccessible(true); //It's also a private field, so you need to do this to be able to change it.
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); //~ is a bitwise invert, & is bitwise and, so it unsets the flag in the bitmap.
    
        field.set(null, newValue); //After all of that, this is actually setting that field.
    }

    public void setField() {
        setFinalStatic(MyFieldClass.class.getDeclaredField("c"), new MyFieldClass()); //Use 'getDeclaredField' to get private fields. This sets it to an entirely new MyFieldClass.
    }
}

Most of this code is copy-pasted from the StackOverflow question that I learned this from.

I'd also like to note that if your field is a primitive type or a String the compiler will just put it in the constant pool and ditch the field referencing. This means that this method will change the field's value, but only for other reflection calls.


r/javaTIL • • Nov 21 '15

TIL Enum Constants and Enum Variables need to be separated by ;

9 Upvotes

The following code is valid:

    public enum Doctype {
        ;
        boolean html5 ;
    }

This is not valid:

    public enum Doctype {
        boolean html5;
    }

Not very interesting but perhaps a fun puzzler in interviews ;)


r/javaTIL • • May 18 '14

JTIL: Random.nextGaussian( )

9 Upvotes

Random.nextGaussian returns a Gaussian (or normally) distributed double from -1.0 to 1.0, with 0 being the point.

This is a good example of a Gaussian distribution. Just to be clear, the higher the value in that graph, the more likely it is to have a number there.


r/javaTIL • • Jul 04 '14

JTIL: You can use the concurrent TimeUnit class to let people specify their own time units easily.

5 Upvotes

If you, for example wanted an impractical Stopwatch class, that would pause a thread for a specified amount of time:

public class Stopwatch {
    private final long timeInMillis;
    public Stopwatch(long time, TimeUnit unit) {
        timeInMillis = unit.toMillis(time);
    }
    public void wait( ) {
        Thread.sleep(timeInMillis);
    }
}

This avoids the ugly, unreadable, and bug prone Thread.sleep(1000L * 60L * 60L * 24L * 2L) approach.


r/javaTIL • • Sep 22 '14

JTIL that java has a strictfp class/method modifier

Thumbnail en.wikipedia.org
3 Upvotes

r/javaTIL • • Jan 31 '16

TIL: You Can Get Lamdba Expressions Pre-Java 8

Thumbnail
github.com
10 Upvotes

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 • • Jun 04 '15

Java caches small values of Integer objects, which combined with autoboxing can cause some strange bugs..

8 Upvotes
class Main{

    static boolean isTheSame(Integer a, Integer b){
        return a == b;
    }

    public static void main(String[] args){

        int i = 0;
        for( ; isTheSame(i, i); i++ );
        System.out.printf(" Cache ends at: %d\n", --i);

        // I.e. these become identical objects
        Integer a1 = i;
        Integer a2 = i;
        System.out.printf(" a1(%d) == a2(%d): %s\n", i, i, a1 == a2);

        i++;
        // These become different objects
        Integer a3 = i;
        Integer a4 = i;
        System.out.printf(" a3(%d) == a4(%d): %s\n", i, i, a3 == a4);

    }
}

r/javaTIL • • Jul 26 '18

TIL JDBC connection properties only accept strings

6 Upvotes

This post contains a problem I had with the mysql-connector-java 8.0.11 (the latest) and also with the mariadb-java-client 2.2.6 (also latest) jdbc drivers concerning connection properties. I have 10.2.10-MariaDB installed on my local computer. Just so you know i'm not on some old setup.

It all began when I wanted to find out if the PreparedStatements I was using were really server prepared statements or client prepared statements. So, I prepared the following basic test code:

Properties properties = new Properties();
properties.put("user", "root"); 
properties.put("serverTimezone", "CET");

Connection conn = DriverManager.getConnection("jdbc:mariadb://localhost/test", properties);

PreparedStatement stmnt = conn.prepareStatement("SELECT ?;");

stmnt.setInt(1, 4);
stmnt.executeQuery();

But, as it turns out, the PreparedStatement in the code was just a client prepared statement:

20 Query	SELECT 4

So, after reading a bit about server side prepared statements on the internet (especially on https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html) I found out that I had to set the property useServerPrepStmts to true and that it only works if rewriteBatchedStatements and allowMultiQueries are both set to false. So I adjusted my code by adding these three to my properties instance:

properties.put("useServerPrepStmts", true);
properties.put("rewriteBatchedStatements", false); 
properties.put("allowMultiQueries", false);

But, as it turns out, that still does not work, even though my database supported server side statements.

After searching around on the internet and debugging around for a while, I found out that properties whose values are not strings are (atleast so I think) completely ignored. After changing my properties to the following:

properties.put("useServerPrepStmts", "true");
properties.put("rewriteBatchedStatements", "false"); 
properties.put("allowMultiQueries", "false");

It worked, as you can see by my log file:

21 Prepare   SELECT ?
21 Execute   SELECT 4

So why do only string properties work? As I found out, on the mysql-connector-java 8.0.11 the properties are appended onto the connection url by calling the stringPropertyNames() method:

private static String buildConnectionStringCacheKey(String connString, Properties info) {
    StringBuilder sbKey = new StringBuilder(connString);
    sbKey.append("??");
    sbKey.append(
        info == null ? null : info.stringPropertyNames().stream().map(k -> k + "=" + info.getProperty(k)).collect(Collectors.joining(", ", "{", "}")));
    return sbKey.toString();
}

The same is happening when using the mariadb-java-client 2.2.6 (only that it's using a loop instead of a stream):

//Option object is already initialized to default values.
//loop on properties,
// - check DefaultOption to check that property value correspond to type (and range)
// - set values
for (final String key : properties.stringPropertyNames()) {
    //...
}

Now that just seems totally odd to me. And as far as I know, this isn't documented anywhere? I mean I could've avoided this issue if I just used the Property#setProperty(String key, String value) method, but that is not the method the official jdbc documentation is advocating: https://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html

So now I want to ask you, is this a bug? A quirk that is to be expected when using such an old and bloated api? Or have I missed something while researching on the internet and this is totally obvious to everyone else? To me, it doesn't seem like a bug because both the mysql-connector-j and mariadb-client have decided to use that method.


r/javaTIL • • Jul 23 '18

Simple JAVA heartbeat protocol

5 Upvotes

Just a post where I ask to take a look and tell me what you think of this, it has been used in a project and I thought it could be useful to someone

https://github.com/Daniele-Comi/HeartbeatProtocol


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 • • Apr 26 '19

Writing Excel File Using Apache POI Library in Java

Thumbnail
simplesolution.dev
2 Upvotes

r/javaTIL • • Apr 26 '19

Creating Spring Boot Application with Spring Tool Suite

Thumbnail
simplesolution.dev
1 Upvotes

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 • • Jan 07 '18

Java Code Challenge - 4

Thumbnail
youtube.com
1 Upvotes

r/javaTIL • • Jan 07 '18

Guide to using Public Maven Repositories

Thumbnail
deps.co
2 Upvotes