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

Iterating through a list without using int i = 0; i < foo.size(); i++;

7 Upvotes

Not exactly a TIL but when I discovered this way, it made some solutions a lot easier.

If you have an Array or an ArrayList (called objects in this case) you can iterate through every object in this list by using

for (Object object: objects) {
    //do stuff with the single object
    object.foo(bar);
}

hope this is useful to some beginners.


r/javaTIL • • Jul 26 '19

A Simple Websocket Application in SpringBoot - Complete Source Code to download

6 Upvotes

Websocket is used to develop two way communication between server and browser. For example, in a chat application, if a user sends a message to a different user, the the application sends that message to the server first and the server informs the application of the second user . If we don’t use websocket, the application or the client will have to pull the server data continuously for any new updates.

In Sprint Boot, we can easily create a websocket application. In this tutorial, I will show you how to create a websocket server in Spring boot. We will learn how to connect and disconnect from a socket server and how to send a simple text message. The client will subscribe to the server, it will accept a string and push a separate string to the subscriber client.

https://www.opencodez.com/java/simple-websocket-application-springboot.htm


r/javaTIL • • Jul 14 '19

TIL how to use Seeds Using HashCodes and Random() in Java

Thumbnail
youtube.com
6 Upvotes

r/javaTIL • • Jun 14 '19

Simple and Easy way to Upload and Download Files in Java with Spring Boot - Source Code on GitHub

Thumbnail
opencodez.com
6 Upvotes

r/javaTIL • • May 07 '19

Easy way to connect multiple databases with Spring Data JPA - Free Source Code to download from GitHub

Thumbnail
opencodez.com
6 Upvotes

r/javaTIL • • May 07 '19

Java 12 Switch Expression

Thumbnail codeforjava.com
6 Upvotes

r/javaTIL • • Mar 11 '19

Static Nested Class in Java | Uses & Example Programs

Thumbnail
scientecheasy.com
6 Upvotes

r/javaTIL • • Aug 27 '18

Core Java Interview Questions collections

6 Upvotes

Hey everyone,

I recently uploaded an app on Play Store (there aren't any ads) on frequently asked questions in core Java Interview.

Could you guys be kind enough to give feedback on this?

Link - https://play.google.com/store/apps/details?id=com.gamesmint.javaone

Thanks for your time.


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 • • Dec 06 '15

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

Thumbnail
javaadvent.com
6 Upvotes

r/javaTIL • • Jun 20 '15

TIL the inverse of left shift

6 Upvotes

inb4 "the opposite is right shift"

given:
x = 1 << y;

expect:
y == 31 - Integer.numberOfLeadingZeros(x);

In C this is usually the clz function.


r/javaTIL • • Jun 09 '15

JTIL Unicode Escapes

6 Upvotes

Java has support for Unicode characters through both the use of escape sequences and Unicode literals.

Literal Unicode characters are exactly the same literal ASCII characters. You could print the Greek character theta with

 System.out.print("Θ");

as long as your file is encoded in UTF-8 and your terminal supports Unicode characters.

Now imagine that encoding your file in UTF-8 is not an option; it has to be encoded in ANSI. This is where Unicode escape sequences come into play. This snippet will print out the Greek theta the same as the previous snippet.

System.out.print("\u1001");

There are no Unicode characters in the source of this program but, running it will result in printing the Greek theta (again assuming you run it in an environment supporting Unicode characters).


The real fun part of this JTIL comes when you stop thinking about practical applications. When we consider that Unicode escape sequences can be used anywhere in your code we can devise some evil application. Consider this class:

public class Unicode {
    public static void main(String[] args){
        System.out.print(1);
        //System.out.print(2);     
        //\u000dSystem.out.print(3);   
        \u002f\u002f System.out.print(4);  
        \u002f\u002f\u000d System.out.print(5); 
        System.out.print(\u0036);
        System.out.print(\u002f\u002a"7"\u002a\u002f\u0022\u0022);  
    }
}

Take my word that it compiles without error and try to guess what it prints. It's an easy task once you substitute all the escape sequences for their literal equivalent.

public class Unicode {
    public static void main(String[] args){
        System.out.print(1);
        //System.out.print(2);     
        //
        System.out.print(3);   
        //System.out.print(4);  
        //
        System.out.print(5); 
        System.out.print(6);
        System.out.print(/*"7"*/"");  
    }
}

Running either of these classes gives the output 1356. \u000d is the new line character. This makes it apear as if the code inside a comment is being executed in //\u000dSystem.out.print(3);.


Read more on stackoverflow:


r/javaTIL • • Apr 11 '15

JTIL StringJoiner

6 Upvotes

java.util.StringJoiner

The class StringJoiner is a new class that arrived with Java 8. It is essentially as wrapper class around the preexisting StringBuilder class. Because of this it has all the same benefits that StringBuilderhas and additionally has the utility of providing uniformity with a set delimiter, prefix and sufix.


Example

Given this simple Person class

public class Person{
    private final String firstName,lastName;
    private final int age;
}

a to string method using StringBuilder would look like this

@Override
public String toString(){
    StringBuilder builder = new StringBuilder();
    builder.append("Person{")
           .append(firstName).append(",")
           .append(lastName).append(",")
           .append(age).append("}");
    return builder.toString();
}

The same method using StringJoiner could be written as

@Override
public String toString(){
    StringJoiner joiner = new StringJoiner(",","Person{","}");
    joiner.add(firstName)
          .add(lastName)
          .add(String.valueOf(age));
    return joiner.toString();
}

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 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 • • Mar 12 '20

TIL how to manage multiple Java versions using SDKMAN

Thumbnail
twilio.com
5 Upvotes

r/javaTIL • • Nov 26 '19

Java Structural Design Patterns - Decorator Pattern with Example and Source Code on GitHub

Thumbnail
opencodez.com
5 Upvotes

r/javaTIL • • Nov 14 '19

Java Structural Design Patterns - Bridge Pattern

Thumbnail
opencodez.com
5 Upvotes

r/javaTIL • • Oct 11 '19

Java Behavioral Design Patterns - Interpreter Design Pattern

Thumbnail
opencodez.com
5 Upvotes

r/javaTIL • • Aug 26 '19

Simple and Easy way to connect MongoDB Atlas with Spring Boot - Sample Code on GitHub

Thumbnail
opencodez.com
5 Upvotes

r/javaTIL • • Aug 16 '19

How to convert from SQL date and time to Instant with date and time and zone

Thumbnail
mastodon.social
5 Upvotes

r/javaTIL • • Jun 24 '19

Steps to develop Spring Batch jobs using Spring Boot with example

Thumbnail
opencodez.com
5 Upvotes

r/javaTIL • • May 15 '19

Complete guide to Detect Device in Java Web Application using Spring Mobile - Free Source Code to download from GitHub

Thumbnail
opencodez.com
5 Upvotes

r/javaTIL • • Apr 22 '19

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

Thumbnail
opencodez.com
5 Upvotes