Wednesday, May 16, 2018

10 Things You Didn’t Know About Java

So, you’ve been working with Java since the very beginning? Remember the days when it was called “Oak”, when OO was still a hot topic, when C++ folks thought that Java had no chance, when Applets were still a thing?
I bet that you didn’t know at least half of the following things. Let’s start this week with some great surprises about the inner workings of Java.

1. There is no such thing as a checked exception

That’s right! The JVM doesn’t know any such thing, only the Java language does.
Today, everyone agrees that checked exceptions were a mistake. As Bruce Eckel said on his closing keynote at GeeCON, Prague, no other language after Java has engaged in using checked exceptions, and even Java 8 does no longer embrace them in the new Streams API (which can actually be a bit of a pain, when your lambdas use IO or JDBC).
Do you want proof that the JVM doesn’t know such a thing? Try the following code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Test {
  
    // No throws clause here
    public static void main(String[] args) {
        doThrow(new SQLException());
    }
  
    static void doThrow(Exception e) {
        Test. doThrow0(e);
    }
  
    @SuppressWarnings("unchecked")
    static extends Exception>
    void doThrow0(Exception e) throws E {
        throw (E) e;
    }
}
Not only does this compile, this also actually throws the SQLException, you don’t even need Lombok’s @SneakyThrows for that.

2. You can have method overloads differing only in return types

That doesn’t compile, right?
1
2
3
4
class Test {
    Object x() { return "abc"; }
    String x() { return "123"; }
}
Right. The Java language doesn’t allow for two methods to be “override-equivalent” within the same class, regardless of their potentially differing throws clauses or return types.
But wait a second. Check out the Javadoc of Class.getMethod(String, Class...). It reads:
Note that there may be more than one matching method in a class because while the Java language forbids a class to declare multiple methods with the same signature but different return types, the Java virtual machine does not. This increased flexibility in the virtual machine can be used to implement various language features. For example, covariant returns can be implemented with bridge methods; the bridge method and the method being overridden would have the same signature but different return types.
Wow, yes that makes sense. In fact, that’s pretty much what happens when you write the following:
1
2
3
4
5
6
7
8
abstract class Parent {
    abstract T x();
}
class Child extends Parent {
    @Override
    String x() { return "abc"; }
}
Check out the generated byte code in Child:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// Method descriptor #15 ()Ljava/lang/String;
// Stack: 1, Locals: 1
java.lang.String x();
  0  ldc [16]
  2  areturn
    Line numbers:
      [pc: 0, line: 7]
    Local variable table:
      [pc: 0, pc: 3] local: this index: 0 type: Child
// Method descriptor #18 ()Ljava/lang/Object;
// Stack: 1, Locals: 1
bridge synthetic java.lang.Object x();
  0  aload_0 [this]
  1  invokevirtual Child.x() : java.lang.String [19]
  4  areturn
    Line numbers:
      [pc: 0, line: 1]
So, T is really just Object in byte code. That’s well understood.
The synthetic bridge method is actually generated by the compiler because the return type of the Parent.x() signature may be expected to Object at certain call sites. Adding generics without such bridge methods would not have been possible in a binary compatible way. So, changing the JVM to allow for this feature was the lesser pain (which also allows covariant overriding as a side-effect…) Clever, huh?
Are you into language specifics and internals? Then find some more very interesting details here.

3. All of these are two-dimensional arrays!

1
2
3
4
5
class Test {
    int[][] a()  { return new int[0][]; }
    int[] b() [] { return new int[0][]; }
    int c() [][] { return new int[0][]; }
}
Yes, it’s true. Even if your mental parser might not immediately understand the return type of the above methods, they are all the same! Similar to the following piece of code:
1
2
3
4
5
class Test {
    int[][] a = {{}};
    int[] b[] = {{}};
    int c[][] = {{}};
}
You think that’s crazy? Imagine using JSR-308 / Java 8 type annotations on the above. The number of syntactic possibilities explodes!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Target(ElementType.TYPE_USE)
@interface Crazy {}
class Test {
    @Crazy int[][]  a1 = {{}};
    int @Crazy [][] a2 = {{}};
    int[] @Crazy [] a3 = {{}};
    @Crazy int[] b1[]  = {{}};
    int @Crazy [] b2[] = {{}};
    int[] b3 @Crazy [] = {{}};
    @Crazy int c1[][]  = {{}};
    int c2 @Crazy [][] = {{}};
    int c3[] @Crazy [] = {{}};
}

4. You don’t get the conditional expression

