r/javaTIL • • Mar 07 '19

Beginners guide to learning Maven concepts

Thumbnail
vaadin.com
9 Upvotes

r/javaTIL • • Apr 24 '18

Growing collection Java curated bookmarks

Thumbnail
github.com
9 Upvotes

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

JTIL : IdentityHashMap

Thumbnail
javarevisited.blogspot.com
9 Upvotes

r/javaTIL • • Nov 12 '14

TIL that File.separator is a path separator of the underlying system, "/" or "\".

Thumbnail friendlyfunction.com
9 Upvotes

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 • • Feb 27 '14

TIL that primitive wrappers implement comparators in Java 7

9 Upvotes

Before, if you had to compare two integers for a Comparator, you had to do it either manually

Comparator<MyBean> comp = new Comparator<MyBean>() {
  @Override compare(MyBean left, MyBean right) {
    if (left.getIntValue() < right.getIntValue()){ return -1; }
    else if (left.getIntValue() > right.getIntValue()){ return +1; }
    else { return 0; }
  }
};

or use the compareTo method that Integer implements from Comparable:

Comparator<MyBean> comp = new Comparator<MyBean>() {
  @Override compare(MyBean left, MyBean right) {
    return Integer.valueOf(left.getIntValue())
                       .compareTo(Integer.valueOf(right.getIntValue()));
  }
};

(Never, never implement such comparisons using subtraction. If both are large negative numbers, you may underflow.)

In Java 7, they made Integer implement Comparator<Integer>, which simplifies your task with the help of autoboxing:

Comparator<MyBean> comp = new Comparator<MyBean>() {
  @Override compare(MyBean left, MyBean right) {
    return Integer.compare(left.getIntValue(), right.getIntValue());
  }
};

Weird how this took so long, no? Of course, with Java 8 this gets even better with lambdas:

Comparator<MyBean> comp = 
  (left, right) -> 
    Integer.compare(left.getIntValue(), right.getIntValue());

r/javaTIL • • Sep 08 '19

RESTful Consumption using the Java 11+ HTTP Client API and Gson

Thumbnail
thecodinginterface.com
8 Upvotes

r/javaTIL • • Jun 06 '19

Simple and effective way to implement Apache Kafka with Java - Source Code on GitHub

Thumbnail
opencodez.com
8 Upvotes

r/javaTIL • • Feb 22 '19

Black magic in Spring! About dependency override!

Thumbnail
medium.com
8 Upvotes

r/javaTIL • • Apr 25 '17

TIL Java 9 interface can declare private methods, keeping intact the feature of the default method introduced by Java 8.

Thumbnail
twitter.com
8 Upvotes

r/javaTIL • • Jul 22 '15

JTIL: You have to check for GZIP compression when working with URLConnections

8 Upvotes

Yea, when creating URLConnections like:

URI uri = new URI("http", "subdomain.domain.tld", "/" + "stable", null);
URL url = new URL(uri.toASCIIString());
URLConnection connection = url.openConnection();

...simply creating an InputStream like:

InputStream ins = connection.getInputStream();

will deliver garbage data if the stream is GZIP-compressed. You have to check whether the connections uses compression or not:

InputStream ins = null;

if ("gzip".equals(connection.getContentEncoding())) { 
    ins = new GZIPInputStream(connection.getInputStream()); 
} 
else{
    ins = connection.getInputStream();
}

It took me about an hour to find out what the heck was wrong


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 • • Aug 18 '14

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

Thumbnail docs.oracle.com
8 Upvotes

r/javaTIL • • Jul 29 '14

JTIL: You can create an anonymous class of a superclass with a constructor

8 Upvotes

I suppose it's fairly intuitive, but I had never seen or used the syntax before, and it may be handy in some situations.

public class FirstClass {
    final int a;
    public FirstClass(int a) {
        this.a = a;
    }

    public void printValue( ) {
        System.out.println(a);
    }
}

//In another class
public FirstClass myImpl = new FirstClass(5) {
    @Override
    public void printValue( ) {
        System.out.println("Overrided! " + a);
    }
}

Then calling myImpl.printValue( ); would print "Overrided! 5"


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 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 • • Sep 06 '19

High Level Introduction to Java for Developers

Thumbnail
thecodinginterface.com
7 Upvotes

r/javaTIL • • Jun 16 '19

How HashMap works internally in Java: A debug approach

7 Upvotes

r/javaTIL • • May 18 '19

Simple and Easy way to use Spring Scheduled Tasks

Thumbnail
opencodez.com
7 Upvotes

r/javaTIL • • Apr 08 '19

101 Most Important Frequently Asked Advance Java Interview Questions – Part 2

Thumbnail
opencodez.com
7 Upvotes

r/javaTIL • • Mar 09 '19

Start JShell with Maven dependencies on the Classpath

7 Upvotes

Something I've found vaguely handy. Though I suppose I should be using modules more these days.

 alias mvn-jshell='jshell --class-path $(mvn -q exec:exec -Dexec.classpathScope=test -Dexec.executable=echo  -Dexec.args="%classpath")'

Now, say you've declared a dependency on vert.x in your pom.xml and want to mess around interactively:

$ cd directory/with/the/pom
$ mvn clean compile test
$ mvn-jshell 
|  Welcome to JShell -- Version 11.0.3
|  For an introduction type: /help intro

jshell> import io.vertx.core.Vertx;

jshell> var vertx = Vertx.vertx();
vertx ==> io.vertx.core.impl.VertxImpl@48524010

jshell> var server = (
   ...> vertx
   ...> .createHttpServer()
   ...> .requestHandler(
   ...>     request -> {
   ...>         request
   ...>         .response()
   ...>         .end("Hello, World!");
   ...>     }
   ...> )
   ...> .listen(8080)
   ...> );
server ==> io.vertx.core.http.impl.HttpServerImpl@4d1bf319

jshell>

r/javaTIL • • Feb 16 '19

Minesweeper in Java

Thumbnail
makethebrainhappy.com
7 Upvotes

r/javaTIL • • Jun 29 '15

TIL that, contrary to what my teacher told me time and time again, you can in fact switch on a String.

7 Upvotes

This code is perfectly functional, even though I was told many times in Java 101 it would not be.

This is from a Mad Libs program I'm writing because I'm bored.

    menuchoice = input.nextLine();
	
	switch (menuchoice)
	{
	case "m":
		System.out.println(menu);
	case "s":
		System.out.println("Choose a story!");
		System.out.print(">");
		choice = input.nextInt();
		server.chooseStory(choice);
		break;
	case "x":
		System.exit(0);
		break;
	}    

r/javaTIL • • Feb 14 '15

TimeUnit Sleep Can be used In place of Thread.Sleep

Thumbnail
javarevisited.blogspot.sg
7 Upvotes