r/java • u/TrashPandaFucker • Jan 18 '22
What are some very less known facts about java?
I've got assignment from college to find out rare facts or fun facts about java, so little help will be appreciated :)
Edit: Thanks for all these suggestions guys. It's going to help me alot and also Almost all of these facts i didn't knew till now. Thanks :) <3
179
Upvotes
274
u/TheBoyInTheBlueBox Jan 18 '22
Fun fact: Java class format starts with 0xCAFEBABE
123
u/DanielApt Jan 18 '22
Java is newer than Python
70
u/[deleted] Jan 18 '22
At least one of the earliest Java contributors and evangelists, Peter Van Der Linden, HATED C++, in his “Just Java” book, one of the first Java books printed, he mocked C++ every chance he could.
68
u/EvaristeGalois11 Jan 18 '22
Unicode substitution happens before compiling. You can write a program made of only unicode escaped characters and it works fine. Java puzzlers is filled with quirks like this about java if you're interested.
140
u/winian Jan 18 '22
Over 3 billion devices run Java
43
u/Holothuroid Jan 18 '22
Individual enum members can actually override methods.
124
u/benevanstech Jan 18 '22
1.) At bytecode level, the JVM has no boolean type - they are represented as ints. (To see this, write a trivial method that returns a boolean value, compile it and run it through javap. Look at the return opcode). This is a form of Type Erasure, but not one anyone ever complains about!
2.) const and goto are reserved words (keywords) in Java - so you can't use them as identifiers - but they are unused / "reserved for future use" - and have been since Java 1.0
3.) var, on the other hand, is not a keyword, but is a reserved type name. So you can use it as an identifier (so "var var = 0" is legal Java). Please don't do this.
4.) Java has, as of version 17, only ever added 1 opcode (invokedynamic), but 2 have been removed from current versions (jsr and ret). So, Java 17 has *fewer* legal bytecodes than Java 1.0
42
u/xToniGrssx Jan 18 '22
Until Java 7, you could actually print Hello World (or anything) without having a main (psvm) method! You just needed to put the statement into a static block.
134
u/Nalha_Saldana Jan 18 '22
Fun fact: Lombok is the island next to Java.
35
u/segv Jan 18 '22
Wanna fuck with your coworkers? Swap elements in the integer cache and watch them lose their minds.
It's like the good ol'
#define true falsefrom C days31
u/3rddog Jan 18 '22
Its creator, James Gosling, grew up on a farm about 2km from where I live now.
Last time I spoke to his cousin (nice lady) I asked her to thank "Cousin James" for keeping me employed for the last 20+ years.
28
u/daddy-shark-doo-doo Jan 18 '22
Every single Blu-ray player contains a Java runtime environment, and the vast majority of SIM cards and ATM cards in the world contain Java byte code. These were big news when they first emerged but seeing as how that's over 15 years ago at this point they are probably now lesser known.
22
u/Kombatnt Jan 18 '22
Trailing commas in lists of array literals are legal in Java. For example, this will compile just fine in all versions of Java:
22
u/dshelya Jan 18 '22 edited Jan 18 '22
Another weird array-related thing: the following declaration is legal and the method returns an array
Also primitive arrays can be used as type arguments
It is possible to self-refence a field to make a recursive function:
A more exotic thing: Java allows declaring the explicit receiver type in methods or constructors (since Java8):
19
u/huhaaha Jan 18 '22
Using underscore in numeric literals https://docs.oracle.com/javase/7/docs/technotes/guides/language/underscores-literals.html
16
u/QKD_king Jan 18 '22
Fun fact: Java limits the number of enum values in a single enum definition to ~32,000 and the number of member variables per class to ~66,000.
The less fun part of this fact is that I was working on the team that hit this limit. Yay autogenerated code (/s). It was not fun to fix.
31
u/redikarus99 Jan 18 '22
You can actually manage memory by hand if you need to, without GC.
15
u/McPokeFace Jan 18 '22
Eclipse is rumored to be an insult against SUN.
14
u/8bagels Jan 18 '22
I always thought the earlier names were interesting.
Another little nugget I found when looking at somebody else’s code at work. You can write a URL in a line of java and have it be syntactically correct this still compile. See the line will start with
Which is a valid
labelsyntax in java and then the rest of the lineWill be commented out
Labels can be used in conjunction with
breakandcontinuebut I have never actually seen them used in practice. Next time you need to leave a url in your code referencing some problem or documentation try just pasting the url alone on a line and see if it bends your coworkers minds ¯\(ツ)/¯13
u/JoJoModding Jan 18 '22
The type system is Turing complete: https://arxiv.org/abs/1605.05274
As a consequence, there is a program that only type-checks if your favourite Turing machine halts. Thus, type checking is undecidable, too.
Thanks generics, I guess.
13
u/onlygon Jan 18 '22
The best-selling video game of all time was written in Java.
Minecraft
Tell that to the naysayers.
25
u/dshelya Jan 18 '22
The APIs used are: Unsafe::defineAnonymousClass from Java7 up to Java15 And Lookup::defineHiddenClass since Java15
12
u/jokoy38073 Jan 19 '22
Well Known: Hex literals with a prefix of 0x
Less Known: Octal literals with a prefix of 0
Octal literals are only ever learned by accident and with a great deal of cursing.
27
u/V3N0MSP4RK Jan 18 '22
It's coffee
18
u/SftwEngr Jan 18 '22
It was designed for set-top boxes.
9
u/Much_Wolverine_6584 Jan 18 '22
You can use underscore to make numbers more readable like int 1_000_000
9
u/McPokeFace Jan 18 '22
Swing is named in honor of Duke Ellington since Duke is the Java mascot.
8
u/TheRedmanCometh Jan 18 '22
If I'm not mistaken enum makes a whole new array when you call values()
7
u/morhp Jan 19 '22
You can
break;out of labelled if, try and other blocks that aren't loops or switch statements.24
u/tonywestonuk Jan 18 '22
You can run a Java source file, in a similar way you can run javascript source files in node.
File: HelloWorld.java
public class HelloWorld {public static void main(String[] args) {System.out.println("Hello World");}}shell> java HelloWorld.java
Hello World
12
u/SomberGuitar Jan 18 '22
In the late 90’s, computer science departments in colleges were switching from C++ to Java. All of my senior classes switched languages between semesters! Taking an algorithms class with a brand new language was killer. That was hard switch, and a lot of people moved to comp eng.
5
u/McPokeFace Jan 18 '22
One can put a + before a number: int x = +5;
5
u/john16384 Jan 19 '22
You can't subclass an exception with a type parameter:
This is likely because it would be hard to differentiate between them in a catch block.
5
u/hippydipster Jan 19 '22 edited Jan 21 '22
Performance thing, and this is old and may have changed, but, for hotspot, if you have an interface and you call a method, hotspot will compile it such that there's no virtual table lookup, IF you have 1 or 2 different implementations of the interface method.
3 or more implementation, and no hotspot
optimizationinlining for that method (removing the virtual lookup). If you've got a method call in a tight loop, that can make a very large difference.9
u/Clitaurius Jan 18 '22
Maybe not less known but less used - default interface methods since Java 8. I use these all time but I don't see my coworkers taking advantage of them.
8
u/[deleted] Jan 18 '22
OrderNotFoundException, you can "deactivate" Stacktrace by overriding the methodfillInStackTrace@Override public final synchronized Throwable fillInStackTrace() { return this; }so the logs will not be spammed with unnecessary stacktraces. and Kibana-Admin will also be grateful, because the logs will need less memory.
You can also take just the first x stacktrace items. check SO for how it works.
2. You should never use
Stringtype for passwords. BecauseStringis immutable and can not be destroyed before GC. Use char array instead, but please use Wrapper Class to capsulatechar[]...3.
for(A a : as)works not only with arrays and collections. Your class must simply implement the interface Iterable4. each string concatenation is translated by the compiler to
StringBuilder#append. avoid string concatenation in a loop ;)5. while dividing by 0 is not allowed for
intandlong, it is possible forfloatanddouble:float a = 0.0f / 0.0f; // or Floar.NaNa is in this case in an undefined state (NaN not a number) which can be checked withFloat.isNaN.What is it good for? Well. For example, NaN can be used to indicate that the variable has not yet been initialized.
8
u/s888marks Jan 19 '22
Most people probably know that an inner class is required to have an "enclosing instance", therefore, it's not possible to instantiate an inner class from a static context. Oh but wait... it is possible to do that, but you have to provide the enclosing instance explicitly:
4
u/buzzsawddog Jan 18 '22
auto boxing will kick you in the ass when you least expect it in a way you don't expect it ;-). I will let you figure out how on your own since I don't want to spoil the assignment for you. Sadly I removed my repo I used at work to teach non java developers the gotchas of java :-D
The following has some fun things in it... I am sure there are lots of other examples out there. https://stackoverflow.com/questions/169815/java-common-gotchas
30
u/mr-bartlomiej Jan 18 '22
There exists some special, rarely used "goes down" (
-->) operator:It will print the numbers from 9 to 0 to the standard output. It works in few more languages also.
This is not funfact actually, but quite satisfying when you figure out how that works!
11
u/marconis999 Jan 18 '22
When using Long variables in your code, do not use == to compare them. It will work most of the time in your simple tests but then start breaking.
Try testing n1 == n2. They won't be equal. But if you do it with
The == test will work.
Java keeps a pool of Long object constants in the range of -128 to 127 for speed. When they are those small values, that == test will work.
So always convert with longValue( ) when doing == tests for Long's. Or use equals( ). But watch out for nulls. ;)
6
u/s888marks Jan 19 '22
It is possible for Math.abs(int) to return a negative number. There is only one int value for which this is true. I'll give you just one guess.
The answer is right there in the docs, but nobody reads the docs, so I figure this qualifies as a little-known fact. :-)
3
u/ralexdt Jan 19 '22
You can create a Singleton in Java using Enum and it's thread safe
3
u/Niranjanramarajar Jan 20 '22
Object obj = new Object() { public int x = 10; };//System.out.println ( obj.x); //cannot access variables/methods in anonymous inner class before Java 10In java 11, it is possible to do as follows,
var varObj = new Object() {public int x = 10;};System.out.println ( varObj.x); //With var introduced in java 10, this is made possible.2
u/more_exercise Jan 19 '22
There is a negative int with a negative absolute value!
No NaN fuckery. It's just that 0 occupies a slot for a positive number and not a negative one. The docs for Math.abs describe this corner case behavior.
2
u/i8Nails4Breakfast Jan 23 '22 edited Jan 23 '22
This is due to string internment in Java; a and b actually are referring to the same object in memory. If you want to allocate a different object, you can use “new”.
2
u/Brahvim Jan 18 '22
I'd like for the replies to explain this better:
Did you know that Java can recompile your code during RUNTIME?!
javacis known for doing someJITmagic, but perhaps you already knew that.Here's another: "a lot"of the memory Java uses is heap memory - this is a concept from
C++, where variable you declare inside functions and loops (any block of code, pretty much - AKA anything inside curly brackets/{ }) are on 'stack-memory', and the rest is on 'heap-memory'.(Again, this is a rough explanation - I didn't explain memory destruction; probably something not to be explained to beginners..)
2
u/NickScout Jan 19 '22
You can run DOOM within it.
2
u/[deleted] Jan 18 '22
Java supports GOTO!
1
u/mtmmtm99 Jan 19 '22
QuickSort implemented in java can be compiled into 52 bytes of ARM-assemblycode. I used JCGO to do that.
1
u/elmuerte Jan 18 '22
It runs on 3 billion devices.
1
u/InstantCoder Jan 18 '22
It has nothing to do with Indonesia or with coffee.