So, you thought you knew it all when it comes to using the conditional expression? Let me tell you, you didn’t. Most of you will think that the below two snippets are equivalent:
1
Object o1 = true ? new Integer(1) : new Double(2.0);
… the same as this?
1
2
3
4
5
6
Object o2;
if (true)
    o2 = new Integer(1);
else
    o2 = new Double(2.0);
Nope. Let’s run a quick test
1
2
System.out.println(o1);
System.out.println(o2);
This programme will print:
1.0
1
Yep! The conditional operator will implement numeric type promotion, if “needed”, with a very very very strong set of quotation marks on that “needed”. Because, would you expect this programme to throw a NullPointerException?
1
2
3
4
5
6
Integer i = new Integer(1);
if (i.equals(1))
    i = null;
Double d = new Double(2.0);
Object o = true ? i : d; // NullPointerException!
System.out.println(o);

5. You also don’t get the compound assignment operator

Quirky enough? Let’s consider the following two pieces of code:
1
2
i += j;
i = i + j;
Intuitively, they should be equivalent, right? But guess what. They aren’t! The JLS specifies:
A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.
This is so beautiful, I would like to cite Peter Lawrey‘s answer to this Stack Overflow question:
A good example of this casting is using *= or /=
byte b = 10;
b *= 5.7;
System.out.println(b); // prints 57
or
byte b = 100;
b /= 2.5;
System.out.println(b); // prints 40
or
char ch = '0';
ch *= 1.1;
System.out.println(ch); // prints '4'
or
char ch = 'A';
ch *= 1.5;
System.out.println(ch); // prints 'a'
Now, how incredibly useful is that? I’m going to cast/multiply chars right there in my application. Because, you know…

6. Random integers

Now, this is more of a puzzler. Don’t read the solution yet. See if you can find this one out yourself. When I run the following programme:
1
2
3
for (int i = 0; i < 10; i++) {
  System.out.println((Integer) i);
}
… then “sometimes”, I get the following output:
92
221
45
48
236
183
39
193
33
84
How is that even possible??
.
.
.
.
.
. spoiler… solution ahead…
.
.
.
.
.
OK, it has to do with overriding the JDK’s Integer cache via reflection, and then using auto-boxing and auto-unboxing. Don’t do this at home! Or in other words, let’s think about it this way, once more

7. GOTO

This is one of my favourite. Java has GOTO! Type it…
1
int goto = 1;
This will result in:
Test.java:44: error:  expected
    int goto = 1;
       ^
This is because goto is an unused keyword, just in case…
But that’s not the exciting part. The exciting part is that you can actually implement goto with break, continue and labelled blocks:
Jumping forward
1
2
3
4
5
label: {
  // do stuff
  if (check) break label;
  // do more stuff
}
In bytecode:
2  iload_1 [check]
3  ifeq 6          // Jumping forward
6  ..
Jumping backward
1
2
3
4
5
6
label: do {
  // do stuff
  if (check) continue label;
  // do more stuff
  break label;
} while(true);
In bytecode:
 2 iload_1 [check]
 3 ifeq 9
 6 goto 2 // Jumping backward

8. Java has type aliases

In other languages (e.g. Ceylon), we can define type aliases very easily:
1
interface People => Set;
A People type constructed in such a way can then be used interchangably with Set:
1
2
3
People?      p1 = null;
Set? p2 = p1;
People?      p3 = p2;
In Java, we can’t define type aliases at a top level. But we can do so for the scope of a class, or a method. Let’s consider that we’re unhappy with the namings of Integer, Longetc, we want shorter names: I and L. Easy:
1
2
3
4
5
6
7
8
class Testextends Integer> {
    extends Long> void x(I i, L l) {
        System.out.println(
            i.intValue() + ", " +
            l.longValue()
        );
    }
}
In the above programme, Integer is “aliased” to I for the scope of the Test class, whereas Long is “aliased” to L for the scope of the x() method. We can then call the above method like this:
1
new Test().x(1, 2L);
This technique is of course not to be taken seriously. In this case, Integer and Long are both final types, which means that the types I and L are effectively aliases (almost. assignment-compatibility only goes one way). If we had used non-final types (e.g. Object), then we’d be really using ordinary generics.
Enough of these silly tricks. Now for something truly remarkable!

9. Some type relationships are undecidable!

OK, this will now get really funky, so take a cup of coffee and concentrate. Consider the following two types:
1
2
3
4
5
// A helper type. You could also just use List
interface Type {}
class C implements Typesuper C>> {}
class D implements Typesuper D>>> {}
Now, what do the types C and D even mean?
They are somewhat recursive, in a similar (yet subtly different) way that java.lang.Enumis recursive. Consider:
1
public abstract class Enumextends Enum> { ... }
With the above specification, an actual enum implementation is just mere syntactic sugar:
1
2
3
4
5
// This
enum MyEnum {}
// Is really just sugar for this
class MyEnum extends Enum { ... }
With this in mind, let’s get back to our two types. Does the following compile?
1
2
3
4
class Test {
    Typesuper C> c = new C();
    Typesuper D> d = new D();
}
Hard question, and Ross Tate has an answer to it. The question is in fact undecidable:
Is C a subtype of Type?
Step 0) C 
Step 1) Type> 
And then:
Is D a subtype of Type>?
Step 0) D >
Step 1) Type>>> >
Step 2) D >>
Step 3) Type>> >
Step 4) D> >>
Step . . . (expand forever)
Try compiling the above in your Eclipse, it’ll crash!

10. Type intersections

Java has a very peculiar feature called type intersections. You can declare a (generic) type that is in fact the intersection of two types. For instance:
1
2
class Testextends Serializable & Cloneable> {
}
The generic type parameter T that you’re binding to instances of the class Test must implement both Serializable and Cloneable. For instance, String is not a possible bound, but Date is:
1
2
3
4
5
// Doesn't compile
Test s = null;
// Compiles
Test d = null;
This feature has seen reuse in Java 8, where you can now cast types to ad-hoc type intersections. How is this useful? Almost not at all, but if you want to coerce a lambda expression into such a type, there’s no other way. Let’s assume you have this crazy type constraint on your method:
1
extends Runnable & Serializable> void execute(T t) {}
You want a Runnable that is also Serializable just in case you’d like to execute it somewhere else and send it over the wire. Lambdas and serialisation are a bit of a quirk.
You can serialize a lambda expression if its target type and its captured arguments are serializable
But even if that’s true, they do not automatically implement the Serializable marker interface. To coerce them to that type, you must cast. But when you cast only to Serializable…
1
execute((Serializable) (() -> {}));
… then the lambda will no longer be Runnable.
Egh…
So…
Cast it to both types:
1
execute((Runnable & Serializable) (() -> {}));

Conclusion

I usually say this only about SQL, but it’s about time to conclude an article with the following:
Java is a device whose mystery is only exceeded by its power

Developer need to know everything!

What Every Programmer Should Know about Memory
This is one of the classic article, which will take you through may lanes of memory, some old, some new, some known and some unknown. Despite being so conman and omnipresent, not every programmer have enough knowledge of Memory. Knowledge of memory in modern system becomes even more important if you are in space of writing high performance application. Hardware designers have come up with ever more sophisticated memory handling and acceleration techniques–such as CPU caches–but these cannot work optimally without some help from the programmer. I am still reading this article, and I can’t tell you how much I have learned from this about RAM, CPU Caches e.g. L1 and L2 cache, different types of memory, direct memory access, memory controller designs and Memory in general. In short, a must read for programmers of all level of experience.

What Every Computer Scientist Should Know About Floating-Point Arithmetic
Floating point arithmetic is a tricky topic, and it’s not easy to master. Even many Java programmer doesn’t know what can go wrong when comparing float/double value with == operator. Many of us often makes mistake of doing monetary calculation in float and double. This article is another gem of this series and must read for all software developers and programmers. As your experience grows, you are expected to know subtle details of common things, and floating point arithmetic is one of them. As as senior Java developer, you must know how do perform monetary calculation, when to use float, double or BigDecimal classes, how to round floating point numbers etc. Even if you know fundamentals of floating point arithmetic, You will learn something new about floating point calculation by reading this article.

What Every Developer Should know about Unicode
Character encoding is another area, where many programmer struggle, and “The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)” aims to fill that gap. On side note, Yes that’s the full title of that article. It was written by Joel Spolsky, one of the founder of statckoverflow.com. Joel has written this post on his blog almost 10 years back, but it is still relevant in today’s world. This article will teach you about What is Unicode, W hat is character encoding, how characters are represented using bytes and many more. One of the best thing about this article is language and flow, even if you don’t know anything about Unicode, you can easily follow. In short, one more must read for all programmers, coders and software engineers.

What Every Programmer Should know about Time
Apart from Character encoding, time and date is another area, where many programmers struggle, including me. Even senior developers lost between GMT, UTC, day light saving and between leap seconds. Frankly speaking, It’s not easy to deal with time zones without making any mistake, then add day light savings and effect of that. Problems becomes worse if you using trial and error method, because you will never able to solve your problem by doing that. There are so many things which can go wrong and there are equal number of misconceptions. Things like, whether date contains time-zone or not can confuse you like hell, converting UNIX time to other time-zone can freak you out, forget about clock synchronization and delays. I hope many of your misconception about time will go away and you will build sound fundamental about Time, by reading this classic article.

What every web developer must know about URL encoding
This article describes common misconceptions about Uniform Resource Locator (URL) encoding, then attempts to clarify URL encoding for HTTP, before presenting frequent problems and their solutions. While this article is not specific to any programming language, it illustrate the problems in Java) and finish by explaining how to fix URL encoding problems in Java, and in a web application at several levels. You will learn basics of URL grammar, general URL syntax in HTTP and other protocol. This article also explores common pitfalls of URLs e.g. character encoding, reserved character at different part of URL, and URL encoding/decoding issues. If you are a Java programmer, then you will also learn about how to handle URLs in Java application, the right way. How to construct URL and using Apache commons HTTP client library. Finally it also suggest best practices or dealing with URLs e.g. you should encode URLs when you build them, making sure your URL-rewrite filters deal with your URL correctly and many more. In short, a must read article for any web developer and programmer.

What should every programmer know about web development?
This is an interesting article from programmers stack exchange, about what should every programmer implementing the technical details of a web application consider before making the site public. This includes things ranging from Interface design and User Experience, Security, Web standards, Performance, Search Engine Optimization(SEO), Technology involved, and about several important resources. Since today’s world is hugely dependent upon internet and programmer having their personal site, blog is quite common. Experience learned on this article will not even help in your professional work but also in your personal work. You will learn about all key technology e.g. HTTP, HTML, XML, CSS, JavaScript, browsers compatibility, tips to reduce loading time of your website, XML sitemaps, W3C specifications and several other key details.

What Every Programmer Should Know About SEO
This is another article, which is very important for web developers, programmers and blogger. SEO is too big to ignore, since many programmers are also blogger, it’s important to learn few basics of Search Engine Optimization to help Google find their content and present to other fellow programmers. Since no company can survive without web presence in today’s inter-connected world, SEO becomes even more important. If you own start-up, selling any product, then SEO is something to care about. All programmers, especially web developers can largely benefit from this article. Remember, Search Engine Optimization is vast and very dynamic subject, and also varies between different search engines e.g. Google, Yahoo, and others. So, In order to master this topic you will always need to update your knowledge.

What Every C Programmer Should Know About Undefined Behaviour #1/3
C programming language have the concept of “undefined behaviour”. Undefined behaviour is a broad topic with a lot of nuances and that’s one reason of Why I like Java, less number of undefined behaviour, less confusion, more stability and more peace. Many seemingly reasonable things in C actually have undefined behaviour, and this is a common source of bugs in programs. Beyond that, any undefined behaviour in C gives license to the implementation (the compiler and runtime) to produce code that formats your hard drive, does completely unexpected things, or worse. Read this excellent article to deep dive on sea of undefined behaviour.

What Every Programmer Need to know about networking
From the article itself “You’re a programmer. Have you ever wondered how multi-player games work? From the outside it seems magical: two or more players sharing a consistent experience across the network like they actually exist together in the same virtual world. But as programmers we know the truth of what is actually going on underneath is quite different from what you see. It turns out that it’s all an illusion.” This is very interesting article about networking, written for game programmers but I think every programmer and developer can benefit from this.

What Every Java Developer Should Know about String
This is my article on java.lang.String and what I personally thing every Java programmer should know about it. String is very important in day to day programming in Java and that’s why good knowledge is must for any Java developer. This article touches many important areas of String including string pool, string literal, comparing String using == vs equals(), converting bytes to String, Why String is immutable, properly concatenating Strings and many more. Advanced programmer may already know all these stuffs but even then it’s good to revise them.

What should every programmer know about security?
This question was ask by one computer programming student in StackOverFlow. Just like we learn a lot about general programming concepts e.g. operating system, algorithm, data-structure, computer architecture, and other stuff, its also important to know about security. Though Security is vast topic ranging from encryption/decryption, SSL, web security, obfuscation, authentication, authorization etc, a basic minimum knowledge is must for every programmer. I personally didn’t know much about Security when I started my career, its when I start writing Servlet/JSP based Java web application, I come to know about web security and several security threats like SQL Injection, Denial of Service, XML Injection, Cross site scripting and others. As Java developer, now I follow secure Java coding practices provided by fortify, PMP and other static code analysis providers.  This article is very good collection of topics and links about Security and whether you are doing coding or not, you will surely benefit from this resource.

Man Utd's next generation of wonderkids

Manchester United have set off on their pre-season United States tour with a number of young stars involved, but some other talents have lef...